diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown index bb2f91f0dd..3f7cc2db5a 100644 --- a/CHICKEN.html.markdown +++ b/CHICKEN.html.markdown @@ -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") diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown index 5fa1d03d63..455c3256c5 100644 --- a/CONTRIBUTING.markdown +++ b/CONTRIBUTING.markdown @@ -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. diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md index 022dedab6f..96278da98c 100644 --- a/ISSUE_TEMPLATE.md +++ b/ISSUE_TEMPLATE.md @@ -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]' diff --git a/ansible.html.markdown b/ansible.html.markdown new file mode 100644 index 0000000000..a319a89d4b --- /dev/null +++ b/ansible.html.markdown @@ -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 user’s 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. + + diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown index 6a6df96871..a1dfe9e1b4 100644 --- a/asymptotic-notation.html.markdown +++ b/asymptotic-notation.html.markdown @@ -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 n0 (n0 > 0), `f(n)` is < `c g(n)` +`f(n)` is o(g(n)), if for all real constants c (c > 0) and n0 (n0 > 0), `f(n)` is < `c g(n)` for every input size n (n > n0). 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 n0 (n0 > 0), `f(n)` is > `c g(n)` +`f(n)` is ω(g(n)), if for all real constants c (c > 0) and n0 (n0 > 0), `f(n)` is > `c g(n)` for every input size n (n > n0). The definitions of Ω-notation and ω-notation are similar. The main difference diff --git a/awk.html.markdown b/awk.html.markdown index e3ea6318fa..3d2c4ccbee 100644 --- a/awk.html.markdown +++ b/awk.html.markdown @@ -6,14 +6,15 @@ contributors: --- -AWK is a standard tool on every POSIX-compliant UNIX system. It's like a -stripped-down Perl, perfect for text-processing tasks and other scripting -needs. It has a C-like syntax, but without semicolons, manual memory -management, or static typing. It excels at text processing. You can call to it -from a shell script, or you can use it as a stand-alone scripting language. - -Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always -count on it, whereas Perl's future is in question. AWK is also easier to read +AWK is a standard tool on every POSIX-compliant UNIX system. It's like +flex/lex, from the command-line, perfect for text-processing tasks and +other scripting needs. It has a C-like syntax, but without mandatory +semicolons (although, you should use them anyway, because they are required +when you're writing one-liners, something AWK excells at), manual memory +management, or static typing. It excels at text processing. You can call to +it from a shell script, or you can use it as a stand-alone scripting language. + +Why use AWK instead of Perl? Readability. AWK is easier to read than Perl. For simple text-processing scripts, particularly ones that read files line by line and split on delimiters, AWK is probably the right tool for the job. @@ -23,8 +24,23 @@ the job. # Comments are like this -# AWK programs consist of a collection of patterns and actions. The most -# important pattern is called BEGIN. Actions go into brace blocks. + +# AWK programs consist of a collection of patterns and actions. +pattern1 { action; } # just like lex +pattern2 { action; } + +# There is an implied loop and AWK automatically reads and parses each +# record of each file supplied. Each record is split by the FS delimiter, +# which defaults to white-space (multiple spaces,tabs count as one) +# You cann assign FS either on the command line (-F C) or in your BEGIN +# pattern + +# One of the special patterns is BEGIN. The BEGIN pattern is true +# BEFORE any of the files are read. The END pattern is true after +# an End-of-file from the last file (or standard-in if no files specified) +# There is also an output field separator (OFS) that you can assign, which +# defaults to a single space + BEGIN { # BEGIN will run at the beginning of the program. It's where you put all @@ -32,114 +48,116 @@ BEGIN { # have no text files, then think of BEGIN as the main entry point. # Variables are global. Just set them or use them, no need to declare.. - count = 0 + count = 0; # Operators just like in C and friends - a = count + 1 - b = count - 1 - c = count * 1 - d = count / 1 # integer division - e = count % 1 # modulus - f = count ^ 1 # exponentiation - - a += 1 - b -= 1 - c *= 1 - d /= 1 - e %= 1 - f ^= 1 + a = count + 1; + b = count - 1; + c = count * 1; + d = count / 1; # integer division + e = count % 1; # modulus + f = count ^ 1; # exponentiation + + a += 1; + b -= 1; + c *= 1; + d /= 1; + e %= 1; + f ^= 1; # Incrementing and decrementing by one - a++ - b-- + a++; + b--; # As a prefix operator, it returns the incremented value - ++a - --b + ++a; + --b; # Notice, also, no punctuation such as semicolons to terminate statements # Control statements if (count == 0) - print "Starting with count of 0" + print "Starting with count of 0"; else - print "Huh?" + print "Huh?"; # Or you could use the ternary operator - print (count == 0) ? "Starting with count of 0" : "Huh?" + print (count == 0) ? "Starting with count of 0" : "Huh?"; # Blocks consisting of multiple lines use braces while (a < 10) { print "String concatenation is done" " with a series" " of" - " space-separated strings" - print a + " space-separated strings"; + print a; - a++ + a++; } for (i = 0; i < 10; i++) - print "Good ol' for loop" + print "Good ol' for loop"; # As for comparisons, they're the standards: - a < b # Less than - a <= b # Less than or equal - a != b # Not equal - a == b # Equal - a > b # Greater than - a >= b # Greater than or equal + # a < b # Less than + # a <= b # Less than or equal + # a != b # Not equal + # a == b # Equal + # a > b # Greater than + # a >= b # Greater than or equal # Logical operators as well - a && b # AND - a || b # OR + # a && b # AND + # a || b # OR # In addition, there's the super useful regular expression match if ("foo" ~ "^fo+$") - print "Fooey!" + print "Fooey!"; if ("boo" !~ "^fo+$") - print "Boo!" + print "Boo!"; # Arrays - arr[0] = "foo" - arr[1] = "bar" - # Unfortunately, there is no other way to initialize an array. Ya just - # gotta chug through every value line by line like that. - - # You also have associative arrays - assoc["foo"] = "bar" - assoc["bar"] = "baz" + arr[0] = "foo"; + arr[1] = "bar"; + + # You can also initialize an array with the built-in function split() + + n = split("foo:bar:baz", arr, ":"); + + # You also have associative arrays (actually, they're all associative arrays) + assoc["foo"] = "bar"; + assoc["bar"] = "baz"; # And multi-dimensional arrays, with some limitations I won't mention here - multidim[0,0] = "foo" - multidim[0,1] = "bar" - multidim[1,0] = "baz" - multidim[1,1] = "boo" + multidim[0,0] = "foo"; + multidim[0,1] = "bar"; + multidim[1,0] = "baz"; + multidim[1,1] = "boo"; # You can test for array membership if ("foo" in assoc) - print "Fooey!" + print "Fooey!"; # You can also use the 'in' operator to traverse the keys of an array for (key in assoc) - print assoc[key] + print assoc[key]; # The command line is in a special array called ARGV for (argnum in ARGV) - print ARGV[argnum] + print ARGV[argnum]; # You can remove elements of an array # This is particularly useful to prevent AWK from assuming the arguments # are files for it to process - delete ARGV[1] + delete ARGV[1]; # The number of command line arguments is in a variable called ARGC - print ARGC + print ARGC; # AWK has several built-in functions. They fall into three categories. I'll # demonstrate each of them in their own functions, defined later. - return_value = arithmetic_functions(a, b, c) - string_functions() - io_functions() + return_value = arithmetic_functions(a, b, c); + string_functions(); + io_functions(); } # Here's how you define a function @@ -159,26 +177,26 @@ function arithmetic_functions(a, b, c, d) { # Now, to demonstrate the arithmetic functions # Most AWK implementations have some standard trig functions - localvar = sin(a) - localvar = cos(a) - localvar = atan2(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) diff --git a/bash.html.markdown b/bash.html.markdown index 0c097c271d..8c40931ece 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -16,6 +16,7 @@ contributors: - ["Betsy Lorton", "https://github.com/schbetsy"] - ["John Detter", "https://github.com/jdetter"] - ["Harry Mumford-Turner", "https://github.com/harrymt"] + - ["Martin Nicholson", "https://github.com/mn113"] filename: LearnBash.sh --- @@ -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: diff --git a/bf.html.markdown b/bf.html.markdown index 69058a2030..1e415a4d6e 100644 --- a/bf.html.markdown +++ b/bf.html.markdown @@ -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/"] diff --git a/bg-bg/logtalk-bg.html.markdown b/bg-bg/logtalk-bg.html.markdown new file mode 100644 index 0000000000..e788b17db2 --- /dev/null +++ b/bg-bg/logtalk-bg.html.markdown @@ -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) за повече информация. + diff --git a/c++.html.markdown b/c++.html.markdown index 8d1c7a262b..4113d5f42c 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -71,10 +71,16 @@ void func(); // function which may accept any number of arguments // Use nullptr instead of NULL in C++ int* ip = nullptr; -// C standard headers are available in C++, -// but are prefixed with "c" and have no .h suffix. +// C standard headers are available in C++. +// C headers end in .h, while +// C++ headers are prefixed with "c" and have no ".h" suffix. + +// The C++ standard version: #include +//The C standard version: +#include + int main() { printf("Hello, world!\n"); @@ -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 - - -Additional resources may be found at +* 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). diff --git a/c.html.markdown b/c.html.markdown index 87a047bedf..7975a1c264 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -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: +> 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` > -> `-Wall -Wextra -Werror -O0 -ansi -pedantic -std=c11` +> 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 // 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 % diff --git a/chapel.html.markdown b/chapel.html.markdown index e9c4019a3d..354cd832d4 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -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-.tar.gz` + 2. `cd chapel-` 3. `source util/setchplenv.bash # or .sh or .csh or .fish` 4. `make` 5. `make check # optional` diff --git a/citron.html.markdown b/citron.html.markdown new file mode 100644 index 0000000000..bd3c398c46 --- /dev/null +++ b/citron.html.markdown @@ -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 +``` diff --git a/clojure.html.markdown b/clojure.html.markdown index 7830f228b6..c94625d65f 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -150,7 +150,7 @@ x ; => 1 ; You can also use this shorthand to create functions: (def hello2 #(str "Hello " %1)) -(hello2 "Fanny") ; => "Hello Fanny" +(hello2 "Julie") ; => "Hello Julie" ; You can have multi-variadic functions, too (defn hello3 diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 9a23bc2658..b12e50ca57 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -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/) +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. -Another popular and recent book is -[Land of Lisp](http://landoflisp.com/). +```lisp -```common_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 +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 -:THING ;Another atom; evaluating to the symbol :thing. -t ; another atom, denoting true. +;;; Comments -(+ 1 2 3 4) ; an s-expression +;;; 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, -'(4 :foo t) ;another one +;;;; life.lisp +;;; Foo bar baz, because quu quux. Optimized for maximum krakaboom and umph. +;;; Needed by the function LINULUKO. -;;; Comments +(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 -;; Single line comments start with a semicolon; use two for normal -;; comments, three for section comments, and four for file-level -;; comments. +;;; Block comments, on the other hand, allow for free-form comments. They are +;;; delimited with #| and |# -#| Block comments - can span multiple lines 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. + +(+ 1 2) ; => 3 + +;;; If you want to create literal data, use QUOTE to prevent it from being +;;; evaluated + +(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 -;; 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) - - ;;; 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 - - ;;; Characters -#\A ; => #\A -#\λ ; => #\GREEK_SMALL_LETTER_LAMDA -#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA - -;;; 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. + +(format nil "~A, ~A!" "Hello" "world") ; => "Hello, world!" +(format t "~A, ~A!" "Hello" "world") ; => NIL -;; Printing is pretty easy; ~% is the format specifier for newline. -(format t "Common Lisp is groovy. Dude.~%") +;;;----------------------------------------------------------------------------- +;;; 2. Variables +;;;----------------------------------------------------------------------------- -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 2. Variables -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; You can create a global (dynamically scoped) using defparameter -;; a variable name can use any character except: ()",'`;#|\ +;;; You can create a global (dynamically scoped) variable using DEFVAR and +;;; DEFPARAMETER. The variable name can use any character except: ()",'`;#|\ -;; Dynamically scoped variables should have earmuffs in their name! +;;; 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. + +;;; 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. -;; Accessing a previously unbound variable is an -;; undefined behavior (but possible). Don't do it. +(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 + +(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) -;; Can still use `cons' to add an item to the beginning of a list -(cons 4 '(1 2 3)) ; => '(4 1 2 3) +;;; 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 -;; Use `append' to - surprisingly - append lists together -(append '(1 2) '(3 4)) ; => '(1 2 3 4) +(cons 4 '(1 2 3)) ; => '(4 1 2 3) -;; Or use concatenate - +;;; Use APPEND to join lists -(concatenate 'list '(1 2) '(3 4)) +(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))) +(aref (make-array (list 2 2 2)) 1 1 1) ; => 0 +;;; This value is implementation-defined: +;;; NIL on ECL, 0 on SBCL and CCL. -;; Caution- the default initial values are -;; implementation-defined. Here's how to define them: +;;; Adjustable vectors -(make-array '(2) :initial-element 'unset) +;;; Adjustable vectors have the same printed representation as +;;; fixed-length vector's literals. -; => #(UNSET UNSET) +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) +*adjvec* ; => #(1 2 3) -;; And, to access the element at 1,1,1 - -(aref (make-array (list 2 2 2)) 1 1 1) +;;; Adding new elements -; => 0 +(vector-push-extend 4 *adjvec*) ; => 3 +*adjvec* ; => #(1 2 3 4) -;;; Adjustable vectors -;; Adjustable vectors have the same printed representation -;; as fixed-length vector's literals. +;;; Sets, naively, are just lists: -(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) - :adjustable t :fill-pointer t)) +(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) -*adjvec* ; => #(1 2 3) +;;; 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 -;; Adding new element: -(vector-push-extend 4 *adjvec*) ; => 3 +(defparameter *m* (make-hash-table)) -*adjvec* ; => #(1 2 3 4) +;;; Set value +(setf (gethash 'a *m*) 1) +;;; Retrieve value -;;; Naively, sets are just lists: +(gethash 'a *m*) ; => 1, T -(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) +;;; CL expressions have the ability to return multiple values. -;; But you'll want to use a better data structure than a linked list -;; for performant work! +(values 1 2) ; => 1, 2 -;;; Dictionaries are implemented as hash tables. +;;; which can be bound with MULTIPLE-VALUE-BIND -;; Create a hash table -(defparameter *m* (make-hash-table)) +(multiple-value-bind (x y) + (values 1 2) + (list y x)) -;; set a value -(setf (gethash 'a *m*) 1) +; => '(2 1) -;; Retrieve a value -(gethash 'a *m*) ; => 1, t +;;; 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. -;; Detail - Common Lisp has multiple return values possible. gethash -;; returns t in the second value if anything was found, and nil if -;; not. +;;; 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 +;;; 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") ; => # -;; Use funcall to call lambda functions -(funcall (lambda () "Hello World")) ; => "Hello World" +;;; Use FUNCALL to call anonymous functions + +(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 -;; Or Apply +((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 - -;; And the defaults can be set... -(defun hello (name &optional (from "The world")) - (format t "Hello, ~a, from ~a" name from)) +(hello "Jim" "Alpacas") ; => Hello, Jim, from Alpacas -(hello "Steve") -; => Hello, Steve, from The world +;;; The default values can also be specified -(hello "Steve" "the alpacas") -; => Hello, Steve, from the alpacas +(defun hello (name &optional (from "The world")) + (format nil "Hello, ~A, from ~A" name from)) +(hello "Steve") ; => Hello, Steve, from The world +(hello "Steve" "the alpacas") ; => Hello, Steve, from the alpacas -;; 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 +;;;----------------------------------------------------------------------------- + +;;; CL has a sophisticated equality system. Some are covered here. + +;;; For numbers, use `=' +(= 3 3.0) ; => T +(= 2 1) ; => NIL -;; for numbers use `=' -(= 3 3.0) ; => t -(= 2 1) ; => nil +;;; For object identity (approximately) use EQL +(eql 3 3) ; => T +(eql 3 3.0) ; => NIL +(eql (list 3) (list 3)) ; => NIL -;; for object identity (approximately) use `eql` -(eql 3 3) ; => t -(eql 3 3.0) ; => nil -(eql (list 3) (list 3)) ; => 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 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 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;;----------------------------------------------------------------------------- +;;; 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 -;;; Iteration -;; Of course recursion is supported: +;;; Looping -(defun walker (n) - (if (zerop n) - :walked - (walker (- n 1)))) +;;; Recursion -(walker 5) ; => :walked +(defun fact (n) + (if (< n 2) + 1 + (* n (fact(- n 1))))) -;; Most of the time, we use DOLIST or LOOP +(fact 5) ; => 120 +;;; Iteration -(dolist (i '(1 2 3 4)) - (format t "~a" i)) +(defun fact (n) + (loop :for result = 1 :then (* result i) + :for i :from 2 :to n + :finally (return result))) -; => 1234 +(fact 5) ; => 120 -(loop for i from 0 below 10 - collect i) +(loop :for x :across "abcd" :collect x) +; => (#\a #\b #\c #\d) -; => (0 1 2 3 4 5 6 7 8 9) +(dolist (i '(1 2 3 4)) + (format t "~A" i)) +; => 1234 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 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 + +- [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) -* [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) +## Extra information -## Extra Info +- [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/) -* [CLiki](http://www.cliki.net/) -* [common-lisp.net](https://common-lisp.net/) -* [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) -## Credits. +## Credits Lots of thanks to the Scheme people for rolling up a great starting point which could be easily moved to Common Lisp. diff --git a/crystal.html.markdown b/crystal.html.markdown index 15cbc0b1ef..8210b443bd 100644 --- a/crystal.html.markdown +++ b/crystal.html.markdown @@ -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 diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown index f19f9e8bff..42ec89e576 100644 --- a/cs-cz/elm.html.markdown +++ b/cs-cz/elm.html.markdown @@ -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". diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index cbf7687e07..c05a9138f1 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -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 mě, 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 *až do* 32 bitů 1 << 2; // = 4 // Přednost se vynucuje závorkami. (1 + 3) * 2; // = 8 -// Existují 3 hodnoty mimo obor reálných čísel +// Existují 3 hodnoty mimo obor reálných čísel: Infinity; // + nekonečno; výsledek např. 1/0 -Infinity; // - nekonečno; výsledek např. -1/0 NaN; // výsledek např. 0/0, znamená, že výsledek není číslo ('Not a Number') -// Také existují hodnoty typu bool +// Také existují hodnoty typu boolean. true; // pravda false; // nepravda -// Řetězce znaků jsou obaleny ' nebo ". +// Řetězce znaků jsou obaleny ' nebo ". 'abc'; -"Ahoj světe!"; +"Hello, world"; -// Negace se tvoří pomocí ! +// Negace se tvoří pomocí znaku ! !true; // = false !false; // = true -// Rovnost se porovnává === +// Rovnost se porovnává pomocí === 1 === 1; // = true 2 === 1; // = false @@ -103,16 +98,16 @@ false; // nepravda 2 >= 2; // = true // Řetězce znaků se spojují pomocí + -"Ahoj " + "světe!"; // = "Ahoj světe!" +"Hello " + "world!"; // = "Hello world!" -// ... což funguje nejenom s řetězci +// ... což funguje nejen s řetězci "1, 2, " + 3; // = "1, 2, 3" -"Ahoj " + ["světe", "!"] // = "Ahoj světe,!" +"Hello " + ["world", "!"]; // = "Hello world,!" // a porovnávají se pomocí < nebo > "a" < "b"; // = true -// Rovnost s převodem typů se dělá pomocí == ... +// Rovnost s převodem typů se dělá za pomoci dvojitého rovnítka... "5" == 5; // = true null == undefined; // = true @@ -124,24 +119,24 @@ null === undefined; // = false 13 + !0; // 14 "13" + !0; // '13true' -// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí charAt` +// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí `charAt` "Toto je řetězec".charAt(0); // = 'T' -// ...nebo použít `substring` k získání podřetězce -"Ahoj světe".substring(0, 4); // = "Ahoj" +// ...nebo použít `substring` k získání podřetězce. +"Hello world".substring(0, 5); // = "Hello" -// `length` znamená délka a je to vlastnost, takže nepoužívejte () -"Ahoj".length; // = 4 +// `length` znamená délka a je to vlastnost, takže nepoužívejte (). +"Hello".length; // = 5 // Existují také typy `null` a `undefined`. -null; // značí, že žádnou hodnotu -undefined; // značí, že hodnota nebyla definovaná (ikdyž +null; // obvykle označuje něco záměrně bez hodnoty +undefined; // obvykle označuje, že hodnota není momentálně definovaná (ačkoli // `undefined` je hodnota sama o sobě) -// false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní -// vrací pravdu (true).. -// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, ikdyž 0 == "0" -// vrací pravdu +// 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 +// Přidání nebo odebrání člena ze začátku nebo konce pole +myArray.unshift(3); // Přidej jako první člen +someVar = myArray.shift(); // Odstraň prvního člena a vrať jeho hodnotu +myArray.push(3); // Přidej jako poslední člen +someVar = myArray.pop(); // Odstraň posledního člena a vrať jeho hodnotu + +// Spoj všechny členy pole středníkem +var myArray0 = [32,false,"js",12,56,90]; +myArray0.join(";") // = "32;false;js;12;56;90" + +// Vrať část pole s elementy od pozice 1 (včetně) do pozice 4 (nepočítaje) +myArray0.slice(1,4); // = [false,"js",12] + +// Odstraň čtyři členy od pozice 2, vlož následující +// "hi","wr" and "ld"; vrať odstraněné členy +myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90] +// myArray0 === [32,false,"hi","wr","ld"] + +// JavaScriptové objekty jsou stejné jako asociativní pole v jiných programovacích // jazycích: je to neuspořádaná množina páru hodnot - klíč:hodnota. -var mujObjekt = {klic1: "Ahoj", klic2: "světe"}; +var mujObjekt = {klic1: "Hello", klic2: "World"}; -// Klíče jsou řetězce, ale nejsou povinné uvozovky, pokud jsou validní -// JavaScriptové identifikátory. Hodnoty můžou být jakéhokoliv typu- +// Klíče jsou řetězce, ale nemusí mít povinné uvozovky, pokud jsou validními +// JavaScriptovými identifikátory. Hodnoty můžou být jakéhokoliv typu. var mujObjekt = {klic: "mojeHodnota", "muj jiny klic": 4}; // K hodnotám můžeme přistupovat opět pomocí hranatých závorek -myObj["muj jiny klic"]; // = 4 +mujObjekt["muj jiny klic"]; // = 4 // ... nebo pokud je klíč platným identifikátorem, můžeme přistupovat k // hodnotám i přes tečku mujObjekt.klic; // = "mojeHodnota" // Objekty jsou měnitelné, můžeme upravit hodnoty, nebo přidat nové klíče. -myObj.mujDalsiKlic = true; +mujObjekt.mujDalsiKlic = true; -// Pokud se snažíte přistoupit ke klíči, který není nastaven, dostanete undefined -myObj.dalsiKlic; // = undefined +// Pokud se snažíte přistoupit ke klíči, který neexistuje, dostanete undefined. +mujObjekt.dalsiKlic; // = undefined /////////////////////////////////// // 3. Řízení toku programu -// Syntaxe pro tuto sekci je prakticky stejná jako pro Javu - -// `if` (když) funguje, jak byste čekali. +// Funkce `if` funguje, jak byste čekali. var pocet = 1; if (pocet == 3){ // provede, když se pocet rovná 3 } 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 -var popis = ""; -var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18}; -for (var x in osoba){ - popis += osoba[x] + " "; +// Opuštění cyklu s návěštím je podobné jako v Javě +outer: +for (var i = 0; i < 10; i++) { + for (var j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // opustí vnější (outer) cyklus místo pouze vnitřního (inner) cyklu + } + } } -//Když chcete iterovat přes vlastnosti, které jsou přímo na objektu a nejsou -//zděněné z prototypů, kontrolujte vlastnosti přes hasOwnProperty() +// Cyklus For-in iteruje přes každou vlastnost prototypu var popis = ""; -var osoba = {prijmeni:"Jan", jmeno:"Novák", vek:18}; +var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18}; for (var x in osoba){ - if (osoba.hasOwnProperty(x)){ - popis += osoba[x] + " "; - } -} + popis += osoba[x] + " "; +} // popis = 'Paul Ken 18 ' -// for-in by neměl být použit pro pole, pokud záleží na pořadí indexů. -// Neexistuje jistota, že for-in je vrátí ve správném pořadí. +// Příkaz for/of umožňuje iterovat iterovatelné objekty (včetně vestavěných typů +// String, Array, například polím podobným argumentům nebo NodeList objektům, +// TypeArray, Map a Set, či uživatelsky definované iterovatelné objekty). +var myPets = ""; +var pets = ["cat", "dog", "hamster", "hedgehog"]; +for (var pet of pets){ + myPets += pet + " "; +} // myPets = 'cat dog hamster hedgehog ' // && je logické a, || je logické nebo if (dum.velikost == "velký" && dum.barva == "modrá"){ dum.obsahuje = "medvěd"; } if (barva == "červená" || barva == "modrá"){ - // barva je červená nebo modtrá + // barva je červená nebo modrá } // && a || jsou praktické i pro nastavení základních hodnot 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ázá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][4] +je varianta tohoto návodu i s úkoly. + +[JavaScript Garden][5] je sbírka příkladů těch nejnepředvídatelnějších částí +tohoto jazyka. + +[JavaScript: The Definitive Guide][6] je klasická výuková kniha. + +[Eloquent Javascript][8] od Marijn Haverbeke je výbornou JS knihou/e-knihou. -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) je varianta tohoto -návodu i s úkoly- +[Javascript: The Right Way][10] je průvodcem JavaScriptem pro začínající +vývojáře i pomocníkem pro zkušené vývojáře, kteří si chtějí prohloubit své +znalosti. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) je sbírka -příkladů těch nejvíce nepředvídatelných částí tohoto jazyka. +[Javascript:Info][11] je moderním JavaScriptovým průvodcem, který pokrývá +základní i pokročilé témata velice výstižným výkladem. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) -je klasická výuková kniha. +Jako dodatek k přímým autorům tohoto článku byly na těchto stránkách části +obsahu převzaty z Pythonního tutoriálu Louiho Dinha, a tak0 z [JS Tutorial][7] +na stránkách Mozilla Developer Network. -Jako dodatek k přímým autorům tohoto článku, některý obsah byl přizpůsoben z -Pythoního tutoriálu od Louie Dinh na této stráce, a z [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -z Mozilla Developer Network. +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[8]: http://eloquentjavascript.net/ +[10]: http://jstherightway.org/ +[11]: https://javascript.info/ diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 568e434356..35becf9452 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -13,7 +13,7 @@ Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce či a psatelná syntaxe, která je jednoduše převeditelná do HTML (a dnes i do mnoha dalších formátů) -```markdown +```md +``` + +## En-têtes + +Vous pouvez facilement créer des balises HTML `

` à `

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

+## Ceci est un

+### Ceci est un

+#### Ceci est un

+##### Ceci est un

+###### Ceci est un
+``` + +Markdown fournit également une façon alternative de marquer les `

` et `

` + +```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 `
`, 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
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 ``), 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 + est équivalent à : +[http://testwebsite.com/](http://testwebsite.com/) +``` + +### Liens Automatiques pour emails + +```md + +``` + +### 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 `` +pour représenter une touche du clavier. + +```md +Ton ordinateur a planté? Essayer de taper : +Ctrl+Alt+Del +``` + +### Tableaux + +Les tableaux ne sont disponibles que dans le "GitHub Flavored Markdown" et +ne sont pas tres agréable d'utilisation. Mais si vous en avez besoin : + +```md +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| Alignement Gauche | Centé | Alignement Droite | +| bla | bla | bla | +``` + +ou bien, pour un résultat équivalent : + +```md +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ough que c'est moche | svp | arrêtez +``` + +Pour plus d'information, consultez le post officiel de Jhon Gruber à propos de +la syntaxe [ici](http://daringfireball.net/projects/markdown/syntax) et la +superbe fiche pense-bête de Adam Pritchard [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown deleted file mode 100644 index 2e4e8461b9..0000000000 --- a/fr-fr/markdown.html.markdown +++ /dev/null @@ -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 - - - - - - - - -# Ceci est un

-## Ceci est un

-### Ceci est un

-#### Ceci est un

-##### Ceci est un

-###### Ceci est un
- - - -Ceci est un h1 -============= - -Ceci est un h2 -------------- - - - - -*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à!__* - - - -~~Ce texte est barré avec strikethrough.~~ - - - -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! - - - -J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). - -Bigre, il y a un
au dessus de moi! - - - -> 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? - - - - -* Item -* Item -* Un autre item - -ou - -+ Item -+ Item -+ Encore un item - -ou - -- Item -- Item -- Un dernier item - - - -1. Item un -2. Item deux -3. Item trois - - - -1. Item un -1. Item deux -1. Item trois - - - - -1. Item un -2. Item deux -3. Item trois -* Sub-item -* Sub-item -4. Item quatre - - - -Les [ ] ci dessous, n'ayant pas de [ x ], -deviendront des cases à cocher HTML non-cochées. - -- [ ] Première tache à réaliser. -- [ ] Une autre chose à faire. -La case suivante sera une case à cocher HTML cochée. -- [x] Ça ... c'est fait! - - - - - echo "Ça, c'est du Code!"; - var Ça = "aussi !"; - - - - my_array.each do |item| - puts item - end - - - -La fonction `run()` ne vous oblige pas à aller courir! - - - -\`\`\`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 ``` --> - - - - -*** ---- -- - - -**************** - - - - -[Clic moi!](http://test.com/) - - - -[Clic moi!](http://test.com/ "Lien vers Test.com") - - - -[En avant la musique](/music/). - - - -[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!" - - - - - -[Ceci][] est un lien. - -[ceci]: http://ceciestunlien.com/ - - - - - - -![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") - - - -![Ceci est l'attribut ALT de l'image][monimage] - -[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." - - - - - est équivalent à : -[http://testwebsite.com/](http://testwebsite.com/) - - - - - - -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\*. - - - - -| Col1 | Col2 | Col3 | -| :----------- | :------: | ------------: | -| Alignement Gauche | Centé | Alignement Droite | -| bla | bla | bla | - - - -Col 1 | Col2 | Col3 -:-- | :-: | --: -Ough que c'est moche | svp | arrêtez - - - -``` - -Pour plus d'information : - consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, - et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. diff --git a/fr-fr/php.html.markdown b/fr-fr/php-fr.html.markdown similarity index 89% rename from fr-fr/php.html.markdown rename to fr-fr/php-fr.html.markdown index 823630bd4e..45a02d754c 100644 --- a/fr-fr/php.html.markdown +++ b/fr-fr/php-fr.html.markdown @@ -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 ' '$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 = << '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) */ diff --git a/fr-fr/pyqt-fr.html.markdown b/fr-fr/pyqt-fr.html.markdown new file mode 100644 index 0000000000..6da9a38079 --- /dev/null +++ b/fr-fr/pyqt-fr.html.markdown @@ -0,0 +1,85 @@ +--- +category: tool +tool: PyQT +filename: learnpyqt-fr.py +contributors: + - ["Nathan Hughes", "https://github.com/sirsharpest"] +translators: + - ["DevHugo", "http://twitter.com/devhugo"] +lang: fr-fr +--- + +**Qt** est un framework très connu pour le développement de logiciel cross-platform qui peuvent être lancé sur différents systèmes avec de petit ou aucun changement dans le code, tout en ayant la puissance et la vitesse des applications natives. Bien que **Qt** ait été écrit à l'origine en *C++*. + + +Ceci est une adaptation de l'intro C++ à QT par [Aleksey Kholovchuk](https://github.com/vortexxx192 +), certains exemples du code doivent avoir la même fonctionnalité, +cette version ayant juste été faite en utilisant pyqt! + +```python +import sys +from PyQt4 import QtGui + +def window(): + # Création de l'objet application + app = QtGui.QApplication(sys.argv) + # Création d'un widget où notre label sera placé + w = QtGui.QWidget() + # Ajout d'un label au widget + b = QtGui.QLabel(w) + # Assignation de texte au label + b.setText("Hello World!") + # Assignation des tailles et des informations de placement + w.setGeometry(100, 100, 200, 50) + b.move(50, 20) + # Assignation d'un nom à notre fenêtre + w.setWindowTitle("PyQt") + # Affichage de la fenêtre + w.show() + # Exécution de l'application + sys.exit(app.exec_()) + +if __name__ == '__main__': + window() + +``` + +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() +``` diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala-fr.html.markdown similarity index 100% rename from fr-fr/scala.html.markdown rename to fr-fr/scala-fr.html.markdown diff --git a/fr-fr/vim.html.markdown b/fr-fr/vim-fr.html.markdown similarity index 100% rename from fr-fr/vim.html.markdown rename to fr-fr/vim-fr.html.markdown diff --git a/fsharp.html.markdown b/fsharp.html.markdown index bbf477baf2..59461eed51 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -34,7 +34,7 @@ let myFloat = 3.14 let myString = "hello" // note that no types needed // ------ Lists ------ -let twoToFive = [2; 3; 4; 5] // Square brackets create a list with +let twoToFive = [2; 3; 4; 5] // Square brackets create a list with // semicolon delimiters. let oneToFive = 1 :: twoToFive // :: creates list with new 1st element // The result is [1; 2; 3; 4; 5] @@ -53,7 +53,8 @@ add 2 3 // Now run the function. // to define a multiline function, just use indents. No semicolons needed. let evens list = - let isEven x = x % 2 = 0 // Define "isEven" as a sub function + let isEven x = x % 2 = 0 // Define "isEven" as a sub function. Note + // that equality operator is single char "=". List.filter isEven list // List.filter is a library function // with two parameters: a boolean function // and a list to work on @@ -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 diff --git a/git.html.markdown b/git.html.markdown index 582f88630c..aa96c90a52 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -26,11 +26,11 @@ Version control is a system that records changes to a file(s), over time. ### Centralized Versioning vs. Distributed Versioning -* Centralized version control focuses on synchronizing, tracking, and backing +* Centralized version control focuses on synchronizing, tracking, and backing up files. -* Distributed version control focuses on sharing changes. Every change has a +* Distributed version control focuses on sharing changes. Every change has a unique id. -* Distributed systems have no defined structure. You could easily have a SVN +* Distributed systems have no defined structure. You could easily have a SVN style, centralized system, with git. [Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -57,7 +57,7 @@ A git repository is comprised of the .git directory & working tree. ### .git Directory (component of repository) -The .git directory contains all the configurations, logs, branches, HEAD, and +The .git directory contains all the configurations, logs, branches, HEAD, and more. [Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) @@ -68,15 +68,15 @@ referred to as your working directory. ### Index (component of .git dir) -The Index is the staging area in git. It's basically a layer that separates -your working tree from the Git repository. This gives developers more power +The Index is the staging area in git. It's basically a layer that separates +your working tree from the Git repository. This gives developers more power over what gets sent to the Git repository. ### Commit -A git commit is a snapshot of a set of changes, or manipulations to your -Working Tree. For example, if you added 5 files, and removed 2 others, these -changes will be contained in a commit (or snapshot). This commit can then be +A git commit is a snapshot of a set of changes, or manipulations to your +Working Tree. For example, if you added 5 files, and removed 2 others, these +changes will be contained in a commit (or snapshot). This commit can then be pushed to other repositories, or not! ### Branch @@ -91,13 +91,13 @@ functionality to mark release points (v1.0, and so on) ### HEAD and head (component of .git dir) -HEAD is a pointer that points to the current branch. A repository only has 1 -*active* HEAD. -head is a pointer that points to any commit. A repository can have any number +HEAD is a pointer that points to the current branch. A repository only has 1 +*active* HEAD. +head is a pointer that points to any commit. A repository can have any number of heads. ### Stages of Git -* Modified - Changes have been made to a file but file has not been committed +* Modified - Changes have been made to a file but file has not been committed to Git Database yet * Staged - Marks a modified file to go into your next commit snapshot * Committed - Files have been committed to the Git Database @@ -111,7 +111,7 @@ to Git Database yet ### init -Create an empty Git repository. The Git repository's settings, stored +Create an empty Git repository. The Git repository's settings, stored information, and more is stored in a directory (a folder) named ".git". ```bash @@ -179,7 +179,7 @@ $ git help status ### add -To add files to the staging area/index. If you do not `git add` new files to +To add files to the staging area/index. If you do not `git add` new files to the staging area/index, they will not be included in commits! ```bash @@ -201,7 +201,7 @@ working directory/repo. ### branch -Manage your branches. You can view, edit, create, delete branches using this +Manage your branches. You can view, edit, create, delete branches using this command. ```bash @@ -250,7 +250,7 @@ $ git push origin --tags ### checkout -Updates all files in the working tree to match the version in the index, or +Updates all files in the working tree to match the version in the index, or specified tree. ```bash @@ -269,7 +269,7 @@ $ git checkout -b newBranch ### clone Clones, or copies, an existing repository into a new directory. It also adds -remote-tracking branches for each branch in the cloned repo, which allows you +remote-tracking branches for each branch in the cloned repo, which allows you to push to a remote branch. ```bash @@ -285,7 +285,7 @@ $ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git - ### commit -Stores the current contents of the index in a new "commit." This commit +Stores the current contents of the index in a new "commit." This commit contains the changes made and a message created by the user. ```bash @@ -401,11 +401,11 @@ Pulls from a repository and merges it with another branch. $ git pull origin master # By default, git pull will update your current branch -# by merging in new changes from its remote-tracking branch +# by merging in new changes from its remote-tracking branch $ git pull # Merge in changes from remote branch and rebase -# branch commits onto your local repo, like: "git fetch , git +# branch commits onto your local repo, like: "git fetch , git # rebase /" $ git pull origin master --rebase ``` @@ -421,7 +421,7 @@ Push and merge changes from a branch to a remote & branch. $ git push origin master # By default, git push will push and merge changes from -# the current branch to its remote-tracking branch +# the current branch to its remote-tracking branch $ git push # To link up current local branch with a remote branch, add -u flag: @@ -432,7 +432,7 @@ $ git push ### stash -Stashing takes the dirty state of your working directory and saves it on a +Stashing takes the dirty state of your working directory and saves it on a stack of unfinished changes that you can reapply at any time. Let's say you've been doing some work in your git repo, but you want to pull @@ -464,7 +464,7 @@ nothing to commit, working directory clean ``` You can see what "hunks" you've stashed so far using `git stash list`. -Since the "hunks" are stored in a Last-In-First-Out stack, our most recent +Since the "hunks" are stored in a Last-In-First-Out stack, our most recent change will be at top. ```bash @@ -495,7 +495,7 @@ Now you're ready to get back to work on your stuff! ### rebase (caution) -Take all changes that were committed on one branch, and replay them onto +Take all changes that were committed on one branch, and replay them onto another branch. *Do not rebase commits that you have pushed to a public repo*. @@ -510,7 +510,7 @@ $ git rebase master experimentBranch ### reset (caution) Reset the current HEAD to the specified state. This allows you to undo merges, -pulls, commits, adds, and more. It's a great command but also dangerous if you +pulls, commits, adds, and more. It's a great command but also dangerous if you don't know what you are doing. ```bash @@ -535,7 +535,7 @@ $ git reset --hard 31f2bb1 Reflog will list most of the git commands you have done for a given time period, default 90 days. -This give you the chance to reverse any git commands that have gone wrong +This give you the chance to reverse any git commands that have gone wrong (for instance, if a rebase has broken your application). You can do this: @@ -558,8 +558,8 @@ ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) ### revert -Revert can be used to undo a commit. It should not be confused with reset which -restores the state of a project to a previous point. Revert will add a new +Revert can be used to undo a commit. It should not be confused with reset which +restores the state of a project to a previous point. Revert will add a new commit which is the inverse of the specified commit, thus reverting it. ```bash @@ -604,3 +604,5 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Pro Git](http://www.git-scm.com/book/en/v2) * [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + +* [The New Boston tutorial to Git covering basic commands and workflow](https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAKWClAD_iKpNC0bGHxGhcx) diff --git a/go.html.markdown b/go.html.markdown index e5263cf648..ae99535bee 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -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 diff --git a/haskell.html.markdown b/haskell.html.markdown index 266cf11b0a..90d47c2791 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -124,6 +124,9 @@ last [1..5] -- 5 fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 +-- pair element accessing does not work on n-tuples (i.e. triple, quadruple, etc) +snd ("snd", "can't touch this", "da na na na") -- error! see function below + ---------------------------------------------------- -- 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 diff --git a/haxe.html.markdown b/haxe.html.markdown index df2a1e7850..afb9d1a3fd 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -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). diff --git a/hre.csv b/hre.csv new file mode 100644 index 0000000000..eab43cc4b5 --- /dev/null +++ b/hre.csv @@ -0,0 +1 @@ +Ix,Dynasty,Name,Birth,Death,Coronation 1,Coronation 2,Ceased to be Emperor N/A,Carolingian,Charles I,2 April 742,28 January 814,25 December 800,N/A,28 January 814 N/A,Carolingian,Louis I,778,20 June 840,11 September 813,5 October 816,20 June 840 N/A,Carolingian,Lothair I,795,29 September 855,5 April 823,N/A,29 September 855 N/A,Carolingian,Louis II,825,12 August 875,15 June 844,18 May 872,12 August 875 N/A,Carolingian,Charles II,13 June 823,6 October 877,29 December 875,N/A,6 October 877 N/A,Carolingian,Charles III,13 June 839,13 January 888,12 February 881,N/A,11 November 887 N/A,Widonid,Guy III,835,12 December 894,21 February 891,N/A,12 December 894 N/A,Widonid,Lambert I,880,15 October 898,30 April 892,N/A,15 October 898 N/A,Carolingian,Arnulph,850,8 December 899,22 February 896,N/A,8 December 899 N/A,Bosonid,Louis III,880,5 June 928,22 February 901,N/A,21 July 905 N/A,Unruoching,Berengar I,845,7 April 924,December 915,N/A,7 April 924 1,Ottonian,Otto I,23 November 912,7 May 973,2 February 962,N/A,7 May 973 2,Ottonian,Otto II,955,7 December 983,25 December 967,N/A,7 December 983 3,Ottonian,Otto III,980,23 January 1002,21 May 996,N/A,23 January 1002 4,Ottonian,Henry II,6 May 973,13 July 1024,14 February 1014,N/A,13 July 1024 5,Salian,Conrad II,990,4 June 1039,26 March 1027,N/A,4 June 1039 6,Salian,Henry III,29 October 1017,5 October 1056,25 December 1046,N/A,5 October 1056 7,Salian,Henry IV,11 November 1050,7 August 1106,31 March 1084,N/A,December 1105 8,Salian,Henry V,8 November 1086,23 May 1125,13 April 1111,N/A,23 May 1125 9,Supplinburg,Lothair III,9 June 1075,4 December 1137,4 June 1133,N/A,4 December 1137 10,Staufen,Frederick I,1122,10 June 1190,18 June 1155,N/A,10 June 1190 11,Staufen,Henry VI,November 1165,28 September 1197,14 April 1191,N/A,28 September 1197 12,Welf,Otto IV,1175,19 May 1218,4 October 1209,N/A,1215 13,Staufen,Frederick II,26 December 1194,13 December 1250,22 November 1220,N/A,13 December 1250 14,Luxembourg,Henry VII,1275,24 August 1313,29 June 1312,N/A,24 August 1313 15,Wittelsbach,Louis IV,1 April 1282,11 October 1347,17 January 1328,N/A,11 October 1347 16,Luxembourg,Charles IV,14 May 1316,29 November 1378,5 April 1355,N/A,29 November 1378 17,Luxembourg,Sigismund,14 February 1368,9 December 1437,31 May 1433,N/A,9 December 1437 18,Habsburg,Frederick III,21 September 1415,19 August 1493,19 March 1452,N/A,19 August 1493 19,Habsburg,Maximilian I,22 March 1459,12 January 1519,N/A,N/A,12 January 1519 20,Habsburg,Charles V,24 February 1500,21 September 1558,February 1530,N/A,16 January 1556 21,Habsburg,Ferdinand I,10 March 1503,25 July 1564,N/A,N/A,25 July 1564 22,Habsburg,Maximilian II,31 July 1527,12 October 1576,N/A,N/A,12 October 1576 23,Habsburg,Rudolph II,18 July 1552,20 January 1612,30 June 1575,N/A,20 January 1612 24,Habsburg,Matthias,24 February 1557,20 March 1619,23 January 1612,N/A,20 March 1619 25,Habsburg,Ferdinand II,9 July 1578,15 February 1637,10 March 1619,N/A,15 February 1637 26,Habsburg,Ferdinand III,13 July 1608,2 April 1657,18 November 1637,N/A,2 April 1657 27,Habsburg,Leopold I,9 June 1640,5 May 1705,6 March 1657,N/A,5 May 1705 28,Habsburg,Joseph I,26 July 1678,17 April 1711,1 May 1705,N/A,17 April 1711 29,Habsburg,Charles VI,1 October 1685,20 October 1740,22 December 1711,N/A,20 October 1740 30,Wittelsbach,Charles VII,6 August 1697,20 January 1745,12 February 1742,N/A,20 January 1745 31,Lorraine,Francis I,8 December 1708,18 August 1765,N/A,N/A,18 August 1765 32,Habsburg-Lorraine,Joseph II,13 March 1741,20 February 1790,19 August 1765,N/A,20 February 1790 33,Habsburg-Lorraine,Leopold II,5 May 1747,1 March 1792,N/A,N/A,1 March 1792 34,Habsburg-Lorraine,Francis II,12 February 1768,2 March 1835,4 March 1792,N/A,6 August 1806 \ No newline at end of file diff --git a/html.html.markdown b/html.html.markdown index 3c855b5c73..04b9f50129 100644 --- a/html.html.markdown +++ b/html.html.markdown @@ -1,6 +1,6 @@ --- language: html -filename: learnhtml.html +filename: learnhtml.txt contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: @@ -111,7 +111,7 @@ This article is concerned principally with HTML syntax and some useful tips. ## Usage -HTML is written in files ending with `.html`. +HTML is written in files ending with `.html` or `.htm`. The mime type is `text/html`. ## To Learn More diff --git a/hu-hu/python-hu.html.markdown b/hu-hu/python-hu.html.markdown new file mode 100644 index 0000000000..9b55f8e2f5 --- /dev/null +++ b/hu-hu/python-hu.html.markdown @@ -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) diff --git a/id-id/bf-id.html.markdown b/id-id/bf-id.html.markdown new file mode 100644 index 0000000000..bf2f6a099d --- /dev/null +++ b/id-id/bf-id.html.markdown @@ -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. + diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown index 06ad1092d4..1ff1963b98 100644 --- a/id-id/markdown.html.markdown +++ b/id-id/markdown.html.markdown @@ -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 Potete creare gli elementi HTML da `

` a `

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

## Questo è un

### Questo è un

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

` a `

` facilmente, basta che inseria ``` Markdown inoltre fornisce due alternative per indicare gli elementi h1 e h2 -```markdown +```md Questo è un h1 ============== @@ -60,7 +60,7 @@ Questo è un h2 ## Stili di testo semplici Il testo può essere stilizzato in corsivo o grassetto usando markdown -```markdown +```md *Questo testo è in corsivo.* _Come pure questo._ @@ -74,12 +74,12 @@ __Come pure questo.__ In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su Github, è presente anche lo stile barrato: -```markdown +```md ~~Questo testo è barrato.~~ ``` ## Paragrafi -```markdown +```md I paragrafi sono una o più linee di testo adiacenti separate da una o più righe vuote. Questo è un paragrafo. Sto scrivendo in un paragrafo, non è divertente? @@ -93,7 +93,7 @@ Qui siamo nel paragrafo 3! Se volete inserire l'elemento HTML `
`, potete terminare la linea con due o più spazi e poi iniziare un nuovo paragrafo. -```markdown +```md Questa frase finisce con due spazi (evidenziatemi per vederli). C'è un
sopra di me! @@ -101,7 +101,7 @@ C'è un
sopra di me! Le citazioni sono semplici da inserire, basta usare il carattere >. -```markdown +```md > Questa è una citazione. Potete > mandare a capo manualmente le linee e inserire un `>` prima di ognuna, oppure potete usare una sola linea e lasciare che vada a capo automaticamente. > Non c'è alcuna differenza, basta che iniziate ogni riga con `>`. @@ -115,7 +115,7 @@ Le citazioni sono semplici da inserire, basta usare il carattere >. ## Liste Le liste non ordinate possono essere inserite usando gli asterischi, il simbolo più o dei trattini -```markdown +```md * Oggetto * Oggetto * Altro oggetto @@ -135,7 +135,7 @@ oppure Le liste ordinate invece, sono inserite con un numero seguito da un punto. -```markdown +```md 1. Primo oggetto 2. Secondo oggetto 3. Terzo oggetto @@ -143,7 +143,7 @@ Le liste ordinate invece, sono inserite con un numero seguito da un punto. Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzerà comunque nell'ordine corretto, anche se potrebbe non essere una buona idea. -```markdown +```md 1. Primo oggetto 1. Secondo oggetto 1. Terzo oggetto @@ -152,7 +152,7 @@ Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzer Potete inserire anche sotto liste -```markdown +```md 1. Primo oggetto 2. Secondo oggetto 3. Terzo oggetto @@ -163,7 +163,7 @@ Potete inserire anche sotto liste Sono presenti anche le task list. In questo modo è possibile creare checkbox in HTML. -```markdown +```md I box senza la 'x' sono checkbox HTML ancora da completare. - [ ] Primo task da completare. - [ ] Secondo task che deve essere completato. @@ -174,14 +174,14 @@ Il box subito sotto è una checkbox HTML spuntata. Potete inserire un estratto di codice (che utilizza l'elemento ``) indentando una linea con quattro spazi oppure con un carattere tab. -```markdown +```md Questa è una linea di codice Come questa ``` Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vostro codice -```markdown +```md my_array.each do |item| puts item end @@ -189,7 +189,7 @@ Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vo Codice inline può essere inserito usando il carattere backtick ` -```markdown +```md Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! ``` @@ -205,7 +205,7 @@ Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre ## Linea orizzontale Le linee orizzontali (`
`) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi. -```markdown +```md *** --- - - - @@ -215,24 +215,24 @@ Le linee orizzontali (`
`) sono inserite facilmente usanto tre o più asteri ## Links Una delle funzionalità migliori di markdown è la facilità con cui si possono inserire i link. Mettete il testo da visualizzare fra parentesi quadre [] seguite dall'url messo fra parentesi tonde () -```markdown +```md [Cliccami!](http://test.com/) ``` Potete inoltre aggiungere al link un titolo mettendolo fra doppi apici dopo il link -```markdown +```md [Cliccami!](http://test.com/ "Link a Test.com") ``` La sintassi funziona anche con i path relativi. -```markdown +```md [Vai a musica](/music/). ``` Markdown supporta inoltre anche la possibilità di aggiungere i link facendo riferimento ad altri punti del testo. -```markdown +```md [Apri questo link][link1] per più informazioni! [Guarda anche questo link][foobar] se ti va. @@ -242,7 +242,7 @@ Markdown supporta inoltre anche la possibilità di aggiungere i link facendo rif l titolo può anche essere inserito in apici singoli o in parentesi, oppure omesso interamente. Il riferimento può essere inserito in un punto qualsiasi del vostro documento e l'identificativo del riferimento può essere lungo a piacere a patto che sia univoco. Esiste anche un "identificativo implicito" che vi permette di usare il testo del link come id. -```markdown +```md [Questo][] è un link. [Questo]: http://thisisalink.com/ @@ -252,13 +252,13 @@ Ma non è comunemente usato. ## Immagini Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre! -```markdown +```md ![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale") ``` E la modalità a riferimento funziona esattamente come ci si aspetta -```markdown +```md ![Questo è il testo alternativo.][myimage] [myimage]: relative/urls/cool/image.jpg "Se vi serve un titolo, lo mettete qui" @@ -266,25 +266,25 @@ E la modalità a riferimento funziona esattamente come ci si aspetta ## Miscellanea ### Auto link -```markdown +```md è equivalente ad [http://testwebsite.com/](http://testwebsite.com/) ``` ### Auto link per le email -```markdown +```md ``` ### Caratteri di escaping -```markdown +```md Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga renderizzato in corsivo, quindi lo inserirò così: \*questo testo è circondato da asterischi\*. ``` ### Combinazioni di tasti In Github Flavored Markdown, potete utilizzare il tag `` per raffigurare i tasti della tastiera. -```markdown +```md Il tuo computer è crashato? Prova a premere Ctrl+Alt+Canc ``` @@ -292,7 +292,7 @@ Il tuo computer è crashato? Prova a premere ### Tabelle Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue: -```markdown +```md | Col1 | Col2 | Col3 | | :------------------- | :------: | -----------------: | | Allineato a sinistra | Centrato | Allineato a destra | @@ -300,7 +300,7 @@ Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente ``` oppure, per lo stesso risultato -```markdown +```md Col 1 | Col2 | Col3 :-- | :-: | --: È una cosa orrenda | fatela | finire in fretta diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown index 8d6d438506..38be884815 100644 --- a/it-it/matlab-it.html.markdown +++ b/it-it/matlab-it.html.markdown @@ -199,8 +199,7 @@ size(A) % ans = 3 3 A(1, :) =[] % Rimuove la prima riga della matrice A(:, 1) =[] % Rimuove la prima colonna della matrice -transpose(A) % Traspone la matrice, equivale a: -A one +transpose(A) % Traspone la matrice, equivale a: A.' ctranspose(A) % Trasposizione hermitiana della matrice % (ovvero il complesso coniugato di ogni elemento della matrice trasposta) diff --git a/it-it/pcre-it.html.markdown b/it-it/pcre-it.html.markdown new file mode 100644 index 0000000000..682338584c --- /dev/null +++ b/it-it/pcre-it.html.markdown @@ -0,0 +1,80 @@ +--- +language: PCRE +filename: pcre-it.txt +contributors: + - ["Sachin Divekar", "http://github.com/ssd532"] +translators: + - ["Christian Grasso", "https://grasso.io"] +lang: it-it +--- + +Un'espressione regolare (regex o regexp in breve) è una speciale stringa +utilizzata per definire un pattern, ad esempio per cercare una sequenza di +caratteri; ad esempio, `/^[a-z]+:/` può essere usato per estrarre `http:` +dall'URL `http://github.com/`. + +PCRE (Perl Compatible Regular Expressions) è una libreria per i regex in C. +La sintassi utilizzata per le espressioni è molto simile a quella di Perl, da +cui il nome. Si tratta di una delle sintassi più diffuse per la scrittura di +regex. + +Esistono due tipi di metacaratteri (caratteri con una funzione speciale): +* Caratteri riconosciuti ovunque tranne che nelle parentesi quadre +``` + \ carattere di escape + ^ cerca all'inizio della stringa (o della riga, in modalità multiline) + $ cerca alla fine della stringa (o della riga, in modalità multiline) + . qualsiasi carattere eccetto le newline + [ inizio classe di caratteri + | separatore condizioni alternative + ( inizio subpattern + ) fine subpattern + ? quantificatore "0 o 1" + * quantificatore "0 o più" + + quantificatore "1 o più" + { inizio quantificatore numerico +``` + +* Caratteri riconosciuti nelle parentesi quadre +``` + \ carattere di escape + ^ nega la classe se è il primo carattere + - indica una serie di caratteri + [ classe caratteri POSIX (se seguita dalla sintassi POSIX) + ] termina la classe caratteri + +``` + +PCRE fornisce inoltre delle classi di caratteri predefinite: +``` + \d cifra decimale + \D NON cifra decimale + \h spazio vuoto orizzontale + \H NON spazio vuoto orizzontale + \s spazio + \S NON spazio + \v spazio vuoto verticale + \V NON spazio vuoto verticale + \w parola + \W "NON parola" +``` + +## Esempi + +Utilizzeremo la seguente stringa per i nostri test: +``` +66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1" +``` +Si tratta di una riga di log del web server Apache. + +| Regex | Risultato | Commento | +| :---- | :-------------- | :------ | +| `GET` | GET | Cerca esattamente la stringa "GET" (case sensitive) | +| `\d+.\d+.\d+.\d+` | 66.249.64.13 | `\d+` identifica uno o più (quantificatore `+`) numeri [0-9], `\.` identifica il carattere `.` | +| `(\d+\.){3}\d+` | 66.249.64.13 | `(\d+\.){3}` cerca il gruppo (`\d+\.`) esattamente 3 volte. | +| `\[.+\]` | [18/Sep/2004:11:07:48 +1000] | `.+` identifica qualsiasi carattere, eccetto le newline; `.` indica un carattere qualsiasi | +| `^\S+` | 66.249.64.13 | `^` cerca all'inizio della stringa, `\S+` identifica la prima stringa di caratteri diversi dallo spazio | +| `\+[0-9]+` | +1000 | `\+` identifica il carattere `+`. `[0-9]` indica una cifra da 0 a 9. L'espressione è equivalente a `\+\d+` | + +## Altre risorse +[Regex101](https://regex101.com/) - tester per le espressioni regolari diff --git a/it-it/pyqt-it.html.markdown b/it-it/pyqt-it.html.markdown new file mode 100644 index 0000000000..855a0c7513 --- /dev/null +++ b/it-it/pyqt-it.html.markdown @@ -0,0 +1,85 @@ +--- +category: tool +tool: PyQT +filename: learnpyqt.py +contributors: + - ["Nathan Hughes", "https://github.com/sirsharpest"] +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +--- + +**Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*. + + +Questo è un adattamento sull'introduzione di C ++ a QT di [Aleksey Kholovchuk] (https://github.com/vortexxx192 +), alcuni degli esempi di codice dovrebbero avere la stessa funzionalità +che avrebbero se fossero fatte usando pyqt! + +```python +import sys +from PyQt4 import QtGui + +def window(): + # Crea un oggetto applicazione + app = QtGui.QApplication(sys.argv) + # Crea un widget in cui verrà inserita la nostra etichetta + w = QtGui.QWidget() + # Aggiungi un'etichetta al widget + b = QtGui.QLabel(w) + # Imposta del testo per l'etichetta + b.setText("Ciao Mondo!") + # Fornisce informazioni su dimensioni e posizionamento + w.setGeometry(100, 100, 200, 50) + b.move(50, 20) + # Dai alla nostra finestra un bel titolo + w.setWindowTitle("PyQt") + # Visualizza tutto + w.show() + # Esegui ciò che abbiamo chiesto, una volta che tutto è stato configurato + sys.exit(app.exec_()) + +if __name__ == '__main__': + window() + +``` + +Per ottenere alcune delle funzionalità più avanzate in **pyqt**, dobbiamo iniziare a cercare di creare elementi aggiuntivi. +Qui mostriamo come creare una finestra popup di dialogo, utile per chiedere all'utente di confermare una decisione o fornire informazioni + +```Python +import sys +from PyQt4.QtGui import * +from PyQt4.QtCore import * + + +def window(): + app = QApplication(sys.argv) + w = QWidget() + # Crea un pulsante e allegalo al widget w + b = QPushButton(w) + b.setText("Premimi") + b.move(50, 50) + # Indica a b di chiamare questa funzione quando si fa clic +    # notare la mancanza di "()" sulla chiamata di funzione + b.clicked.connect(showdialog) + w.setWindowTitle("PyQt Dialog") + w.show() + sys.exit(app.exec_()) + +# Questa funzione dovrebbe creare una finestra di dialogo con un pulsante +# che aspetta di essere cliccato e quindi esce dal programma +def showdialog(): + d = QDialog() + b1 = QPushButton("ok", d) + b1.move(50, 50) + d.setWindowTitle("Dialog") + # Questa modalità dice al popup di bloccare il genitore, mentre è attivo + d.setWindowModality(Qt.ApplicationModal) + # Al click vorrei che l'intero processo finisse + b1.clicked.connect(sys.exit) + d.exec_() + +if __name__ == '__main__': + window() +``` diff --git a/it-it/python3-it.html.markdown b/it-it/python3-it.html.markdown new file mode 100644 index 0000000000..04f78cffa2 --- /dev/null +++ b/it-it/python3-it.html.markdown @@ -0,0 +1,1016 @@ +--- +language: python3 +filename: learnpython3-it.py +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] +translators: + - ["Draio", "http://github.com/Draio/"] + - ["Ale46", "http://github.com/Ale46/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] +lang: it-it +--- + +Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente pseudocodice eseguibile. + +Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] + +Nota: Questo articolo è riferito a Python 3 in modo specifico. Se volete avete la necessità di utilizzare Python 2.7 potete consultarla [qui](https://learnxinyminutes.com/docs/it-it/python-it/) + +```python + +# I commenti su una sola linea iniziano con un cancelletto + + +""" Più stringhe possono essere scritte + usando tre ", e sono spesso usate + come documentazione +""" + +#################################################### +## 1. Tipi di dati primitivi ed Operatori +#################################################### + +# Ci sono i numeri +3 # => 3 + +# La matematica è quello che vi aspettereste +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Risultato della divisione intera troncata sia in positivo che in negativo +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Il risultato di una divisione è sempre un numero decimale (float) +10.0 / 3 # => 3.3333333333333335 + +# Operazione Modulo +7 % 3 # => 1 + +# Elevamento a potenza (x alla y-esima potenza) +2**3 # => 8 + +# Forzare le precedenze con le parentesi +(1 + 3) * 2 # => 8 + +# I valori booleani sono primitive del linguaggio (nota la maiuscola) +True +False + +# nega con not +not True # => False +not False # => True + +# Operatori Booleani +# Nota "and" e "or" sono case-sensitive +True and False # => False +False or True # => True + +# Note sull'uso di operatori Bool con interi +# False è 0 e True è 1 +# Non confonderti tra bool(ints) e le operazioni bitwise and/or (&,|) +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True +-5 != False != True #=> True + +# Uguaglianza è == +1 == 1 # => True +2 == 1 # => False + +# Disuguaglianza è != +1 != 1 # => False +2 != 1 # => True + +# Altri confronti +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# I confronti possono essere concatenati! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# ('is' vs. '==') +# 'is' controlla se due variabili si riferiscono allo stesso oggetto +# '==' controlla se gli oggetti puntati hanno lo stesso valore. +a = [1, 2, 3, 4] # a punta ad una nuova lista [1, 2, 3, 4] +b = a # b punta a ciò a cui punta a +b is a # => True, a e b puntano allo stesso oggeto +b == a # => True, gli oggetti di a e b sono uguali +b = [1, 2, 3, 4] # b punta ad una nuova lista [1, 2, 3, 4] +b is a # => False, a e b non puntano allo stesso oggetto +b == a # => True, gli oggetti di a e b sono uguali + +# Le stringhe sono create con " o ' +"Questa è una stringa." +'Anche questa è una stringa.' + +# Anche le stringhe possono essere sommate! Ma cerca di non farlo. +"Hello " + "world!" # => "Hello world!" +# Le stringhe (ma non le variabili contenenti stringhe) possono essere +# sommate anche senza '+' +"Hello " "world!" # => "Hello world!" + +# Una stringa può essere considerata come una lista di caratteri +"Questa è una stringa"[0] # => 'Q' + +# Puoi conoscere la lunghezza di una stringa +len("Questa è una stringa") # => 20 + +# .format può essere usato per formattare le stringhe, in questo modo: +"{} possono essere {}".format("Le stringhe", "interpolate") # => "Le stringhe possono essere interpolate" + +# Puoi ripetere gli argomenti di formattazione per risparmiare un po' di codice +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# Puoi usare dei nomi se non vuoi contare gli argomenti +"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="le lasagne") # => "Bob vuole mangiare le lasagne" + +# Se il tuo codice Python 3 necessita di eseguire codice Python 2.x puoi ancora +# utilizzare il vecchio stile di formattazione: +"%s possono essere %s nel %s modo" % ("Le stringhe", "interpolate", "vecchio") # => "Le stringhe possono essere interpolate nel vecchio modo" + +# None è un oggetto +None # => None + +# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None +# Usa "is" invece +"etc" is None # => False +None is None # => True + +# None, 0, e stringhe/liste/dizionari/tuple vuoti vengono considerati +# falsi (False). Tutti gli altri valori sono considerati veri (True). +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Variabili e Collections +#################################################### + +# Python ha una funzione per scrivere (sul tuo schermo) +print("Sono Python. Piacere di conoscerti!") # => Sono Python. Piacere di conoscerti! + +# Di default la funzione print() scrive e va a capo aggiungendo un carattere +# newline alla fine della stringa. È possibile utilizzare l'argomento opzionale +# end per cambiare quest'ultimo carattere aggiunto. +print("Hello, World", end="!") # => Hello, World! + +# Un modo semplice per ricevere dati in input dalla riga di comando +variabile_stringa_input = input("Inserisci del testo: ") # Restituisce i dati letti come stringa +# Nota: Nelle precedenti vesioni di Python, il metodo input() +# era chiamato raw_input() + +# Non c'è bisogno di dichiarare una variabile per assegnarle un valore +# Come convenzione, per i nomi delle variabili, si utilizzano i caratteri +# minuscoli separati, se necessario, da underscore +some_var = 5 +some_var # => 5 + +# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. +# Dai un'occhiata al Control Flow per imparare di più su come gestire +# le eccezioni. +some_unknown_var # Genera un errore di nome + +# if può essere usato come un'espressione +# È l'equivalente dell'operatore ternario in C +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Le liste immagazzinano sequenze +li = [] +# Puoi partire con una lista pre-riempita +other_li = [4, 5, 6] + +# Aggiungere alla fine di una lista con append +li.append(1) # li ora è [1] +li.append(2) # li ora è [1, 2] +li.append(4) # li ora è [1, 2, 4] +li.append(3) # li ora è [1, 2, 4, 3] +# Rimuovi dalla fine della lista con pop +li.pop() # => 3 e li ora è [1, 2, 4] +# Rimettiamolo a posto +li.append(3) # li ora è [1, 2, 4, 3] di nuovo. + +# Accedi ad una lista come faresti con un array +li[0] # => 1 +# Guarda l'ultimo elemento +li[-1] # => 3 + +# Guardare al di fuori dei limiti genera un IndexError +li[4] # Genera IndexError + +# Puoi guardare gli intervalli con la sintassi slice (a fetta). +# (E' un intervallo chiuso/aperto per voi tipi matematici.) +li[1:3] # => [2, 4] +# Ometti l'inizio +li[2:] # => [4, 3] +# Ometti la fine +li[:3] # => [1, 2, 4] +# Seleziona ogni seconda voce +li[::2] # =>[1, 4] +# Copia al contrario della lista +li[::-1] # => [3, 4, 2, 1] +# Usa combinazioni per fare slices avanzate +# li[inizio:fine:passo] + +# Crea una copia (one layer deep copy) usando la sintassi slices +li2 = li[:] # => li2 = [1, 2, 4, 3] ma (li2 is li) risulterà falso. + +# Rimuovi arbitrariamente elementi da una lista con "del" +del li[2] # li è ora [1, 2, 3] + +# Rimuove la prima occorrenza di un elemento +li.remove(2) # Ora li è [1, 3, 4, 5, 6] +li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista + +# Inserisce un elemento all'indice specificato +li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6] + + Ritorna l'indice della prima occorrenza dell'elemento fornito +li.index(2) # => 1 +li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista + +# Puoi sommare le liste +# Nota: i valori per li e per other_li non vengono modificati. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatena le liste con "extend()" +li.extend(other_li) # Adesso li è [1, 2, 3, 4, 5, 6] + +# Controlla l'esistenza di un valore in una lista con "in" +1 in li # => True + +# Esamina la lunghezza con "len()" +len(li) # => 6 + + +# Le tuple sono come le liste ma immutabili. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Genera un TypeError + +# Note that a tuple of length one has to have a comma after the last element but +# tuples of other lengths, even zero, do not. +type((1)) # => +type((1,)) # => +type(()) # => + +# Puoi fare tutte queste cose da lista anche sulle tuple +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Puoi scompattare le tuple (o liste) in variabili +a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 e c è ora 3 +d, e, f = 4, 5, 6 # puoi anche omettere le parentesi +# Le tuple sono create di default se non usi le parentesi +g = 4, 5, 6 # => (4, 5, 6) +# Guarda come è facile scambiare due valori +e, d = d, e # d è ora 5 ed e è ora 4 + +# I dizionari memorizzano insiemi di dati indicizzati da nomi arbitrari (chiavi) +empty_dict= {} +# Questo è un dizionario pre-caricato +filled_dict = {"uno": 1, "due": 2, "tre": 3} + +# Nota: le chiavi dei dizionari devono essere di tipo immutabile. Questo per +# assicurare che le chiavi possano essere convertite in calori hash costanti +# per un risposta più veloce. +invalid_dict = {[1,2,3]: "123"} # => Emette un TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # I valori, invece, possono essere di qualunque tipo + +# Accedi ai valori indicando la chiave tra [] +filled_dict["uno"] # => 1 + +# Puoi ottenere tutte le chiavi di un dizionario con "keys()" +# (come oggetto iterabile). Per averle in formato lista è necessario +# utilizzare list(). +# Nota - Nei dizionari l'ordine delle chiavi non è garantito. +# Il tuo risultato potrebbe non essere uguale a questo. +list(filled_dict.keys()) # => ["tre", "due", "uno"] + + +# Puoi ottenere tutti i valori di un dizionario con "values()" +# (come oggetto iterabile). +# Anche in questo caso, er averle in formato lista, è necessario utilizzare list() +# Anche in questo caso, come per le chiavi, l'ordine non è garantito +list(filled_dict.values()) # => [3, 2, 1] + +# Controlla l'esistenza delle chiavi in un dizionario con "in" +"uno" in filled_dict # => True +1 in filled_dict # => False + +# Cercando una chiave non esistente genera un KeyError +filled_dict["quattro"] # KeyError + +# Usa il metodo "get()" per evitare KeyError +filled_dict.get("uno") # => 1 +filled_dict.get("quattro") # => None +# Il metodo get supporta un argomento di default quando il valore è mancante +filled_dict.get("uno", 4) # => 1 +filled_dict.get("quattro", 4) # => 4 + + +# "setdefault()" inserisce un valore per una chiave in un dizionario +# solo se la chiave data non è già presente +filled_dict.setdefault("cinque", 5) # filled_dict["cinque"] viene impostato a 5 +filled_dict.setdefault("cinque", 6) # filled_dict["cinque"] rimane 5 + +# Aggiungere una coppia chiave->valore a un dizionario +filled_dict.update({"quattro":4}) # => {"uno": 1, "due": 2, "tre": 3, "quattro": 4} +filled_dict["quattro"] = 4 # un altro modo pe aggiungere a un dizionario + +# Rimuovi una chiave da un dizionario con del +del filled_dict["uno"] # Rimuove la chiave "uno" dal dizionario + +# Da Python 3.5 puoi anche usare ulteriori opzioni di spacchettamento +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + +# I set sono come le liste ma non possono contenere doppioni +empty_set = set() +# Inizializza un "set()" con un dei valori. Sì, sembra un dizionario. +some_set = {1, 1, 2, 2, 3, 4} # set_nuovo è {1, 2, 3, 4} + +# Come le chiavi di un dizionario, gli elementi di un set devono essere +# di tipo immutabile +invalid_set = {[1], 1} # => Genera un "TypeError: unhashable type: 'list'"" +valid_set = {(1,), 1} + +# Aggiungere uno o più elementi ad un set +some_set.add(5) # some_set ora è {1, 2, 3, 4, 5} + +# Fai intersezioni su un set con & +other_set = {3, 4, 5, 6} +some_set & other_set # => {3, 4, 5} + +# Fai unioni su set con | +some_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Fai differenze su set con - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Effettua la differenza simmetrica con ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Controlla se il set a sinistra contiene quello a destra +{1, 2} >= {1, 2, 3} # => False + +# Controlla se il set a sinistra è un sottoinsieme di quello a destra +{1, 2} <= {1, 2, 3} # => True + +# Controlla l'esistenza in un set con in +2 in some_set # => True +10 in some_set # => False + + + +#################################################### +## 3. Control Flow e oggetti Iterabili +#################################################### + +# Dichiariamo una variabile +some_var = 5 + +# Questo è un controllo if. L'indentazione è molto importante in python! +# Come convenzione si utilizzano quattro spazi, non la tabulazione. +# Il seguente codice stampa "some_var è minore di 10" +if some_var > 10: + print("some_var è maggiore di 10") +elif some_var < 10: # La clausolo elif è opzionale + print("some_var è minore di 10") +else: # Anche else è opzionale + print("some_var è 10.") + +""" +I cicli for iterano sulle liste, cioè ripetono un codice per ogni elemento +di una lista. +Il seguente codice scriverà: + cane è un mammifero + gatto è un mammifero + topo è un mammifero +""" +for animale in ["cane", "gatto", "topo"]: + # Puoi usare format() per interpolare le stringhe formattate. + print("{} è un mammifero".format(animale)) + +""" +"range(numero)" restituisce una lista di numeri da zero al numero dato +Il seguente codice scriverà: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" restituisce una lista di numeri dal più piccolo (lower) +al più grande (upper). +Il seguente codice scriverà: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" rrestituisce una lista di numeri dal più piccolo +(lower) al più grande (upper), incrementando del valore step. +Se step non è indicato, avrà come valore di default 1. +Il seguente codice scriverà: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +I cicli while vengono eseguiti finchè una condizione viene a mancare +Il seguente codice scriverà: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Forma compatta per x = x + 1 + +# Gestione delle eccezioni con un blocco try/except +try: + # Usa "raise" per generare un errore + raise IndexError("Questo è un IndexError") +except IndexError as e: + pass # Pass è solo una non-operazione. Solitamente vorrai rimediare all'errore. +except (TypeError, NameError): + pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. +else: # Clausola opzionale al blocco try/except. Deve essere dopo tutti i blocchi except + print("Tutto ok!") # Viene eseguita solo se il codice dentro try non genera eccezioni +finally: # Eseguito sempre + print("Possiamo liberare risorse qui") + +# Se ti serve solo un try/finally, per liberare risorse, puoi usare il metodo with +with open("myfile.txt") as f: + for line in f: + print(line) + +# In Python qualunque oggetto in grado di essere trattato come una +# sequenza è definito un oggetto Iterable (itarabile). +# L'oggetto restituito da una funzione range è un iterabile. + +filled_dict = {"uno": 1, "due": 2, "tre": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['uno', 'due', 'tre']). +# Questo è un oggetto che implementa la nostra interfaccia Iterable. + +# È possibile utilizzarlo con i loop: +for i in our_iterable: + print(i) # Scrive uno, due, tre + +# Tuttavia non possiamo recuperarne i valori tramite indice. +our_iterable[1] # Genera un TypeError + +# Un oggetto iterabile è in grado di generare un iteratore +our_iterator = iter(our_iterable) + +# L'iteratore è un oggetto che ricorda il suo stato mentro lo si "attraversa" +# Possiamo accedere al successivo elemento con "next()". +next(our_iterator) # => "uno" + +# Mantiene il suo stato mentro eseguiamo l'iterazione +next(our_iterator) # => "due" +next(our_iterator) # => "tre" + +# Dopo che un iteratore ha restituito tutti i suoi dati, genera +# un'eccezione StopIteration +next(our_iterator) # Raises StopIteration + +# Puoi prendere tutti gli elementi di un iteratore utilizzando list(). +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + + +#################################################### +## 4. Funzioni +#################################################### + +# Usa "def" per creare nuove funzioni +def aggiungi(x, y): + print("x è {} e y è {}".format(x, y)) // Scrive i valori formattati in una stringa + return x + y # Restituisce la somma dei valori con il metodo return + +# Chiamare funzioni con parametri +aggiungi(5, 6) # => scrive "x è 5 e y è 6" e restituisce 11 + +# Un altro modo per chiamare funzioni è con parole chiave come argomenti +aggiungi(y=6, x=5) # In questo modo non è necessario rispettare l'ordine degli argomenti + +# Puoi definire funzioni che accettano un numero non definito di argomenti +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Puoi definire funzioni che accettano un numero variabile di parole chiave +# come argomento, che saranno interpretati come un dizionario usando ** +def keyword_args(**kwargs): + return kwargs + +# Chiamiamola per vedere cosa succede +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Puoi farle entrambi in una volta, se ti va +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) stampa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! +# Usa * per sviluppare gli argomenti posizionale ed usa ** per +# espandere gli argomenti parola chiave +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + + +# Restituire valori multipli (with tuple assignments) +def swap(x, y): + return y, x # Restituisce valori multipli come tupla senza parentesi + # (Nota: le parentesi sono state escluse ma possono essere messe) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Le parentesi sono state escluse ma possono essere incluse. + +# Funzioni - Visibilità delle variabili (variable scope) +x = 5 + +def set_x(num): + # La variabile locale x non è la variabile globale x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # la variabile globable x è ora 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Python ha "first class functions" +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Ci sono anche funzioni anonime +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# È possibile creare "mappe" e "filtri" +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# Possiamo usare le "list comprehensions" per mappe e filtri +# Le "list comprehensions" memorizzano l'output come una lista che può essere +# di per sé una lista annidata +[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] + +# Puoi fare anche la comprensione di set e dizionari +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Modules +#################################################### + +# Puoi importare moduli +import math +print(math.sqrt(16)) # => 4.0 + +# Puoi ottenere specifiche funzione da un modulo +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Puoi importare tutte le funzioni da un modulo +# Attenzione: questo non è raccomandato +from math import * + +# Puoi abbreviare i nomi dei moduli +import math as m +math.sqrt(16) == m.sqrt(16) # => True + + +# I moduli di Python sono normali file python. Ne puoi +# scrivere di tuoi ed importarli. Il nome del modulo +# è lo stesso del nome del file. + +# Potete scoprire quali funzioni e attributi +# sono definiti in un modulo +import math +dir(math) + +# Se nella cartella corrente hai uno script chiamato math.py, +# Python caricherà quello invece del modulo math. +# Questo succede perchè la cartella corrente ha priorità +# sulle librerie standard di Python + +# Se hai uno script Python chiamato math.py nella stessa +# cartella del tua script, Python caricherà quello al posto del +# comune modulo math. +# Questo accade perché la cartella locale ha la priorità +# sulle librerie built-in di Python. + + +#################################################### +## 6. Classes +#################################################### + +# Usiamo l'istruzione "class" per creare una classe +class Human: + + # Un attributo della classe. E' condiviso tra tutte le istanze delle classe + species = "H. sapiens" + + # Si noti che i doppi underscore iniziali e finali denotano gli oggetti o + # attributi utilizzati da Python ma che vivono nel namespace controllato + # dall'utente + # Metodi, oggetti o attributi come: __init__, __str__, __repr__, etc. sono + # chiamati metodi speciali (o talvolta chiamati "dunder methods"). + # Non dovresti inventare tali nomi da solo. + + def __init__(self, name): + # Assegna l'argomento all'attributo name dell'istanza + self.name = name + + # Inizializza una proprietà + self._age = 0 + + # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Un altro metodo dell'istanza + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Un metodo della classe è condiviso fra tutte le istanze + # Sono chiamati con la classe chiamante come primo argomento + @classmethod + def get_species(cls): + return cls.species + + # Un metodo statico è chiamato senza classe o istanza di riferimento + @staticmethod + def grunt(): + return "*grunt*" + + # Una property è come un metodo getter. + # Trasforma il metodo age() in un attributo in sola lettura, che ha + # lo stesso nome + # In Python non c'è bisogno di scrivere futili getter e setter. + @property + def age(self): + return self._age + + # Questo metodo permette di modificare una property + @age.setter + def age(self, age): + self._age = age + + # Questo metodo permette di cancellare una property + @age.deleter + def age(self): + del self._age + +# Quando l'interprete Python legge un sorgente esegue tutto il suo codice. +# Questo controllo su __name__ assicura che questo blocco di codice venga +# eseguito solo quando questo modulo è il programma principale. + +if __name__ == '__main__': + # Crea un'istanza della classe + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i e j sono istanze del tipo Human, o in altre parole sono oggetti Human + + # Chiama un metodo della classe + i.say(i.get_species()) # "Ian: H. sapiens" + # Cambia l'attributo condiviso + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Chiama un metodo statico + print(Human.grunt()) # => "*grunt*" + + # Non è possibile chiamare il metodo statico con l'istanza dell'oggetto + # poiché i.grunt() metterà automaticamente "self" (l'oggetto i) + # come argomento + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Aggiorna la property (age) di questa istanza + i.age = 42 + # Leggi la property + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Cancella la property + del i.age + i.age # => questo genererà un AttributeError + + +#################################################### +## 6.1 Ereditarietà (Inheritance) +#################################################### + +# L'ereditarietà consente di definire nuove classi figlio che ereditano metodi e +# variabili dalla loro classe genitore. + +# Usando la classe Human definita sopra come classe base o genitore, possiamo +# definire una classe figlia, Superhero, che erediterà le variabili di classe +# come "species", "name" e "age", così come i metodi, come "sing" e "grunt", +# dalla classe Human, ma potrà anche avere le sue proprietà uniche. + +# Per importare le funzioni da altri file usa il seguente formato +# from "nomefile-senza-estensione" import "funzione-o-classe" + +from human import Human + +# Specificare le classi genitore come parametri della definizione della classe +class Superhero(Human): + + # Se la classe figlio deve ereditare tutte le definizioni del genitore + # senza alcuna modifica, puoi semplicemente usare la parola chiave "pass" + # (e nient'altro) + + #Le classi figlio possono sovrascrivere gli attributi dei loro genitori + species = 'Superhuman' + + # Le classi figlie ereditano automaticamente il costruttore della classe + # genitore, inclusi i suoi argomenti, ma possono anche definire ulteriori + # argomenti o definizioni e sovrascrivere i suoi metodi (compreso il + # costruttore della classe). + # Questo costruttore eredita l'argomento "nome" dalla classe "Human" e + # aggiunge gli argomenti "superpowers" e "movie": + + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # aggiungi ulteriori attributi della classe + self.fictional = True + self.movie = movie + self.superpowers = superpowers + + # La funzione "super" ti consente di accedere ai metodi della classe + # genitore che sono stati sovrascritti dalla classe figlia, + # in questo caso il metodo __init__. + # Il seguente codice esegue il costruttore della classe genitore: + super().__init__(name) + + # Sovrascrivere il metodo "sing" + def sing(self): + return 'Dun, dun, DUN!' + + # Aggiungi un ulteriore metodo dell'istanza + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Controllo del tipo di istanza + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # Ottieni il "Method Resolution search Order" usato sia da getattr () + # che da super (). Questo attributo è dinamico e può essere aggiornato + print(Superhero.__mro__) # => (, + # => , ) + + # Esegui il metodo principale ma utilizza il proprio attributo di classe + print(sup.get_species()) # => Superhuman + + # Esegui un metodo che è stato sovrascritto + print(sup.sing()) # => Dun, dun, DUN! + + # Esegui un metodo di Human + sup.say('Spoon') # => Tick: Spoon + + # Esegui un metodo che esiste solo in Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Attributo di classe ereditato + sup.age = 31 + print(sup.age) # => 31 + + # Attributo che esiste solo in Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Ereditarietà multipla +#################################################### + +# Un'altra definizione di classe +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # Questa classe ha anche un metodo "say" + def say(self, msg): + msg = '... ... ...' + return msg + + # E anche un suo metodo personale + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# Definizione di classe che eredita da Superhero e Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Definisci Batman come classe figlia che eredita sia da Superhero che da Bat +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # In genere per ereditare gli attributi devi chiamare super: + # super(Batman, self).__init__(*args, **kwargs) + # Ma qui abbiamo a che fare con l'ereditarietà multipla, e super() + # funziona solo con la successiva classe nell'elenco MRO. + # Quindi, invece, chiamiamo esplicitamente __init__ per tutti gli + # antenati. L'uso di *args e **kwargs consente di passare in modo + # pulito gli argomenti, con ciascun genitore che "sbuccia un + # livello della cipolla". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # sovrascrivere il valore per l'attributo name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # Ottieni il "Method Resolution search Order" utilizzato da getattr() e super(). + # Questo attributo è dinamico e può essere aggiornato + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Esegui il metodo del genitore ma utilizza il proprio attributo di classe + print(sup.get_species()) # => Superhuman + + # Esegui un metodo che è stato sovrascritto + print(sup.sing()) # => nan nan nan nan nan batman! + + # Esegui un metodo da Human, perché l'ordine di ereditarietà è importante + sup.say('I agree') # => Sad Affleck: I agree + + # Esegui un metodo che esiste solo nel 2o antenato + print(sup.sonar()) # => ))) ... ((( + + # Attributo di classe ereditato + sup.age = 100 + print(sup.age) # => 100 + + # Attributo ereditato dal secondo antenato il cui valore predefinito + # è stato ignorato. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. Advanced +#################################################### + +# I generatori ti aiutano a creare codice pigro (lazy code). +# Codice che darà un risultato solo quando sarà "valutato" +def double_numbers(iterable): + for i in iterable: + yield i + i + +# I generatori sono efficienti in termini di memoria perché caricano +# solo i dati necessari per elaborare il valore successivo nell'iterabile. +# Ciò consente loro di eseguire operazioni su intervalli di valori +# altrimenti proibitivi. +# NOTA: `range` sostituisce` xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. + print(i) + if i >= 30: + break + +# Proprio come è possibile creare una "list comprehension", è possibile +# creare anche delle "generator comprehensions". +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# Puoi anche trasmettere una "generator comprehensions" direttamente +# ad un elenco. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decoratori +# In questo esempio "beg" avvolge/wrappa "say". +# Se say_please è True, cambierà il messaggio restituito. +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, "Per favore! Sono povero :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Puoi comprarmi una birra?" + return msg, say_please + + +print(say()) # Puoi comprarmi una birra? +print(say(say_please=True)) # Puoi comprarmi una birra? Per favore! Sono povero :( +``` + +## Pronto per qualcosa di più? + +### Gratis Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/it-it/qt-it.html.markdown b/it-it/qt-it.html.markdown new file mode 100644 index 0000000000..4543818f80 --- /dev/null +++ b/it-it/qt-it.html.markdown @@ -0,0 +1,161 @@ +--- +category: tool +tool: Qt Framework +language: c++ +filename: learnqt.cpp +contributors: + - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] +translators: + - ["Ale46", "https://gihub.com/ale46"] +lang: it-it +--- + +**Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*, ci sono diversi porting in altri linguaggi: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc. + +**Qt** è ottimo per la creazione di applicazioni con interfaccia utente grafica (GUI). Questo tutorial descrive come farlo in *C++*. + +```c++ +/* + * Iniziamo classicamente + */ + +// tutte le intestazioni dal framework Qt iniziano con la lettera maiuscola 'Q' +#include +#include + +int main(int argc, char *argv[]) { + // crea un oggetto per gestire le risorse a livello di applicazione + QApplication app(argc, argv); + + // crea un widget di campo di testo e lo mostra sullo schermo + QLineEdit lineEdit("Hello world!"); + lineEdit.show(); + + // avvia il ciclo degli eventi dell'applicazione + return app.exec(); +} +``` + +La parte relativa alla GUI di **Qt** riguarda esclusivamente *widget* e le loro *connessioni*. + +[LEGGI DI PIÙ SUI WIDGET](http://doc.qt.io/qt-5/qtwidgets-index.html) + +```c++ +/* + * Creiamo un'etichetta e un pulsante. + * Un'etichetta dovrebbe apparire quando si preme un pulsante. + * + * Il codice Qt parla da solo. + */ + +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + // add vertical layout + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + QLabel textLabel("Grazie per aver premuto quel pulsante"); + layout.addWidget(&textLabel); + textLabel.hide(); + + QPushButton button("Premimi"); + layout.addWidget(&button); + + // mostra l'etichetta nascosta quando viene premuto il pulsante + QObject::connect(&button, &QPushButton::pressed, + &textLabel, &QLabel::show); + + return app.exec(); +} +``` + +Si noti la parte relativa a *QObject::connect*. Questo metodo viene utilizzato per connettere *SEGNALI* di un oggetto agli *SLOTS* di un altro. + +**I SEGNALI** vengono emessi quando certe cose accadono agli oggetti, come il segnale *premuto* che viene emesso quando l'utente preme sull'oggetto QPushButton. + +**Gli slot** sono *azioni* che potrebbero essere eseguite in risposta ai segnali ricevuti. + +[LEGGI DI PIÙ SU SLOT E SEGNALI](http://doc.qt.io/qt-5/signalsandslots.html) + + +Successivamente, impariamo che non possiamo solo usare i widget standard, ma estendere il loro comportamento usando l'ereditarietà. Creiamo un pulsante e contiamo quante volte è stato premuto. A tale scopo definiamo la nostra classe *CounterLabel*. Deve essere dichiarato in un file separato a causa dell'architettura Qt specifica. + +```c++ +// counterlabel.hpp + +#ifndef COUNTERLABEL +#define COUNTERLABEL + +#include + +class CounterLabel : public QLabel { + Q_OBJECT // Macro definite da Qt che devono essere presenti in ogni widget personalizzato + +public: + CounterLabel() : counter(0) { + setText("Il contatore non è stato ancora aumentato"); // metodo di QLabel + } + +public slots: + // azione che verrà chiamata in risposta alla pressione del pulsante + void increaseCounter() { + setText(QString("Valore contatore: %1").arg(QString::number(++counter))); + } + +private: + int counter; +}; + +#endif // COUNTERLABEL +``` + +```c++ +// main.cpp +// Quasi uguale all'esempio precedente + +#include +#include +#include +#include +#include +#include "counterlabel.hpp" + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + CounterLabel counterLabel; + layout.addWidget(&counterLabel); + + QPushButton button("Premimi ancora una volta"); + layout.addWidget(&button); + QObject::connect(&button, &QPushButton::pressed, + &counterLabel, &CounterLabel::increaseCounter); + + return app.exec(); +} +``` + +Questo è tutto! Ovviamente, il framework Qt è molto più grande della parte che è stata trattata in questo tutorial, quindi preparatevi a leggere e fare pratica. + +## Ulteriori letture + +- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html) +- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html) + +Buona fortuna e buon divertimento! diff --git a/it-it/rst-it.html.markdown b/it-it/rst-it.html.markdown index 8947c738a1..a834e8998f 100644 --- a/it-it/rst-it.html.markdown +++ b/it-it/rst-it.html.markdown @@ -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 `_ . +- Utilizzando una sintassi simile a Markdown: `Github `_ . .. _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 diff --git a/it-it/ruby-it.html.markdown b/it-it/ruby-it.html.markdown new file mode 100644 index 0000000000..295bf28a3d --- /dev/null +++ b/it-it/ruby-it.html.markdown @@ -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. diff --git a/it-it/toml-it.html.markdown b/it-it/toml-it.html.markdown new file mode 100644 index 0000000000..9908204814 --- /dev/null +++ b/it-it/toml-it.html.markdown @@ -0,0 +1,276 @@ +--- +language: toml +filename: learntoml-it.toml +contributors: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +translators: + - ["Christian Grasso", "https://grasso.io"] +lang: it-it +--- + +TOML è l'acronimo di _Tom's Obvious, Minimal Language_. È un linguaggio per la +serializzazione di dati, progettato per i file di configurazione. + +È un'alternativa a linguaggi come YAML e JSON, che punta ad essere più leggibile +per le persone. Allo stesso tempo, TOML può essere utilizzato in modo abbastanza +semplice nella maggior parte dei linguaggi di programmazione, in quanto è +progettato per essere tradotto senza ambiguità in una hash table. + +Tieni presente che TOML è ancora in fase di sviluppo, e la sua specifica non è +ancora stabile. Questo documento utilizza TOML 0.4.0. + +```toml +# I commenti in TOML sono fatti così. + +################ +# TIPI SCALARI # +################ + +# Il nostro oggetto root (corrispondente all'intero documento) sarà una mappa, +# anche chiamata dizionario, hash o oggetto in altri linguaggi. + +# La key, il simbolo di uguale e il valore devono trovarsi sulla stessa riga, +# eccetto per alcuni tipi di valori. +key = "value" +stringa = "ciao" +numero = 42 +float = 3.14 +boolean = true +data = 1979-05-27T07:32:00-08:00 +notazScientifica = 1e+12 +"puoi utilizzare le virgolette per la key" = true # Puoi usare " oppure ' +"la key può contenere" = "lettere, numeri, underscore e trattini" + +############ +# Stringhe # +############ + +# Le stringhe possono contenere solo caratteri UTF-8 validi. +# Possiamo effettuare l'escape dei caratteri, e alcuni hanno delle sequenze +# di escape compatte. Ad esempio, \t corrisponde al TAB. +stringaSemplice = "Racchiusa tra virgolette. \"Usa il backslash per l'escape\"." + +stringaMultiriga = """ +Racchiusa da tre virgolette doppie all'inizio e +alla fine - consente di andare a capo.""" + +stringaLiteral = 'Virgolette singole. Non consente di effettuare escape.' + +stringaMultirigaLiteral = ''' +Racchiusa da tre virgolette singole all'inizio e +alla fine - consente di andare a capo. +Anche in questo caso non si può fare escape. +Il primo ritorno a capo viene eliminato. + Tutti gli altri spazi aggiuntivi + vengono mantenuti. +''' + +# Per i dati binari è consigliabile utilizzare Base64 e +# gestirli manualmente dall'applicazione. + +########## +# Interi # +########## + +## Gli interi possono avere o meno un segno (+, -). +## Non si possono inserire zero superflui all'inizio. +## Non è possibile inoltre utilizzare valori numerici +## non rappresentabili con una sequenza di cifre. +int1 = +42 +int2 = 0 +int3 = -21 + +## Puoi utilizzare gli underscore per migliorare la leggibilità. +## Fai attenzione a non inserirne due di seguito. +int4 = 5_349_221 +int5 = 1_2_3_4_5 # VALIDO, ma da evitare + +######### +# Float # +######### + +# I float permettono di rappresentare numeri decimali. +flt1 = 3.1415 +flt2 = -5e6 +flt3 = 6.626E-34 + +########### +# Boolean # +########### + +# I valori boolean (true/false) devono essere scritti in minuscolo. +bool1 = true +bool2 = false + +############ +# Data/ora # +############ + +data1 = 1979-05-27T07:32:00Z # Specifica RFC 3339/ISO 8601 (UTC) +data2 = 1979-05-26T15:32:00+08:00 # RFC 3339/ISO 8601 con offset + +###################### +# TIPI DI COLLECTION # +###################### + +######### +# Array # +######### + +array1 = [ 1, 2, 3 ] +array2 = [ "Le", "virgole", "sono", "delimitatori" ] +array3 = [ "Non", "unire", "tipi", "diversi" ] +array4 = [ "tutte", 'le stringhe', """hanno lo stesso""", '''tipo''' ] +array5 = [ + "Gli spazi vuoti", "sono", "ignorati" +] + +########### +# Tabelle # +########### + +# Le tabelle (o hash table o dizionari) sono collection di coppie key/value. +# Iniziano con un nome tra parentesi quadre su una linea separata. +# Le tabelle vuote (senza alcun valore) sono valide. +[tabella] + +# Tutti i valori che si trovano sotto il nome della tabella +# appartengono alla tabella stessa (finchè non ne viene creata un'altra). +# L'ordine di questi valori non è garantito. +[tabella-1] +key1 = "una stringa" +key2 = 123 + +[tabella-2] +key1 = "un'altra stringa" +key2 = 456 + +# Utilizzando i punti è possibile creare delle sottotabelle. +# Ogni parte suddivisa dai punti segue le regole delle key per il nome. +[tabella-3."sotto.tabella"] +key1 = "prova" + +# Ecco l'equivalente JSON della tabella precedente: +# { "tabella-3": { "sotto.tabella": { "key1": "prova" } } } + +# Gli spazi non vengono considerati, ma è consigliabile +# evitare di usare spazi superflui. +[a.b.c] # consigliato +[ d.e.f ] # identico a [d.e.f] + +# Non c'è bisogno di creare le tabelle superiori per creare una sottotabella. +# [x] queste +# [x.y] non +# [x.y.z] servono +[x.y.z.w] # per creare questa tabella + +# Se non è stata già creata prima, puoi anche creare +# una tabella superiore più avanti. +[a.b] +c = 1 + +[a] +d = 2 + +# Non puoi definire una key o una tabella più di una volta. + +# ERRORE +[a] +b = 1 + +[a] +c = 2 + +# ERRORE +[a] +b = 1 + +[a.b] +c = 2 + +# I nomi delle tabelle non possono essere vuoti. +[] # NON VALIDO +[a.] # NON VALIDO +[a..b] # NON VALIDO +[.b] # NON VALIDO +[.] # NON VALIDO + +################## +# Tabelle inline # +################## + +tabelleInline = { racchiuseData = "{ e }", rigaSingola = true } +punto = { x = 1, y = 2 } + +#################### +# Array di tabelle # +#################### + +# Un array di tabelle può essere creato utilizzando due parentesi quadre. +# Tutte le tabelle con questo nome saranno elementi dell'array. +# Gli elementi vengono inseriti nell'ordine in cui si trovano. + +[[prodotti]] +nome = "array di tabelle" +sku = 738594937 +tabelleVuoteValide = true + +[[prodotti]] + +[[prodotti]] +nome = "un altro item" +sku = 284758393 +colore = "grigio" + +# Puoi anche creare array di tabelle nested. Le sottotabelle con doppie +# parentesi quadre apparterranno alla tabella più vicina sopra di esse. + +[[frutta]] + nome = "mela" + + [frutto.geometria] + forma = "sferica" + nota = "Sono una proprietà del frutto" + + [[frutto.colore]] + nome = "rosso" + nota = "Sono un oggetto di un array dentro mela" + + [[frutto.colore]] + nome = "verde" + nota = "Sono nello stesso array di rosso" + +[[frutta]] + nome = "banana" + + [[frutto.colore]] + nome = "giallo" + nota = "Anche io sono un oggetto di un array, ma dentro banana" +``` + +Ecco l'equivalente JSON dell'ultima tabella: + +```json +{ + "frutta": [ + { + "nome": "mela", + "geometria": { "forma": "sferica", "nota": "..."}, + "colore": [ + { "nome": "rosso", "nota": "..." }, + { "nome": "verde", "nota": "..." } + ] + }, + { + "nome": "banana", + "colore": [ + { "nome": "giallo", "nota": "..." } + ] + } + ] +} +``` + +### Altre risorse + ++ [Repository ufficiale di TOML](https://github.com/toml-lang/toml) diff --git a/it-it/typescript-it.html.markdown b/it-it/typescript-it.html.markdown new file mode 100644 index 0000000000..b78705c5ea --- /dev/null +++ b/it-it/typescript-it.html.markdown @@ -0,0 +1,227 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Christian Grasso", "https://grasso.io"] +filename: learntypescript-it.ts +lang: it-it +--- + +TypeScript è un linguaggio basato su JavaScript che punta a rendere il codice +più scalabile introducendo concetti quali le classi, i moduli, le interface, +e i generics. +Poichè TypeScript è un superset di JavaScript, è possibile sfruttare le sue +funzionalità anche in progetti esistenti: il codice JavaScript valido è anche +valido in TypeScript. Il compilatore di TypeScript genera codice JavaScript. + +Questo articolo si concentrerà solo sulle funzionalità aggiuntive di TypeScript. + +Per testare il compilatore, puoi utilizzare il +[Playground](http://www.typescriptlang.org/Playground), dove potrai scrivere +codice TypeScript e visualizzare l'output in JavaScript. + +```ts +// TypeScript ha tre tipi di base +let completato: boolean = false; +let righe: number = 42; +let nome: string = "Andrea"; + +// Il tipo può essere omesso se è presente un assegnamento a scalari/literal +let completato = false; +let righe = 42; +let nome = "Andrea"; + +// Il tipo "any" indica che la variabile può essere di qualsiasi tipo +let qualsiasi: any = 4; +qualsiasi = "oppure una stringa"; +qualsiasi = false; // o magari un boolean + +// Usa la keyword "const" per le costanti +const numeroViteGatti = 9; +numeroViteGatti = 1; // Errore + +// Per gli array, puoi usare l'apposito tipo o la versione con i generics +let lista: number[] = [1, 2, 3]; +let lista: Array = [1, 2, 3]; + +// Per le enumerazioni: +enum Colore { Rosso, Verde, Blu }; +let c: Colore = Colore.Verde; + +// Infine, "void" viene utilizzato per le funzioni che non restituiscono valori +function avviso(): void { + alert("Sono un piccolo avviso fastidioso!"); +} + +// Le funzioni supportano la sintassi "a freccia" (lambda) e supportano la type +// inference, cioè per scalari/literal non c'è bisogno di specificare il tipo + +// Tutte le seguenti funzioni sono equivalenti, e il compilatore genererà +// lo stesso codice JavaScript per ognuna di esse +let f1 = function (i: number): number { return i * i; } +// Type inference +let f2 = function (i: number) { return i * i; } +// Sintassi lambda +let f3 = (i: number): number => { return i * i; } +// Sintassi lambda + type inference +let f4 = (i: number) => { return i * i; } +// Sintassi lambda + type inference + sintassi abbreviata (senza return) +let f5 = (i: number) => i * i; + +// Le interfacce sono strutturali, e qualunque oggetto con le stesse proprietà +// di un'interfaccia è compatibile con essa +interface Persona { + nome: string; + // Proprietà opzionale, indicata con "?" + anni?: number; + // Funzioni + saluta(): void; +} + +// Oggetto che implementa l'interfaccia Persona +// È una Persona valida poichè implementa tutta le proprietà non opzionali +let p: Persona = { nome: "Bobby", saluta: () => { } }; +// Naturalmente può avere anche le proprietà opzionali: +let pValida: Persona = { nome: "Bobby", anni: 42, saluta: () => { } }; +// Questa invece NON è una Persona, poichè il tipo di "anni" è sbagliato +let pNonValida: Persona = { nome: "Bobby", anni: true }; + +// Le interfacce possono anche descrivere una funzione +interface SearchFunc { + (source: string, subString: string): boolean; +} +// I nomi dei parametri non sono rilevanti: vengono controllati solo i tipi +let ricerca: SearchFunc; +ricerca = function (src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classi - i membri sono pubblici di default +class Punto { + // Proprietà + x: number; + + // Costruttore - in questo caso la keyword "public" può generare in automatico + // il codice per l'inizializzazione di una variabile. + // In questo esempio, verrà creata la variabile y in modo identico alla x, ma + // con meno codice. Sono supportati anche i valori di default. + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Funzioni + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Membri statici + static origine = new Point(0, 0); +} + +// Le classi possono anche implementare esplicitamente delle interfacce. +// Il compilatore restituirà un errore nel caso in cui manchino delle proprietà. +class PersonaDiRiferimento implements Persona { + nome: string + saluta() {} +} + +let p1 = new Punto(10, 20); +let p2 = new Punto(25); // y = 0 + +// Inheritance +class Punto3D extends Punto { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // La chiamata esplicita a super è obbligatoria + } + + // Sovrascrittura + dist() { + let d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Moduli - "." può essere usato come separatore per i sottomoduli +module Geometria { + export class Quadrato { + constructor(public lato: number = 0) { } + + area() { + return Math.pow(this.lato, 2); + } + } +} + +let s1 = new Geometria.Quadrato(5); + +// Alias locale per un modulo +import G = Geometria; + +let s2 = new G.Quadrato(10); + +// Generics +// Classi +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfacce +interface Pair { + item1: T; + item2: T; +} + +// E funzioni +let pairToTuple = function (p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +let tuple = pairToTuple({ item1: "hello", item2: "world" }); + +// Interpolazione con le template string (definite con i backtick) +let nome = 'Tyrone'; +let saluto = `Ciao ${name}, come stai?` +// Possono anche estendersi su più righe +let multiriga = `Questo è un esempio +di stringa multiriga.`; + +// La keyword "readonly" rende un membro di sola lettura +interface Persona { + readonly nome: string; + readonly anni: number; +} + +var p1: Persona = { nome: "Tyrone", anni: 42 }; +p1.anni = 25; // Errore, p1.anni è readonly + +var p2 = { nome: "John", anni: 60 }; +var p3: Person = p2; // Ok, abbiamo creato una versione readonly di p2 +p3.anni = 35; // Errore, p3.anni è readonly +p2.anni = 45; // Compila, ma cambia anche p3.anni per via dell'aliasing! + +class Macchina { + readonly marca: string; + readonly modello: string; + readonly anno = 2018; + + constructor() { + // Possiamo anche assegnare nel constructor + this.marca = "Marca sconosciuta"; + this.modello = "Modello sconosciuto"; + } +} + +let numeri: Array = [0, 1, 2, 3, 4]; +let altriNumeri: ReadonlyArray = numbers; +altriNumeri[5] = 5; // Errore, gli elementi sono readonly +altriNumeri.push(5); // Errore, il metodo push non esiste (modifica l'array) +altriNumeri.length = 3; // Errore, length è readonly +numeri = altriNumeri; // Errore, i metodi di modifica non esistono +``` + +## Altre risorse + * [Sito ufficiale di TypeScript](http://www.typescriptlang.org/) + * [Specifica di TypeScript](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) + * [Anders Hejlsberg - Introducing TypeScript su Channel 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [TypeScript su GitHub](https://github.com/Microsoft/TypeScript) + * [Definitely Typed - definizioni per le librerie](http://definitelytyped.org/) diff --git a/java.html.markdown b/java.html.markdown index 7b59b08542..ca0b04c247 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -11,6 +11,7 @@ contributors: - ["Michael Dähnert", "https://github.com/JaXt0r"] - ["Rob Rose", "https://github.com/RobRoseKnows"] - ["Sean Nam", "https://github.com/seannam"] + - ["Shawn M. Hanes", "https://github.com/smhanes15"] filename: LearnJava.java --- @@ -44,8 +45,6 @@ import java.util.ArrayList; // Import all classes inside of java.security package import java.security.*; -// Each .java file contains one outer-level public class, with the same name -// as the file. public class LearnJava { // In order to run a java program, it must have a main method as an entry @@ -173,7 +172,7 @@ public class LearnJava { // Char - A single 16-bit Unicode character char fooChar = 'A'; - // final variables can't be reassigned to another object, + // final variables can't be reassigned, final int HOURS_I_WORK_PER_WEEK = 9001; // but they can be initialized later. final double E; @@ -280,7 +279,7 @@ public class LearnJava { // LinkedLists - Implementation of doubly-linked list. All of the // operations perform as could be expected for a // doubly-linked list. - // Maps - A set of objects that map keys to values. Map is + // Maps - A mapping of key Objects to value Objects. Map is // an interface and therefore cannot be instantiated. // The type of keys and values contained in a Map must // be specified upon instantiation of the implementing @@ -289,10 +288,16 @@ public class LearnJava { // HashMaps - This class uses a hashtable to implement the Map // interface. This allows the execution time of basic // operations, such as get and insert element, to remain - // constant even for large sets. - // TreeMap - This class is a sorted tree structure. It implements a red - // black tree and sorts the entries based on the key value or - // the comparator provided while creating the object + // constant-amortized even for large sets. + // TreeMap - A Map that is sorted by its keys. Each modification + // maintains the sorting defined by either a Comparator + // supplied at instantiation, or comparisons of each Object + // if they implement the Comparable interface. + // Failure of keys to implement Comparable combined with failure to + // supply a Comparator will throw ClassCastExceptions. + // Insertion and removal operations take O(log(n)) time + // so avoid using this data structure unless you are taking + // advantage of the sorting. /////////////////////////////////////// // Operators @@ -306,7 +311,7 @@ public class LearnJava { System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int) - System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + System.out.println("1/2.0 = " + (i1 / (double)i2)); // => 0.5 // Modulo System.out.println("11%3 = "+(11 % 3)); // => 2 @@ -703,15 +708,21 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // // Method declarations // } -// Marking a class as abstract means that it contains at least one abstract -// method that must be defined in a child class. Similar to interfaces, abstract -// classes cannot be instantiated, but instead must be extended and the abstract -// methods defined. Different from interfaces, abstract classes can contain a -// mixture of concrete and abstract methods. Methods in an interface cannot -// have a body, unless the method is static, and variables are final by default, -// unlike an abstract class. Also abstract classes CAN have the "main" method. +// Abstract Classes cannot be instantiated. +// Abstract classes may define abstract methods. +// Abstract methods have no body and are marked abstract +// Non-abstract child classes must @Override all abstract methods +// from their super-classes. +// Abstract classes can be useful when combining repetitive logic +// with customised behavior, but as Abstract classes require +// inheritance, they violate "Composition over inheritance" +// so consider other approaches using composition. +// https://en.wikipedia.org/wiki/Composition_over_inheritance + public abstract class Animal { + private int age; + public abstract void makeSound(); // Method can have a body @@ -722,17 +733,12 @@ public abstract class Animal age = 30; } - // No need to initialize, however in an interface - // a variable is implicitly final and hence has - // to be initialized. - private int age; - public void printAge() { System.out.println(age); } - // Abstract classes can have main function. + // Abstract classes can have main method. public static void main(String[] args) { System.out.println("I am abstract"); @@ -853,6 +859,108 @@ public class EnumTest { // The enum body can include methods and other fields. // You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html +// Getting Started with Lambda Expressions +// +// New to Java version 8 are lambda expressions. Lambdas are more commonly found +// in functional programming languages, which means they are methods which can +// be created without belonging to a class, passed around as if it were itself +// an object, and executed on demand. +// +// Final note, lambdas must implement a functional interface. A functional +// interface is one which has only a single abstract method declared. It can +// have any number of default methods. Lambda expressions can be used as an +// instance of that functional interface. Any interface meeting the requirements +// is treated as a functional interface. You can read more about interfaces +// above. +// +import java.util.Map; +import java.util.HashMap; +import java.util.function.*; +import java.security.SecureRandom; + +public class Lambdas { + public static void main(String[] args) { + // Lambda declaration syntax: + // -> + + // We will use this hashmap in our examples below. + Map planets = new HashMap<>(); + planets.put("Mercury", "87.969"); + planets.put("Venus", "224.7"); + planets.put("Earth", "365.2564"); + planets.put("Mars", "687"); + planets.put("Jupiter", "4,332.59"); + planets.put("Saturn", "10,759"); + planets.put("Uranus", "30,688.5"); + planets.put("Neptune", "60,182"); + + // Lambda with zero parameters using the Supplier functional interface + // from java.util.function.Supplier. The actual lambda expression is + // what comes after numPlanets =. + Supplier numPlanets = () -> Integer.toString(planets.size()); + System.out.format("Number of Planets: %s\n\n", numPlanets.get()); + + // Lambda with one parameter and using the Consumer functional interface + // from java.util.function.Consumer. This is because planets is a Map, + // which implements both Collection and Iterable. The forEach used here, + // found in Iterable, applies the lambda expression to each member of + // the Collection. The default implementation of forEach behaves as if: + /* + for (T t : this) + action.accept(t); + */ + + // The actual lambda expression is the parameter passed to forEach. + planets.keySet().forEach((p) -> System.out.format("%s\n", p)); + + // If you are only passing a single argument, then the above can also be + // written as (note absent parentheses around p): + planets.keySet().forEach(p -> System.out.format("%s\n", p)); + + // Tracing the above, we see that planets is a HashMap, keySet() returns + // a Set of its keys, forEach applies each element as the lambda + // expression of: (parameter p) -> System.out.format("%s\n", p). Each + // time, the element is said to be "consumed" and the statement(s) + // referred to in the lambda body is applied. Remember the lambda body + // is what comes after the ->. + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format("%s\n", planet); + } + + // This example differs from the above in that a different forEach + // implementation is used: the forEach found in the HashMap class + // implementing the Map interface. This forEach accepts a BiConsumer, + // which generically speaking is a fancy way of saying it handles + // the Set of each Key -> Value pairs. This default implementation + // behaves as if: + /* + for (Map.Entry entry : map.entrySet()) + action.accept(entry.getKey(), entry.getValue()); + */ + + // The actual lambda expression is the parameter passed to forEach. + String orbits = "%s orbits the Sun in %s Earth days.\n"; + planets.forEach((K, V) -> System.out.format(orbits, K, V)); + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format(orbits, planet, planets.get(planet)); + } + + // Or, if following more closely the specification provided by the + // default implementation: + for (Map.Entry planet : planets.entrySet()) { + System.out.format(orbits, planet.getKey(), planet.getValue()); + } + + // These examples cover only the very basic use of lambdas. It might not + // seem like much or even very useful, but remember that a lambda can be + // created as an object that can later be passed as parameters to other + // methods. + } +} ``` ## Further Reading diff --git a/javascript.html.markdown b/javascript.html.markdown index 85c8a52d26..ecaf02c5c2 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -103,7 +103,7 @@ false; // ... which works with more than just strings "1, 2, " + 3; // = "1, 2, 3" -"Hello " + ["world", "!"] // = "Hello world,!" +"Hello " + ["world", "!"]; // = "Hello world,!" // and are compared with < and > "a" < "b"; // = true @@ -180,6 +180,24 @@ myArray.length; // = 4 // Add/Modify at specific index myArray[3] = "Hello"; +// Add and remove element from front or back end of an array +myArray.unshift(3); // Add as the first element +someVar = myArray.shift(); // Remove first element and return it +myArray.push(3); // Add as the last element +someVar = myArray.pop(); // Remove last element and return it + +// Join all elements of an array with semicolon +var myArray0 = [32,false,"js",12,56,90]; +myArray0.join(";") // = "32;false;js;12;56;90" + +// Get subarray of elements from index 1 (include) to 4 (exclude) +myArray0.slice(1,4); // = [false,"js",12] + +// Remove 4 elements starting from index 2, and insert there strings +// "hi","wr" and "ld"; return removed subarray +myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90] +// myArray0 === [32,false,"hi","wr","ld"] + // JavaScript's objects are equivalent to "dictionaries" or "maps" in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; @@ -222,7 +240,7 @@ while (true){ var input; do { input = getInput(); -} while (!isValid(input)) +} while (!isValid(input)); // The `for` loop is the same as C and Java: // initialization; continue condition; iteration. @@ -248,6 +266,15 @@ for (var x in person){ description += person[x] + " "; } // description = 'Paul Ken 18 ' +// The for/of statement allows iteration over iterable objects (including the built-in String, +// Array, e.g. the Array-like arguments or NodeList objects, TypedArray, Map and Set, +// and user-defined iterables). +var myPets = ""; +var pets = ["cat", "dog", "hamster", "hedgehog"]; +for (var pet of pets){ + myPets += pet + " "; +} // myPets = 'cat dog hamster hedgehog ' + // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ house.contains = "bear"; @@ -293,7 +320,7 @@ myFunction("foo"); // = "FOO" // automatic semicolon insertion. Watch out for this when using Allman style. function myFunction(){ return // <- semicolon automatically inserted here - {thisIsAn: 'object literal'} + {thisIsAn: 'object literal'}; } myFunction(); // = undefined @@ -388,7 +415,7 @@ myFunc(); // = undefined // through `this`, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase(); -} +}; myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" @@ -397,7 +424,7 @@ myObj.myOtherFunc(); // = "HELLO WORLD!" var anotherFunc = function(s){ return this.myString + s; -} +}; anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" // The `apply` function is nearly identical, but takes an array for an argument @@ -420,7 +447,7 @@ boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" // `bind` can also be used to partially apply (curry) a function. -var product = function(a, b){ return a * b; } +var product = function(a, b){ return a * b; }; var doubler = product.bind(this, 2); doubler(8); // = 16 @@ -430,11 +457,11 @@ doubler(8); // = 16 var MyConstructor = function(){ this.myNumber = 5; -} +}; myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Unlike most other popular object-oriented languages, JavaScript has no +// Unlike most other popular object-oriented languages, JavaScript has no // concept of 'instances' created from 'class' blueprints; instead, JavaScript // combines instantiation and inheritance into a single concept: a 'prototype'. @@ -451,7 +478,7 @@ var myObj = { var myPrototype = { meaningOfLife: 42, myFunc: function(){ - return this.myString.toLowerCase() + return this.myString.toLowerCase(); } }; @@ -515,7 +542,7 @@ MyConstructor.prototype = { }; var myNewObj2 = new MyConstructor(); myNewObj2.getMyNumber(); // = 5 -myNewObj2.myNumber = 6 +myNewObj2.myNumber = 6; myNewObj2.getMyNumber(); // = 6 // Built-in types like strings and numbers also have constructors that create @@ -540,7 +567,7 @@ if (new Number(0)){ // you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ return this.charAt(0); -} +}; "abc".firstCharacter(); // = "a" // This fact is often used in "polyfilling", which is implementing newer @@ -556,7 +583,7 @@ if (Object.create === undefined){ // don't overwrite it if it exists Constructor.prototype = proto; // then use it to create a new, appropriately-prototyped object return new Constructor(); - } + }; } ``` @@ -582,13 +609,13 @@ of the language. [Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal -[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great -derivative of Eloquent Javascript with extra explanations and clarifications for -some of the more complicated examples. - [Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. +[Javascript:Info][11] is a modern javascript tutorial covering the basics (core language and working with a browser) +as well as advanced topics with concise explanations. + + In addition to direct contributors to this article, some content is adapted from Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the Mozilla Developer Network. @@ -602,5 +629,5 @@ Mozilla Developer Network. [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/ -[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version [10]: http://jstherightway.org/ +[11]: https://javascript.info/ diff --git a/jquery.html.markdown b/jquery.html.markdown index 9326c74b20..a1673c1052 100644 --- a/jquery.html.markdown +++ b/jquery.html.markdown @@ -104,7 +104,7 @@ tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction); // 3. Manipulation // These are similar to effects but can do more -$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div +$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div // Common manipulation methods $('p').append('Hello world'); // Adds to end of element @@ -126,3 +126,7 @@ $('p').each(function() { ``` + +## Further Reading + +* [Codecademy - jQuery](https://www.codecademy.com/learn/learn-jquery) A good introduction to jQuery in a "learn by doing it" format. diff --git a/json.html.markdown b/json.html.markdown index cd42d42d58..322c7a47b0 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -81,3 +81,5 @@ Supported data types: ## Further Reading * [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics. + +* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) A concise introduction to JSON. diff --git a/julia.html.markdown b/julia.html.markdown index 85033aa6f5..2fe05c49a1 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -2,17 +2,18 @@ language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] - - ["Pranit Bauva", "http://github.com/pranitbauva1997"] + - ["Pranit Bauva", "https://github.com/pranitbauva1997"] + - ["Daniel YC Lin", "https://github.com/dlintw"] filename: learnjulia.jl --- Julia is a new homoiconic functional language focused on technical computing. -While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. +While having the full power of homoiconic macros, first-class functions, +and low-level control, Julia is as easy to learn and use as Python. -This is based on Julia 0.4. - -```ruby +This is based on Julia 1.0.0 +```julia # Single line comments start with a hash (pound) symbol. #= Multiline comments can be written by putting '#=' before the text and '=#' @@ -26,38 +27,38 @@ This is based on Julia 0.4. # Everything in Julia is an expression. # There are several basic types of numbers. -3 # => 3 (Int64) -3.2 # => 3.2 (Float64) -2 + 1im # => 2 + 1im (Complex{Int64}) -2//3 # => 2//3 (Rational{Int64}) +typeof(3) # => Int64 +typeof(3.2) # => Float64 +typeof(2 + 1im) # => Complex{Int64} +typeof(2 // 3) # => Rational{Int64} # All of the normal infix operators are available. -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 -5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float -div(5, 2) # => 2 # for a truncated result, use div -5 \ 35 # => 7.0 -2 ^ 2 # => 4 # power, not bitwise xor -12 % 10 # => 2 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +10 / 2 # => 5.0 # dividing integers always results in a Float64 +div(5, 2) # => 2 # for a truncated result, use div +5 \ 35 # => 7.0 +2^2 # => 4 # power, not bitwise xor +12 % 10 # => 2 # Enforce precedence with parentheses -(1 + 3) * 2 # => 8 +(1 + 3) * 2 # => 8 # Bitwise Operators -~2 # => -3 # bitwise not -3 & 5 # => 1 # bitwise and -2 | 4 # => 6 # bitwise or -2 $ 4 # => 6 # bitwise xor -2 >>> 1 # => 1 # logical shift right -2 >> 1 # => 1 # arithmetic shift right -2 << 1 # => 4 # logical/arithmetic shift left - -# You can use the bits function to see the binary representation of a number. -bits(12345) +~2 # => -3 # bitwise not +3 & 5 # => 1 # bitwise and +2 | 4 # => 6 # bitwise or +xor(2, 4) # => 6 # bitwise xor +2 >>> 1 # => 1 # logical shift right +2 >> 1 # => 1 # arithmetic shift right +2 << 1 # => 4 # logical/arithmetic shift left + +# Use the bitstring function to see the binary representation of a number. +bitstring(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" -bits(12345.0) +bitstring(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" # Boolean values are primitives @@ -65,70 +66,70 @@ true false # Boolean operators -!true # => false -!false # => true -1 == 1 # => true -2 == 1 # => false -1 != 1 # => false -2 != 1 # => true -1 < 10 # => true -1 > 10 # => false -2 <= 2 # => true -2 >= 2 # => true +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true # Comparisons can be chained -1 < 2 < 3 # => true -2 < 3 < 2 # => false +1 < 2 < 3 # => true +2 < 3 < 2 # => false # Strings are created with " "This is a string." -# Julia has several types of strings, including ASCIIString and UTF8String. -# More on this in the Types section. - # Character literals are written with ' 'a' -# Some strings can be indexed like an array of characters -"This is a string"[1] # => 'T' # Julia indexes from 1 -# However, this is will not work well for UTF8 strings, -# so iterating over strings is recommended (map, for loops, etc). +# Strings are UTF8 encoded. Only if they contain only ASCII characters can +# they be safely indexed. +ascii("This is a string")[1] +# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase) +# Julia indexes from 1 +# Otherwise, iterating over strings is recommended (map, for loops, etc). # $ can be used for string interpolation: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" # You can put any Julia expression inside the parentheses. -# Another way to format strings is the printf macro. -@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 +# Another way to format strings is the printf macro from the stdlib Printf. +using Printf +@printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000 # Printing is easy -println("I'm Julia. Nice to meet you!") +println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you! # String can be compared lexicographically "good" > "bye" # => true "good" == "good" # => true -"1 + 2 = 3" == "1 + 2 = $(1+2)" # => true +"1 + 2 = 3" == "1 + 2 = $(1 + 2)" # => true #################################################### ## 2. Variables and Collections #################################################### # You don't declare variables before assigning to them. -some_var = 5 # => 5 -some_var # => 5 +someVar = 5 # => 5 +someVar # => 5 # Accessing a previously unassigned variable is an error try - some_other_var # => ERROR: some_other_var not defined + someOtherVar # => ERROR: UndefVarError: someOtherVar not defined catch e println(e) end # Variable names start with a letter or underscore. # After that, you can use letters, digits, underscores, and exclamation points. -SomeOtherVar123! = 6 # => 6 +SomeOtherVar123! = 6 # => 6 # You can also use certain unicode characters -☃ = 8 # => 8 +☃ = 8 # => 8 # These are especially handy for mathematical notation 2 * π # => 6.283185307179586 @@ -147,250 +148,280 @@ SomeOtherVar123! = 6 # => 6 # functions are sometimes called mutating functions or in-place functions. # Arrays store a sequence of values indexed by integers 1 through n: -a = Int64[] # => 0-element Int64 Array +a = Int64[] # => 0-element Array{Int64,1} # 1-dimensional array literals can be written with comma-separated values. -b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] -b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6] -b[1] # => 4 -b[end] # => 6 +b = [4, 5, 6] # => 3-element Array{Int64,1}: [4, 5, 6] +b = [4; 5; 6] # => 3-element Array{Int64,1}: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 # 2-dimensional arrays use space-separated values and semicolon-separated rows. -matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] +matrix = [1 2; 3 4] # => 2×2 Array{Int64,2}: [1 2; 3 4] -# Arrays of a particular Type -b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6] +# Arrays of a particular type +b = Int8[4, 5, 6] # => 3-element Array{Int8,1}: [4, 5, 6] # Add stuff to the end of a list with push! and append! -push!(a,1) # => [1] -push!(a,2) # => [1,2] -push!(a,4) # => [1,2,4] -push!(a,3) # => [1,2,4,3] -append!(a,b) # => [1,2,4,3,4,5,6] +push!(a, 1) # => [1] +push!(a, 2) # => [1,2] +push!(a, 4) # => [1,2,4] +push!(a, 3) # => [1,2,4,3] +append!(a, b) # => [1,2,4,3,4,5,6] # Remove from the end with pop -pop!(b) # => 6 and b is now [4,5] +pop!(b) # => 6 +b # => [4,5] # Let's put it back -push!(b,6) # b is now [4,5,6] again. +push!(b, 6) # => [4,5,6] +b # => [4,5,6] -a[1] # => 1 # remember that Julia indexes from 1, not 0! +a[1] # => 1 # remember that Julia indexes from 1, not 0! # end is a shorthand for the last index. It can be used in any # indexing expression -a[end] # => 6 +a[end] # => 6 -# we also have shift and unshift -shift!(a) # => 1 and a is now [2,4,3,4,5,6] -unshift!(a,7) # => [7,2,4,3,4,5,6] +# we also have popfirst! and pushfirst! +popfirst!(a) # => 1 +a # => [2,4,3,4,5,6] +pushfirst!(a, 7) # => [7,2,4,3,4,5,6] +a # => [7,2,4,3,4,5,6] # Function names that end in exclamations points indicate that they modify # their argument. -arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] -sort(arr) # => [4,5,6]; arr is still [5,4,6] -sort!(arr) # => [4,5,6]; arr is now [4,5,6] +arr = [5,4,6] # => 3-element Array{Int64,1}: [5,4,6] +sort(arr) # => [4,5,6] +arr # => [5,4,6] +sort!(arr) # => [4,5,6] +arr # => [4,5,6] # Looking out of bounds is a BoundsError try - a[0] # => ERROR: BoundsError() in getindex at array.jl:270 - a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 + a[0] + # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at + # index [0] + # => Stacktrace: + # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 + # => [2] top-level scope at none:0 + # => [3] ... + # => in expression starting at ...\LearnJulia.jl:180 + a[end + 1] + # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at + # index [8] + # => Stacktrace: + # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 + # => [2] top-level scope at none:0 + # => [3] ... + # => in expression starting at ...\LearnJulia.jl:188 catch e println(e) end # Errors list the line and file they came from, even if it's in the standard -# library. If you built Julia from source, you can look in the folder base -# inside the julia folder to find these files. +# library. You can look in the folder share/julia inside the julia folder to +# find these files. # You can initialize arrays from ranges -a = [1:5;] # => 5-element Int64 Array: [1,2,3,4,5] +a = [1:5;] # => 5-element Array{Int64,1}: [1,2,3,4,5] +a2 = [1:5] # => 1-element Array{UnitRange{Int64},1}: [1:5] # You can look at ranges with slice syntax. -a[1:3] # => [1, 2, 3] -a[2:end] # => [2, 3, 4, 5] +a[1:3] # => [1, 2, 3] +a[2:end] # => [2, 3, 4, 5] # Remove elements from an array by index with splice! arr = [3,4,5] -splice!(arr,2) # => 4 ; arr is now [3,5] +splice!(arr, 2) # => 4 +arr # => [3,5] # Concatenate lists with append! b = [1,2,3] -append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] +append!(a, b) # => [1, 2, 3, 4, 5, 1, 2, 3] +a # => [1, 2, 3, 4, 5, 1, 2, 3] # Check for existence in a list with in -in(1, a) # => true +in(1, a) # => true # Examine the length with length -length(a) # => 8 +length(a) # => 8 # Tuples are immutable. -tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +tup = (1, 2, 3) # => (1,2,3) +typeof(tup) # => Tuple{Int64,Int64,Int64} tup[1] # => 1 -try: - tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +try + tup[1] = 3 + # => ERROR: MethodError: no method matching + # setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64) catch e println(e) end -# Many list functions also work on tuples +# Many array functions also work on tuples length(tup) # => 3 -tup[1:2] # => (1,2) -in(2, tup) # => true +tup[1:2] # => (1,2) +in(2, tup) # => true # You can unpack tuples into variables -a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 +a, b, c = (1, 2, 3) # => (1,2,3) +a # => 1 +b # => 2 +c # => 3 # Tuples are created even if you leave out the parentheses -d, e, f = 4, 5, 6 # => (4,5,6) +d, e, f = 4, 5, 6 # => (4,5,6) +d # => 4 +e # => 5 +f # => 6 # A 1-element tuple is distinct from the value it contains (1,) == 1 # => false -(1) == 1 # => true +(1) == 1 # => true # Look how easy it is to swap two values -e, d = d, e # => (5,4) # d is now 5 and e is now 4 - +e, d = d, e # => (5,4) +d # => 5 +e # => 4 # Dictionaries store mappings -empty_dict = Dict() # => Dict{Any,Any}() +emptyDict = Dict() # => Dict{Any,Any} with 0 entries # You can create a dictionary using a literal -filled_dict = Dict("one"=> 1, "two"=> 2, "three"=> 3) -# => Dict{ASCIIString,Int64} +filledDict = Dict("one" => 1, "two" => 2, "three" => 3) +# => Dict{String,Int64} with 3 entries: +# => "two" => 2, "one" => 1, "three" => 3 # Look up values with [] -filled_dict["one"] # => 1 +filledDict["one"] # => 1 # Get all keys -keys(filled_dict) -# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +keys(filledDict) +# => Base.KeySet for a Dict{String,Int64} with 3 entries. Keys: +# => "two", "one", "three" # Note - dictionary keys are not sorted or in the order you inserted them. # Get all values -values(filled_dict) -# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +values(filledDict) +# => Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values: +# => 2, 1, 3 # Note - Same as above regarding key ordering. # Check for existence of keys in a dictionary with in, haskey -in(("one" => 1), filled_dict) # => true -in(("two" => 3), filled_dict) # => false -haskey(filled_dict, "one") # => true -haskey(filled_dict, 1) # => false +in(("one" => 1), filledDict) # => true +in(("two" => 3), filledDict) # => false +haskey(filledDict, "one") # => true +haskey(filledDict, 1) # => false # Trying to look up a non-existent key will raise an error try - filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 + filledDict["four"] # => ERROR: KeyError: key "four" not found catch e println(e) end # Use the get method to avoid that error by providing a default value -# get(dictionary,key,default_value) -get(filled_dict,"one",4) # => 1 -get(filled_dict,"four",4) # => 4 +# get(dictionary, key, defaultValue) +get(filledDict, "one", 4) # => 1 +get(filledDict, "four", 4) # => 4 # Use Sets to represent collections of unordered, unique values -empty_set = Set() # => Set{Any}() +emptySet = Set() # => Set(Any[]) # Initialize a set with values -filled_set = Set([1,2,2,3,4]) # => Set{Int64}(1,2,3,4) +filledSet = Set([1, 2, 2, 3, 4]) # => Set([4, 2, 3, 1]) # Add more values to a set -push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) +push!(filledSet, 5) # => Set([4, 2, 3, 5, 1]) # Check if the values are in the set -in(2, filled_set) # => true -in(10, filled_set) # => false +in(2, filledSet) # => true +in(10, filledSet) # => false # There are functions for set intersection, union, and difference. -other_set = Set([3, 4, 5, 6]) # => Set{Int64}(6,4,5,3) -intersect(filled_set, other_set) # => Set{Int64}(3,4,5) -union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) -setdiff(Set([1,2,3,4]),Set([2,3,5])) # => Set{Int64}(1,4) - +otherSet = Set([3, 4, 5, 6]) # => Set([4, 3, 5, 6]) +intersect(filledSet, otherSet) # => Set([4, 3, 5]) +union(filledSet, otherSet) # => Set([4, 2, 3, 5, 6, 1]) +setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1]) #################################################### ## 3. Control Flow #################################################### # Let's make a variable -some_var = 5 +someVar = 5 # Here is an if statement. Indentation is not meaningful in Julia. -if some_var > 10 - println("some_var is totally bigger than 10.") -elseif some_var < 10 # This elseif clause is optional. - println("some_var is smaller than 10.") +if someVar > 10 + println("someVar is totally bigger than 10.") +elseif someVar < 10 # This elseif clause is optional. + println("someVar is smaller than 10.") else # The else clause is optional too. - println("some_var is indeed 10.") + println("someVar is indeed 10.") end # => prints "some var is smaller than 10" - # For loops iterate over iterables. # Iterable types include Range, Array, Set, Dict, and AbstractString. -for animal=["dog", "cat", "mouse"] +for animal = ["dog", "cat", "mouse"] println("$animal is a mammal") # You can use $ to interpolate variables or expression into strings end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => dog is a mammal +# => cat is a mammal +# => mouse is a mammal # You can use 'in' instead of '='. for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => dog is a mammal +# => cat is a mammal +# => mouse is a mammal -for a in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal") - println("$(a[1]) is a $(a[2])") +for pair in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal") + from, to = pair + println("$from is a $to") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => mouse is a mammal +# => cat is a mammal +# => dog is a mammal -for (k,v) in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal") +for (k, v) in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal") println("$k is a $v") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => mouse is a mammal +# => cat is a mammal +# => dog is a mammal # While loops loop while a condition is true -x = 0 -while x < 4 - println(x) - x += 1 # Shorthand for x = x + 1 +let x = 0 + while x < 4 + println(x) + x += 1 # Shorthand for x = x + 1 + end end -# prints: -# 0 -# 1 -# 2 -# 3 +# => 0 +# => 1 +# => 2 +# => 3 # Handle exceptions with a try/catch block try - error("help") + error("help") catch e - println("caught it $e") + println("caught it $e") end # => caught it ErrorException("help") - #################################################### ## 4. Functions #################################################### # The keyword 'function' creates new functions -#function name(arglist) -# body... -#end +# function name(arglist) +# body... +# end function add(x, y) println("x is $x and y is $y") @@ -398,15 +429,17 @@ function add(x, y) x + y end -add(5, 6) # => 11 after printing out "x is 5 and y is 6" +add(5, 6) +# => x is 5 and y is 6 +# => 11 # Compact assignment of functions -f_add(x, y) = x + y # => "f (generic function with 1 method)" -f_add(3, 4) # => 7 +f_add(x, y) = x + y # => f_add (generic function with 1 method) +f_add(3, 4) # => 7 # Function can also return multiple values as tuple -f(x, y) = x + y, x - y -f(3, 4) # => (7, -1) +fn(x, y) = x + y, x - y # => fn (generic function with 1 method) +fn(3, 4) # => (7, -1) # You can define functions that take a variable number of # positional arguments @@ -416,54 +449,56 @@ function varargs(args...) end # => varargs (generic function with 1 method) -varargs(1,2,3) # => (1,2,3) +varargs(1, 2, 3) # => (1,2,3) # The ... is called a splat. # We just used it in a function definition. # It can also be used in a function call, # where it will splat an Array or Tuple's contents into the argument list. -add([5,6]...) # this is equivalent to add(5,6) +add([5,6]...) # this is equivalent to add(5,6) -x = (5,6) # => (5,6) -add(x...) # this is equivalent to add(5,6) +x = (5, 6) # => (5,6) +add(x...) # this is equivalent to add(5,6) # You can define functions with optional positional arguments -function defaults(a,b,x=5,y=6) +function defaults(a, b, x=5, y=6) return "$a $b and $x $y" end +# => defaults (generic function with 3 methods) -defaults('h','g') # => "h g and 5 6" -defaults('h','g','j') # => "h g and j 6" -defaults('h','g','j','k') # => "h g and j k" +defaults('h', 'g') # => "h g and 5 6" +defaults('h', 'g', 'j') # => "h g and j 6" +defaults('h', 'g', 'j', 'k') # => "h g and j k" try - defaults('h') # => ERROR: no method defaults(Char,) - defaults() # => ERROR: no methods defaults() + defaults('h') # => ERROR: MethodError: no method matching defaults(::Char) + defaults() # => ERROR: MethodError: no method matching defaults() catch e println(e) end # You can define functions that take keyword arguments -function keyword_args(;k1=4,name2="hello") # note the ; - return Dict("k1"=>k1,"name2"=>name2) +function keyword_args(;k1=4, name2="hello") # note the ; + return Dict("k1" => k1, "name2" => name2) end +# => keyword_args (generic function with 1 method) -keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] -keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] -keyword_args() # => ["name2"=>"hello","k1"=>4] +keyword_args(name2="ness") # => ["name2"=>"ness", "k1"=>4] +keyword_args(k1="mine") # => ["name2"=>"hello", "k1"=>"mine"] +keyword_args() # => ["name2"=>"hello", "k1"=>4] # You can combine all kinds of arguments in the same function -function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") - println("normal arg: $normal_arg") - println("optional arg: $optional_positional_arg") - println("keyword arg: $keyword_arg") +function all_the_args(normalArg, optionalPositionalArg=2; keywordArg="foo") + println("normal arg: $normalArg") + println("optional arg: $optionalPositionalArg") + println("keyword arg: $keywordArg") end +# => all_the_args (generic function with 2 methods) -all_the_args(1, 3, keyword_arg=4) -# prints: -# normal arg: 1 -# optional arg: 3 -# keyword arg: 4 +all_the_args(1, 3, keywordArg=4) +# => normal arg: 1 +# => optional arg: 3 +# => keyword arg: 4 # Julia has first class functions function create_adder(x) @@ -472,14 +507,16 @@ function create_adder(x) end return adder end +# => create_adder (generic function with 1 method) # This is "stabby lambda syntax" for creating anonymous functions -(x -> x > 2)(3) # => true +(x -> x > 2)(3) # => true # This function is identical to create_adder implementation above. function create_adder(x) y -> x + y end +# => create_adder (generic function with 1 method) # You can also name the internal function, if you want function create_adder(x) @@ -488,18 +525,21 @@ function create_adder(x) end adder end +# => create_adder (generic function with 1 method) -add_10 = create_adder(10) +add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) + # (generic function with 1 method) add_10(3) # => 13 # There are built-in higher order functions -map(add_10, [1,2,3]) # => [11, 12, 13] -filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -# We can use list comprehensions for nicer maps -[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +# We can use list comprehensions +[add_10(i) for i = [1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### ## 5. Types @@ -508,11 +548,11 @@ filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # Julia has a type system. # Every value has a type; variables do not have types themselves. # You can use the `typeof` function to get the type of a value. -typeof(5) # => Int64 +typeof(5) # => Int64 # Types are first-class values -typeof(Int64) # => DataType -typeof(DataType) # => DataType +typeof(Int64) # => DataType +typeof(DataType) # => DataType # DataType is the type that represents types, including itself. # Types are used for documentation, optimizations, and dispatch. @@ -520,80 +560,76 @@ typeof(DataType) # => DataType # Users can define types # They are like records or structs in other languages. -# New types are defined using the `type` keyword. +# New types are defined using the `struct` keyword. -# type Name +# struct Name # field::OptionalType # ... # end -type Tiger - taillength::Float64 - coatcolor # not including a type annotation is the same as `::Any` +struct Tiger + taillength::Float64 + coatcolor # not including a type annotation is the same as `::Any` end # The default constructor's arguments are the properties # of the type, in the order they are listed in the definition -tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") +tigger = Tiger(3.5, "orange") # => Tiger(3.5,"orange") # The type doubles as the constructor function for values of that type -sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") +sherekhan = typeof(tigger)(5.6, "fire") # => Tiger(5.6,"fire") # These struct-style types are called concrete types # They can be instantiated, but cannot have subtypes. # The other kind of types is abstract types. # abstract Name -abstract Cat # just a name and point in the type hierarchy +abstract type Cat end # just a name and point in the type hierarchy # Abstract types cannot be instantiated, but can have subtypes. # For example, Number is an abstract type -subtypes(Number) # => 2-element Array{Any,1}: - # Complex{T<:Real} - # Real -subtypes(Cat) # => 0-element Array{Any,1} +subtypes(Number) # => 2-element Array{Any,1}: + # => Complex + # => Real +subtypes(Cat) # => 0-element Array{Any,1} # AbstractString, as the name implies, is also an abstract type -subtypes(AbstractString) # 8-element Array{Any,1}: - # Base.SubstitutionString{T<:AbstractString} - # DirectIndexString - # RepString - # RevString{T<:AbstractString} - # RopeString - # SubString{T<:AbstractString} - # UTF16String - # UTF8String - -# Every type has a super type; use the `super` function to get it. +subtypes(AbstractString) # => 4-element Array{Any,1}: + # => String + # => SubString + # => SubstitutionString + # => Test.GenericString + +# Every type has a super type; use the `supertype` function to get it. typeof(5) # => Int64 -super(Int64) # => Signed -super(Signed) # => Integer -super(Integer) # => Real -super(Real) # => Number -super(Number) # => Any -super(super(Signed)) # => Real -super(Any) # => Any +supertype(Int64) # => Signed +supertype(Signed) # => Integer +supertype(Integer) # => Real +supertype(Real) # => Number +supertype(Number) # => Any +supertype(supertype(Signed)) # => Real +supertype(Any) # => Any # All of these type, except for Int64, are abstract. -typeof("fire") # => ASCIIString -super(ASCIIString) # => DirectIndexString -super(DirectIndexString) # => AbstractString -# Likewise here with ASCIIString +typeof("fire") # => String +supertype(String) # => AbstractString +# Likewise here with String +supertype(SubString) # => AbstractString # <: is the subtyping operator -type Lion <: Cat # Lion is a subtype of Cat - mane_color - roar::AbstractString +struct Lion <: Cat # Lion is a subtype of Cat + maneColor + roar::AbstractString end # You can define more constructors for your type # Just define a function of the same name as the type # and call an existing constructor to get a value of the correct type -Lion(roar::AbstractString) = Lion("green",roar) +Lion(roar::AbstractString) = Lion("green", roar) # This is an outer constructor because it's outside the type definition -type Panther <: Cat # Panther is also a subtype of Cat - eye_color - Panther() = new("green") - # Panthers will only have this constructor, and no default constructor. +struct Panther <: Cat # Panther is also a subtype of Cat + eyeColor + Panther() = new("green") + # Panthers will only have this constructor, and no default constructor. end # Using inner constructors, like Panther does, gives you control # over how values of the type can be created. @@ -611,35 +647,36 @@ end # Definitions for Lion, Panther, Tiger function meow(animal::Lion) - animal.roar # access type properties using dot notation + animal.roar # access type properties using dot notation end function meow(animal::Panther) - "grrr" + "grrr" end function meow(animal::Tiger) - "rawwwr" + "rawwwr" end # Testing the meow function -meow(tigger) # => "rawwr" -meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(tigger) # => "rawwwr" +meow(Lion("brown", "ROAAR")) # => "ROAAR" meow(Panther()) # => "grrr" # Review the local type hierarchy -issubtype(Tiger,Cat) # => false -issubtype(Lion,Cat) # => true -issubtype(Panther,Cat) # => true +Tiger <: Cat # => false +Lion <: Cat # => true +Panther <: Cat # => true # Defining a function that takes Cats function pet_cat(cat::Cat) - println("The cat says $(meow(cat))") + println("The cat says $(meow(cat))") end +# => pet_cat (generic function with 1 method) -pet_cat(Lion("42")) # => prints "The cat says 42" +pet_cat(Lion("42")) # => The cat says 42 try - pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) + pet_cat(tigger) # => ERROR: MethodError: no method matching pet_cat(::Tiger) catch e println(e) end @@ -649,130 +686,179 @@ end # In Julia, all of the argument types contribute to selecting the best method. # Let's define a function with more arguments, so we can see the difference -function fight(t::Tiger,c::Cat) - println("The $(t.coatcolor) tiger wins!") +function fight(t::Tiger, c::Cat) + println("The $(t.coatcolor) tiger wins!") end # => fight (generic function with 1 method) -fight(tigger,Panther()) # => prints The orange tiger wins! -fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! +fight(tigger, Panther()) # => The orange tiger wins! +fight(tigger, Lion("ROAR")) # => The orange tiger wins! # Let's change the behavior when the Cat is specifically a Lion -fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +fight(t::Tiger, l::Lion) = println("The $(l.maneColor)-maned lion wins!") # => fight (generic function with 2 methods) -fight(tigger,Panther()) # => prints The orange tiger wins! -fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! +fight(tigger, Panther()) # => The orange tiger wins! +fight(tigger, Lion("ROAR")) # => The green-maned lion wins! # We don't need a Tiger in order to fight -fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +fight(l::Lion, c::Cat) = println("The victorious cat says $(meow(c))") # => fight (generic function with 3 methods) -fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +fight(Lion("balooga!"), Panther()) # => The victorious cat says grrr try - fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) -catch + fight(Panther(), Lion("RAWR")) + # => ERROR: MethodError: no method matching fight(::Panther, ::Lion) + # => Closest candidates are: + # => fight(::Tiger, ::Lion) at ... + # => fight(::Tiger, ::Cat) at ... + # => fight(::Lion, ::Cat) at ... + # => ... +catch e + println(e) end # Also let the cat go first -fight(c::Cat,l::Lion) = println("The cat beats the Lion") -# => Warning: New definition -# fight(Cat,Lion) at none:1 -# is ambiguous with -# fight(Lion,Cat) at none:2. -# Make sure -# fight(Lion,Lion) -# is defined first. -#fight (generic function with 4 methods) +fight(c::Cat, l::Lion) = println("The cat beats the Lion") +# => fight (generic function with 4 methods) # This warning is because it's unclear which fight will be called in: -fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +try + fight(Lion("RAR"), Lion("brown", "rarrr")) + # => ERROR: MethodError: fight(::Lion, ::Lion) is ambiguous. Candidates: + # => fight(c::Cat, l::Lion) in Main at ... + # => fight(l::Lion, c::Cat) in Main at ... + # => Possible fix, define + # => fight(::Lion, ::Lion) + # => ... +catch e + println(e) +end # The result may be different in other versions of Julia -fight(l::Lion,l2::Lion) = println("The lions come to a tie") -fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie +fight(l::Lion, l2::Lion) = println("The lions come to a tie") +# => fight (generic function with 5 methods) +fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie # Under the hood # You can take a look at the llvm and the assembly code generated. -square_area(l) = l * l # square_area (generic function with 1 method) +square_area(l) = l * l # square_area (generic function with 1 method) -square_area(5) #25 +square_area(5) # => 25 # What happens when we feed square_area an integer? -code_native(square_area, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 # Prologue - # push RBP - # mov RBP, RSP - # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # Square l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX - -code_native(square_area, (Float32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) - # pop RBP - # ret - -code_native(square_area, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) - # pop RBP - # ret - # +code_native(square_area, (Int32,), syntax = :intel) + # .text + # ; Function square_area { + # ; Location: REPL[116]:1 # Prologue + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: int.jl:54 + # imul ecx, ecx # Square l and store the result in ECX + # ;} + # mov eax, ecx + # pop rbp # Restore old base pointer + # ret # Result will still be in EAX + # nop dword ptr [rax + rax] + # ;} + +code_native(square_area, (Float32,), syntax = :intel) + # .text + # ; Function square_area { + # ; Location: REPL[116]:1 + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: float.jl:398 + # vmulss xmm0, xmm0, xmm0 # Scalar single precision multiply (AVX) + # ;} + # pop rbp + # ret + # nop word ptr [rax + rax] + # ;} + +code_native(square_area, (Float64,), syntax = :intel) + # .text + # ; Function square_area { + # ; Location: REPL[116]:1 + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd xmm0, xmm0, xmm0 # Scalar double precision multiply (AVX) + # ;} + # pop rbp + # ret + # nop word ptr [rax + rax] + # ;} + # Note that julia will use floating point instructions if any of the # arguments are floats. # Let's calculate the area of a circle circle_area(r) = pi * r * r # circle_area (generic function with 1 method) -circle_area(5) # 78.53981633974483 - -code_native(circle_area, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory - # movabs RAX, 4593140240 # Load pi - # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r - # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r - # pop RBP - # ret - # - -code_native(circle_area, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # movabs RAX, 4593140496 - # Source line: 1 - # vmulsd XMM1, XMM0, QWORD PTR [RAX] - # vmulsd XMM0, XMM1, XMM0 - # pop RBP - # ret - # +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,), syntax = :intel) + # .text + # ; Function circle_area { + # ; Location: REPL[121]:1 + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: operators.jl:502 + # ; Function *; { + # ; Location: promotion.jl:314 + # ; Function promote; { + # ; Location: promotion.jl:284 + # ; Function _promote; { + # ; Location: promotion.jl:261 + # ; Function convert; { + # ; Location: number.jl:7 + # ; Function Type; { + # ; Location: float.jl:60 + # vcvtsi2sd xmm0, xmm0, ecx # Load integer (r) from memory + # movabs rax, 497710928 # Load pi + # ;}}}}} + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd xmm1, xmm0, qword ptr [rax] # pi * r + # vmulsd xmm0, xmm1, xmm0 # (pi * r) * r + # ;}} + # pop rbp + # ret + # nop dword ptr [rax] + # ;} + +code_native(circle_area, (Float64,), syntax = :intel) + # .text + # ; Function circle_area { + # ; Location: REPL[121]:1 + # push rbp + # mov rbp, rsp + # movabs rax, 497711048 + # ; Function *; { + # ; Location: operators.jl:502 + # ; Function *; { + # ; Location: promotion.jl:314 + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd xmm1, xmm0, qword ptr [rax] + # ;}}} + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd xmm0, xmm1, xmm0 + # ;} + # pop rbp + # ret + # nop dword ptr [rax + rax] + # ;} ``` ## Further Reading -You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/#Manual-1) +You can get a lot more detail from the [Julia Documentation](https://docs.julialang.org/) The best place to get help with Julia is the (very friendly) [Discourse forum](https://discourse.julialang.org/). diff --git a/kdb+.html.markdown b/kdb+.html.markdown index 5ae86a4f2d..027b6571ae 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -76,7 +76,7 @@ floor 3.14159 / => 3 / ...getting the absolute value... abs -3.14159 / => 3.14159 / ...and many other things -/ see http://code.kx.com/wiki/Reference for more +/ see http://code.kx.com/q/ref/card/ for more / q has no operator precedence, everything is evaluated right to left / so results like this might take some getting used to @@ -174,7 +174,7 @@ t - 00:10:00.000 / => 00:50:00.000 d.year / => 2015i d.mm / => 12i d.dd / => 25i -/ see http://code.kx.com/wiki/JB:QforMortals2/atoms#Temporal_Data for more +/ see http://code.kx.com/q4m3/2_Basic_Data_Types_Atoms/#25-temporal-data for more / q also has an infinity value so div by zero will not throw an error 1%0 / => 0w @@ -183,7 +183,7 @@ d.dd / => 25i / And null types for representing missing values 0N / => null int 0n / => null float -/ see http://code.kx.com/wiki/JB:QforMortals2/atoms#Null_Values for more +/ see http://code.kx.com/q4m3/2_Basic_Data_Types_Atoms/#27-nulls for more / q has standard control structures / if is as you might expect (; separates the condition and instructions) @@ -642,7 +642,7 @@ kt upsert ([]name:`Thomas`Chester;age:33 58;height:175 179;sex:`f`m) / => Thomas 32 175 m / Most of the standard SQL joins are present in q-sql, plus a few new friends -/ see http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Joins +/ see http://code.kx.com/q4m3/9_Queries_q-sql/#99-joins / the two most important (commonly used) are lj and aj / lj is basically the same as SQL LEFT JOIN @@ -669,7 +669,7 @@ aj[`time`sym;trades;quotes] / => 10:01:04 ge 150 / for each row in the trade table, the last (prevailing) quote (px) for that sym / is joined on. -/ see http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Asof_Join +/ see http://code.kx.com/q4m3/9_Queries_q-sql/#998-as-of-joins //////////////////////////////////// ///// Extra/Advanced ////// @@ -689,14 +689,14 @@ first each (1 2 3;4 5 6;7 8 9) / each-left (\:) and each-right (/:) modify a two-argument function / to treat one of the arguments and individual variables instead of a list -1 2 3 +\: 1 2 3 -/ => 2 3 4 -/ => 3 4 5 -/ => 4 5 6 -1 2 3 +/: 1 2 3 -/ => 2 3 4 -/ => 3 4 5 -/ => 4 5 6 +1 2 3 +\: 11 22 33 +/ => 12 23 34 +/ => 13 24 35 +/ => 14 25 36 +1 2 3 +/: 11 22 33 +/ => 12 13 14 +/ => 23 24 25 +/ => 34 35 36 / The true alternatives to loops in q are the adverbs scan (\) and over (/) / their behaviour differs based on the number of arguments the function they @@ -716,7 +716,7 @@ first each (1 2 3;4 5 6;7 8 9) {x + y}/[1 2 3 4 5] / => 15 (only the final result) / There are other adverbs and uses, this is only intended as quick overview -/ http://code.kx.com/wiki/JB:QforMortals2/functions#Adverbs +/ http://code.kx.com/q4m3/6_Functions/#67-adverbs ////// Scripts ////// / q scripts can be loaded from a q session using the "\l" command @@ -756,7 +756,7 @@ select from splayed / (the columns are read from disk on request) / => 1 1 / => 2 2 / => 3 3 -/ see http://code.kx.com/wiki/JB:KdbplusForMortals/contents for more +/ see http://code.kx.com/q4m3/14_Introduction_to_Kdb+/ for more ////// Frameworks ////// / kdb+ is typically used for data capture and analysis. @@ -769,8 +769,8 @@ select from splayed / (the columns are read from disk on request) ## Want to know more? -* [*q for mortals* q language tutorial](http://code.kx.com/wiki/JB:QforMortals2/contents) -* [*kdb for mortals* on disk data tutorial](http://code.kx.com/wiki/JB:KdbplusForMortals/contents) -* [q language reference](http://code.kx.com/wiki/Reference) +* [*q for mortals* q language tutorial](http://code.kx.com/q4m3/) +* [*Introduction to Kdb+* on disk data tutorial](http://code.kx.com/q4m3/14_Introduction_to_Kdb+/) +* [q language reference](http://code.kx.com/q/ref/card/) * [Online training courses](http://training.aquaq.co.uk/) * [TorQ production framework](https://github.com/AquaQAnalytics/TorQ) diff --git a/ko-kr/markdown-kr.html.markdown b/ko-kr/markdown-kr.html.markdown index bfa2a87729..397e9f30ef 100644 --- a/ko-kr/markdown-kr.html.markdown +++ b/ko-kr/markdown-kr.html.markdown @@ -25,7 +25,7 @@ lang: ko-kr ## HTML 요소 HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마크다운이라는 것입니다. -```markdown +```md @@ -34,7 +34,7 @@ HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마 텍스트 앞에 붙이는 우물 정 기호(#)의 갯수에 따라 `

`부터 `

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

입니다. ##

입니다. ###

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

입니다. ``` 또한 h1과 h2를 나타내는 다른 방법이 있습니다. -```markdown +```md h1입니다. ============= @@ -53,7 +53,7 @@ h2입니다. ## 간단한 텍스트 꾸미기 마크다운으로 쉽게 텍스트를 기울이거나 굵게 할 수 있습니다. -```markdown +```md *기울인 텍스트입니다.* _이 텍스트도 같습니다._ @@ -65,14 +65,14 @@ __이 텍스트도 같습니다.__ *__이것도 같습니다.__* ``` 깃헙 전용 마크다운에는 취소선도 있습니다. -```markdown +```md ~~이 텍스트에는 취소선이 그려집니다.~~ ``` ## 문단 문단은 하나 이상의 빈 줄로 구분되는, 한 줄 이상의 인접한 텍스트입니다. -```markdown +```md 문단입니다. 문단에 글을 쓰다니 재밌지 않나요? 이제 두 번째 문단입니다. @@ -83,7 +83,7 @@ __이 텍스트도 같습니다.__ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어쓰기로 문단을 끝내고 새 문단을 시작할 수 있습니다. -```markdown +```md 띄어쓰기 두 개로 끝나는 문단 (마우스로 긁어 보세요). 이 위에는 `
` 태그가 있습니다. @@ -91,7 +91,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 인용문은 > 문자로 쉽게 쓸 수 있습니다. -```markdown +```md > 인용문입니다. 수동으로 개행하고서 > 줄마다 `>`를 칠 수도 있고 줄을 길게 쓴 다음에 저절로 개행되게 내버려 둘 수도 있습니다. > `>`로 시작하기만 한다면 차이가 없습니다. @@ -103,7 +103,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 ## 목록 순서가 없는 목록은 별표, 더하기, 하이픈을 이용해 만들 수 있습니다. -```markdown +```md * 이거 * 저거 * 그거 @@ -111,7 +111,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 또는 -```markdown +```md + 이거 + 저거 + 그거 @@ -119,7 +119,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 또는 -```markdown +```md - 이거 - 저거 - 그거 @@ -127,7 +127,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 순서가 있는 목록은 숫자와 마침표입니다. -```markdown +```md 1. 하나 2. 둘 3. 셋 @@ -135,7 +135,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 숫자를 정확히 붙이지 않더라도 제대로 된 순서로 보여주겠지만, 좋은 생각은 아닙니다. -```markdown +```md 1. 하나 1. 둘 1. 셋 @@ -144,7 +144,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 목록 안에 목록이 올 수도 있습니다. -```markdown +```md 1. 하나 2. 둘 3. 셋 @@ -155,7 +155,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 심지어 할 일 목록도 있습니다. HTML 체크박스가 만들어집니다. -```markdown +```md x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다. - [ ] 첫 번째 할 일 - [ ] 두 번째 할 일 @@ -168,13 +168,13 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다. 띄어쓰기 네 개 혹은 탭 한 개로 줄을 들여씀으로서 (` 요소를 사용하여`) 코드를 나타낼 수 있습니다. -```markdown +```md puts "Hello, world!" ``` 탭을 더 치거나 띄어쓰기를 네 번 더 함으로써 코드를 들여쓸 수 있습니다. -```markdown +```md my_array.each do |item| puts item end @@ -182,7 +182,7 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다. 인라인 코드는 백틱 문자를 이용하여 나타냅니다. ` -```markdown +```md 철수는 `go_to()` 함수가 뭘 했는지도 몰랐어! ``` @@ -202,7 +202,7 @@ end 수평선(`
`)은 셋 이상의 별표나 하이픈을 이용해 쉽게 나타낼 수 있습니다. 띄어쓰기가 포함될 수 있습니다. -```markdown +```md *** --- - - - @@ -213,19 +213,19 @@ end 마크다운의 장점 중 하나는 링크를 만들기 쉽다는 것입니다. 대괄호 안에 나타낼 텍스트를 쓰고 괄호 안에 URL을 쓰면 됩니다. -```markdown +```md [클릭](http://test.com/) ``` 괄호 안에 따옴표를 이용해 링크에 제목을 달 수도 있습니다. -```markdown +```md [클릭](http://test.com/ "test.com으로 가기") ``` 상대 경로도 유효합니다. -```markdown +```md [music으로 가기](/music/). ``` @@ -251,7 +251,7 @@ end ## 이미지 이미지는 링크와 같지만 앞에 느낌표가 붙습니다. -```markdown +```md ![이미지의 alt 속성](http://imgur.com/myimage.jpg "제목") ``` @@ -264,18 +264,18 @@ end ## 기타 ### 자동 링크 -```markdown +```md 와 [http://testwebsite.com/](http://testwebsite.com/)는 동일합니다. ``` ### 이메일 자동 링크 -```markdown +```md ``` ### 탈출 문자 -```markdown +```md *별표 사이에 이 텍스트*를 치고 싶지만 기울이고 싶지는 않다면 이렇게 하시면 됩니다. \*별표 사이에 이 텍스트\*. ``` @@ -284,7 +284,7 @@ end 깃헙 전용 마크다운에서는 `` 태그를 이용해 키보드 키를 나타낼 수 있습니다. -```markdown +```md 컴퓨터가 멈췄다면 눌러보세요. Ctrl+Alt+Del ``` @@ -292,14 +292,14 @@ end ### 표 표는 깃헙 전용 마크다운에서만 쓸 수 있고 다소 복잡하지만, 정말 쓰고 싶으시다면 -```markdown +```md | 1열 | 2열 | 3열 | | :--------| :-------: | --------: | | 왼쪽 정렬 | 가운데 정렬 | 오른쪽 정렬 | | 머시기 | 머시기 | 머시기 | ``` 혹은 -```markdown +```md 1열 | 2열 | 3열 :-- | :-: | --: 으악 너무 못생겼어 | 그만 | 둬 diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 0c787d7e03..81242bac8d 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -65,7 +65,7 @@ fun helloWorld(val name : String) { A template expression starts with a dollar sign ($). */ val fooTemplateString = "$fooString has ${fooString.length} characters" - println(fooTemplateString) // => My String Is Here! has 18 characters + println(fooTemplateString) // => My String Is Here! has 18 characters /* For a variable to hold null it must be explicitly specified as nullable. @@ -175,12 +175,12 @@ fun helloWorld(val name : String) { // Objects can be destructured into multiple variables. val (a, b, c) = fooCopy println("$a $b $c") // => 1 100 4 - + // destructuring in "for" loop for ((a, b, c) in listOf(fooData)) { println("$a $b $c") // => 1 100 4 } - + val mapData = mapOf("a" to 1, "b" to 2) // Map.Entry is destructurable as well for ((key, value) in mapData) { @@ -347,6 +347,8 @@ fun helloWorld(val name : String) { println(EnumExample.A) // => A println(ObjectExample.hello()) // => hello + + testOperator() } // Enum classes are similar to Java enum types. @@ -370,10 +372,81 @@ fun useObject() { val someRef: Any = ObjectExample // we use objects name just as is } + +/* The not-null assertion operator (!!) converts any value to a non-null type and +throws an exception if the value is null. +*/ +var b: String? = "abc" +val l = b!!.length + +/* You can add many custom operations using symbol like +, to particular instance +by overloading the built-in kotlin operator, using "operator" keyword + +below is the sample class to add some operator, and the most basic example +*/ +data class SomeClass(var savedValue: Int = 0) + +// instance += valueToAdd +operator fun SomeClass.plusAssign(valueToAdd: Int) { + this.savedValue += valueToAdd +} + +// -instance +operator fun SomeClass.unaryMinus() = SomeClass(-this.savedValue) + +// ++instance or instance++ +operator fun SomeClass.inc() = SomeClass(this.savedValue + 1) + +// instance * other +operator fun SomeClass.times(other: SomeClass) = + SomeClass(this.savedValue * other.savedValue) + +// an overload for multiply +operator fun SomeClass.times(value: Int) = SomeClass(this.savedValue * value) + +// other in instance +operator fun SomeClass.contains(other: SomeClass) = + other.savedValue == this.savedValue + +// instance[dummyIndex] = valueToSet +operator fun SomeClass.set(dummyIndex: Int, valueToSet: Int) { + this.savedValue = valueToSet + dummyIndex +} + +// instance() +operator fun SomeClass.invoke() { + println("instance invoked by invoker") +} + +/* return type must be Integer, +so that, it can be translated to "returned value" compareTo 0 + +for equality (==,!=) using operator will violates overloading equals function, +since it is already defined in Any class +*/ +operator fun SomeClass.compareTo(other: SomeClass) = + this.savedValue - other.savedValue + +fun testOperator() { + var x = SomeClass(4) + + println(x) // => "SomeClass(savedValue=4)" + x += 10 + println(x) // => "SomeClass(savedValue=14)" + println(-x) // => "SomeClass(savedValue=-14)" + println(++x) // => "SomeClass(savedValue=15)" + println(x * SomeClass(3)) // => "SomeClass(savedValue=45)" + println(x * 2) // => "SomeClass(savedValue=30)" + println(SomeClass(15) in x) // => true + x[2] = 10 + println(x) // => "SomeClass(savedValue=12)" + x() // => "instance invoked by invoker" + println(x >= 15) // => false +} ``` ### Further Reading * [Kotlin tutorials](https://kotlinlang.org/docs/tutorials/) -* [Try Kotlin in your browser](http://try.kotlinlang.org/) +* [Try Kotlin in your browser](https://play.kotlinlang.org/) * [A list of Kotlin resources](http://kotlin.link/) diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown new file mode 100644 index 0000000000..3d080de78a --- /dev/null +++ b/lambda-calculus.html.markdown @@ -0,0 +1,214 @@ +--- +category: Algorithms & Data Structures +name: Lambda Calculus +contributors: + - ["Max Sun", "http://github.com/maxsun"] + - ["Yan Hui Hang", "http://github.com/yanhh0"] +--- + +# Lambda Calculus + +Lambda calculus (λ-calculus), originally created by +[Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), +is the world's smallest programming language. +Despite not having numbers, strings, booleans, or any non-function datatype, +lambda calculus can be used to represent any Turing Machine! + +Lambda calculus is composed of 3 elements: **variables**, **functions**, and +**applications**. + + +| Name | Syntax | Example | Explanation | +|-------------|------------------------------------|-----------|-----------------------------------------------| +| Variable | `` | `x` | a variable named "x" | +| Function | `λ.` | `λx.x` | a function with parameter "x" and body "x" | +| Application | `` | `(λx.x)a` | calling the function "λx.x" with argument "a" | + +The most basic function is the identity function: `λx.x` which is equivalent to +`f(x) = x`. The first "x" is the function's argument, and the second is the +body of the function. + +## Free vs. Bound Variables: + +- In the function `λx.x`, "x" is called a bound variable because it is both in +the body of the function and a parameter. +- In `λx.y`, "y" is called a free variable because it is never declared before hand. + +## Evaluation: + +Evaluation is done via +[β-Reduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), +which is essentially lexically-scoped substitution. + +When evaluating the +expression `(λx.x)a`, we replace all occurences of "x" in the function's body +with "a". + +- `(λx.x)a` evaluates to: `a` +- `(λx.y)a` evaluates to: `y` + +You can even create higher-order functions: + +- `(λx.(λy.x))a` evaluates to: `λy.a` + +Although lambda calculus traditionally supports only single parameter +functions, we can create multi-parameter functions using a technique called +[currying](https://en.wikipedia.org/wiki/Currying). + +- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = ((x y) z)` + +Sometimes `λxy.` is used interchangeably with: `λx.λy.` + +---- + +It's important to recognize that traditional **lambda calculus doesn't have +numbers, characters, or any non-function datatype!** + +## Boolean Logic: + +There is no "True" or "False" in lambda calculus. There isn't even a 1 or 0. + +Instead: + +`T` is represented by: `λx.λy.x` + +`F` is represented by: `λx.λy.y` + +First, we can define an "if" function `λbtf` that +returns `t` if `b` is True and `f` if `b` is False + +`IF` is equivalent to: `λb.λt.λf.b t f` + +Using `IF`, we can define the basic boolean logic operators: + +`a AND b` is equivalent to: `λab.IF a b F` + +`a OR b` is equivalent to: `λab.IF a T b` + +`a NOT b` is equivalent to: `λa.IF a F T` + +*Note: `IF a b c` is essentially saying: `IF((a b) c)`* + +## Numbers: + +Although there are no numbers in lambda calculus, we can encode numbers using +[Church numerals](https://en.wikipedia.org/wiki/Church_encoding). + +For any number n: n = λf.fn so: + +`0 = λf.λx.x` + +`1 = λf.λx.f x` + +`2 = λf.λx.f(f x)` + +`3 = λf.λx.f(f(f x))` + +To increment a Church numeral, +we use the successor function `S(n) = n + 1` which is: + +`S = λn.λf.λx.f((n f) x)` + +Using successor, we can define add: + +`ADD = λab.(a S)n` + +**Challenge:** try defining your own multiplication function! + +## Get even smaller: SKI, SK and Iota + +### SKI Combinator Calculus + +Let S, K, I be the following functions: + +`I x = x` + +`K x y = x` + +`S x y z = x z (y z)` + +We can convert an expression in the lambda calculus to an expression +in the SKI combinator calculus: + +1. `λx.x = I` +2. `λx.c = Kc` +3. `λx.(y z) = S (λx.y) (λx.z)` + +Take the church number 2 for example: + +`2 = λf.λx.f(f x)` + +For the inner part `λx.f(f x)`: +``` + λx.f(f x) += S (λx.f) (λx.(f x)) (case 3) += S (K f) (S (λx.f) (λx.x)) (case 2, 3) += S (K f) (S (K f) I) (case 2, 1) +``` + +So: +``` + 2 += λf.λx.f(f x) += λf.(S (K f) (S (K f) I)) += λf.((S (K f)) (S (K f) I)) += S (λf.(S (K f))) (λf.(S (K f) I)) (case 3) +``` + +For the first argument `λf.(S (K f))`: +``` + λf.(S (K f)) += S (λf.S) (λf.(K f)) (case 3) += S (K S) (S (λf.K) (λf.f)) (case 2, 3) += S (K S) (S (K K) I) (case 2, 3) +``` + +For the second argument `λf.(S (K f) I)`: +``` + λf.(S (K f) I) += λf.((S (K f)) I) += S (λf.(S (K f))) (λf.I) (case 3) += S (S (λf.S) (λf.(K f))) (K I) (case 2, 3) += S (S (K S) (S (λf.K) (λf.f))) (K I) (case 1, 3) += S (S (K S) (S (K K) I)) (K I) (case 1, 2) +``` + +Merging them up: +``` + 2 += S (λf.(S (K f))) (λf.(S (K f) I)) += S (S (K S) (S (K K) I)) (S (S (K S) (S (K K) I)) (K I)) +``` + +Expanding this, we would end up with the same expression for the +church number 2 again. + +### SK Combinator Calculus + +The SKI combinator calculus can still be reduced further. We can +remove the I combinator by noting that `I = SKK`. We can substitute +all `I`'s with `SKK`. + +### Iota Combinator + +The SK combinator calculus is still not minimal. Defining: + +``` +ι = λf.((f S) K) +``` + +We have: + +``` +I = ιι +K = ι(ιI) = ι(ι(ιι)) +S = ι(K) = ι(ι(ι(ιι))) +``` + +## For more advanced reading: + +1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) +2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) +4. [Wikipedia - SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) +5. [Wikipedia - Iota and Jot](https://en.wikipedia.org/wiki/Iota_and_Jot) diff --git a/latex.html.markdown b/latex.html.markdown index a386689289..874efeeb36 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] - ["Svetlana Golubeva", "https://attillax.github.io/"] + - ["Oliver Kopp", "http://orcid.org/0000-0001-6962-4290"] filename: learn-latex.tex --- @@ -26,8 +27,8 @@ filename: learn-latex.tex % Next we define the packages the document uses. % If you want to include graphics, colored text, or -% source code from another language file into your document, -% you need to enhance the capabilities of LaTeX. This is done by adding packages. +% source code from another language file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. % I'm going to include the float and caption packages for figures % and hyperref package for hyperlinks \usepackage{caption} @@ -38,18 +39,18 @@ filename: learn-latex.tex \author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\ Svetlana Golubeva} \date{\today} -\title{Learn \LaTeX \hspace{1pt} in Y Minutes!} +\title{Learn \LaTeX{} in Y Minutes!} % Now we're ready to begin the document % Everything before this line is called "The Preamble" -\begin{document} -% if we set the author, date, title fields, we can have LaTeX +\begin{document} +% if we set the author, date, title fields, we can have LaTeX % create a title page for us. \maketitle % If we have sections, we can create table of contents. We have to compile our % document twice to make it appear in right order. -% It is a good practice to separate the table of contents form the body of the +% It is a good practice to separate the table of contents form the body of the % document. To do so we use \newpage command \newpage \tableofcontents @@ -58,14 +59,14 @@ Svetlana Golubeva} % Most research papers have abstract, you can use the predefined commands for this. % This should appear in its logical order, therefore, after the top matter, -% but before the main sections of the body. +% but before the main sections of the body. % This command is available in the document classes article and report. \begin{abstract} - \LaTeX \hspace{1pt} documentation written as \LaTeX! How novel and totally not + \LaTeX{} documentation written as \LaTeX! How novel and totally not my idea! \end{abstract} -% Section commands are intuitive. +% Section commands are intuitive. % All the titles of the sections are added automatically to the table of contents. \section{Introduction} Hello, my name is Colton and together we're going to explore \LaTeX! @@ -74,23 +75,28 @@ Hello, my name is Colton and together we're going to explore \LaTeX! This is the text for another section. I think it needs a subsection. \subsection{This is a subsection} % Subsections are also intuitive. -I think we need another one +I think we need another one. \subsubsection{Pythagoras} Much better now. \label{subsec:pythagoras} % By using the asterisk we can suppress LaTeX's inbuilt numbering. -% This works for other LaTeX commands as well. -\section*{This is an unnumbered section} +% This works for other LaTeX commands as well. +\section*{This is an unnumbered section} However not all sections have to be numbered! \section{Some Text notes} %\section{Spacing} % Need to add more information about space intervals -\LaTeX \hspace{1pt} is generally pretty good about placing text where it should -go. If -a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash -\hspace{1pt} to the source code. \\ +\LaTeX{} is generally pretty good about placing text where it should +go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash{} +to the source code. + +Separate paragraphs by empty lines. + +You need to add a dot after abbreviations (if not followed by a comma), because otherwise the spacing after the dot is too large: +E.g., i.e., etc.\ are are such abbreviations. \section{Lists} Lists are one of the easiest things to create in \LaTeX! I need to go shopping @@ -109,18 +115,18 @@ tomorrow, so let's make a grocery list. \section{Math} -One of the primary uses for \LaTeX \hspace{1pt} is to produce academic articles -or technical papers. Usually in the realm of math and science. As such, -we need to be able to add special symbols to our paper! \\ +One of the primary uses for \LaTeX{} is to produce academic articles +or technical papers. Usually in the realm of math and science. As such, +we need to be able to add special symbols to our paper! Math has many symbols, far beyond what you can find on a keyboard; -Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ +Set and relation symbols, arrows, operators, and Greek letters to name a few. Sets and relations play a vital role in many mathematical research papers. -Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\ -% Notice how I needed to add $ signs before and after the symbols. This is -% because when writing, we are in text-mode. -% However, the math symbols only exist in math-mode. +Here's how you state all x that belong to X, $\forall$ x $\in$ X. +% Notice how I needed to add $ signs before and after the symbols. This is +% because when writing, we are in text-mode. +% However, the math symbols only exist in math-mode. % We can enter math-mode from text mode with the $ signs. % The opposite also holds true. Variable can also be rendered in math-mode. % We can also enter math mode with \[\] @@ -128,16 +134,16 @@ Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\ \[a^2 + b^2 = c^2 \] My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. -I haven't found a Greek letter yet that \LaTeX \hspace{1pt} doesn't know -about! \\ +I haven't found a Greek letter yet that \LaTeX{} doesn't know +about! -Operators are essential parts of a mathematical document: -trigonometric functions ($\sin$, $\cos$, $\tan$), -logarithms and exponentials ($\log$, $\exp$), -limits ($\lim$), etc. -have per-defined LaTeX commands. -Let's write an equation to see how it's done: -$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\ +Operators are essential parts of a mathematical document: +trigonometric functions ($\sin$, $\cos$, $\tan$), +logarithms and exponentials ($\log$, $\exp$), +limits ($\lim$), etc.\ +have per-defined LaTeX commands. +Let's write an equation to see how it's done: +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ Fractions (Numerator-denominators) can be written in these forms: @@ -146,7 +152,7 @@ $$ ^{10}/_{7} $$ % Relatively complex fractions can be written as % \frac{numerator}{denominator} -$$ \frac{n!}{k!(n - k)!} $$ \\ +$$ \frac{n!}{k!(n - k)!} $$ We can also insert equations in an ``equation environment''. @@ -156,31 +162,31 @@ We can also insert equations in an ``equation environment''. \label{eq:pythagoras} % for referencing \end{equation} % all \begin statements must have an end statement -We can then reference our new equation! +We can then reference our new equation! Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also -the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: +the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: figures, equations, sections, etc. Summations and Integrals are written with sum and int commands: % Some LaTeX compilers will complain if there are blank lines % In an equation environment. -\begin{equation} +\begin{equation} \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} +\end{equation} +\begin{equation} \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} +\end{equation} \section{Figures} -Let's insert a Figure. Figure placement can get a little tricky. +Let's insert a figure. Figure placement can get a little tricky. I definitely have to lookup the placement options each time. -\begin{figure}[H] % H here denoted the placement option. +\begin{figure}[H] % H here denoted the placement option. \centering % centers the figure on the page % Inserts a figure scaled to 0.8 the width of the page. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} + %\includegraphics[width=0.8\linewidth]{right-triangle.png} % Commented out for compilation purposes. Please use your imagination. \caption{Right triangle with sides $a$, $b$, $c$} \label{fig:right-triangle} @@ -193,7 +199,7 @@ We can also insert Tables in the same way as figures. \caption{Caption for the Table.} % the {} arguments below describe how each row of the table is drawn. % Again, I have to look these up. Each. And. Every. Time. - \begin{tabular}{c|cc} + \begin{tabular}{c|cc} Number & Last Name & First Name \\ % Column rows are separated by & \hline % a horizontal line 1 & Biggus & Dickus \\ @@ -201,37 +207,38 @@ We can also insert Tables in the same way as figures. \end{tabular} \end{table} -\section{Getting \LaTeX \hspace{1pt} to not compile something (i.e. Source Code)} -Let's say we want to include some code into our \LaTeX \hspace{1pt} document, -we would then need \LaTeX \hspace{1pt} to not try and interpret that text and -instead just print it to the document. We do this with a verbatim -environment. +\section{Getting \LaTeX{} to not compile something (i.e.\ Source Code)} +Let's say we want to include some code into our \LaTeX{} document, +we would then need \LaTeX{} to not try and interpret that text and +instead just print it to the document. We do this with a verbatim +environment. % There are other packages that exist (i.e. minty, lstlisting, etc.) % but verbatim is the bare-bones basic one. -\begin{verbatim} +\begin{verbatim} print("Hello World!") - a%b; % look! We can use % signs in verbatim. + a%b; % look! We can use % signs in verbatim. random = 4; #decided by fair random dice roll \end{verbatim} -\section{Compiling} +\section{Compiling} + +By now you're probably wondering how to compile this fabulous document +and look at the glorious glory that is a \LaTeX{} pdf. +(yes, this document actually does compile). -By now you're probably wondering how to compile this fabulous document -and look at the glorious glory that is a \LaTeX \hspace{1pt} pdf. -(yes, this document actually does compile). \\ -Getting to the final document using \LaTeX \hspace{1pt} consists of the following +Getting to the final document using \LaTeX{} consists of the following steps: \begin{enumerate} \item Write the document in plain text (the ``source code''). - \item Compile source code to produce a pdf. + \item Compile source code to produce a pdf. The compilation step looks like this (in Linux): \\ - \begin{verbatim} + \begin{verbatim} > pdflatex learn-latex.tex \end{verbatim} \end{enumerate} -A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the +A number of \LaTeX{} editors combine both Step 1 and Step 2 in the same piece of software. So, you get to see Step 1, but not Step 2 completely. Step 2 is still happening behind the scenes\footnote{In cases, where you use references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2 @@ -245,17 +252,17 @@ format you defined in Step 1. \section{Hyperlinks} We can also insert hyperlinks in our document. To do so we need to include the package hyperref into preamble with the command: -\begin{verbatim} +\begin{verbatim} \usepackage{hyperref} \end{verbatim} There exists two main types of links: visible URL \\ -\url{https://learnxinyminutes.com/docs/latex/}, or +\url{https://learnxinyminutes.com/docs/latex/}, or \href{https://learnxinyminutes.com/docs/latex/}{shadowed by text} -% You can not add extra-spaces or special symbols into shadowing text since it +% You can not add extra-spaces or special symbols into shadowing text since it % will cause mistakes during the compilation -This package also produces list of tumbnails in the output pdf document and +This package also produces list of thumbnails in the output pdf document and active links in the table of contents. \section{End} @@ -267,9 +274,8 @@ That's all for now! \begin{thebibliography}{1} % similar to other lists, the \bibitem command can be used to list items % each entry can then be cited directly in the body of the text - \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em -https://en.wikibooks.org/wiki/LaTeX} - \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com} + \bibitem{latexwiki} The amazing \LaTeX{} wikibook: \emph{https://en.wikibooks.org/wiki/LaTeX} + \bibitem{latextutorial} An actual tutorial: \emph{http://www.latex-tutorial.com} \end{thebibliography} % end the document @@ -280,3 +286,4 @@ https://en.wikibooks.org/wiki/LaTeX} * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) * An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) +* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes) diff --git a/lua.html.markdown b/lua.html.markdown index 1e2d4366be..32174a8107 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -62,6 +62,11 @@ if not aBoolValue then print('twas false') end -- in C/js: ans = aBoolValue and 'yes' or 'no' --> 'no' +-- BEWARE: this only acts as a ternary if the value returned when the condition +-- evaluates to true is not `false` or Nil +iAmNotFalse = (not aBoolValue) and false or true --> true +iAmAlsoNotFalse = (not aBoolValue) and true or false --> true + karlSum = 0 for i = 1, 100 do -- The range includes both ends. karlSum = karlSum + i diff --git a/make.html.markdown b/make.html.markdown index ab128475a1..45d020e925 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] filename: Makefile --- @@ -11,7 +12,7 @@ target to the most recent version of the source. Famously written over a weekend by Stuart Feldman in 1976, it is still widely used (particularly on Unix and Linux) despite many competitors and criticisms. -There are many varieties of make in existence, however this article +There are many varieties of make in existence, however this article assumes that we are using GNU make which is the standard on Linux. ```make @@ -168,9 +169,9 @@ echo: name2 = Sara # True within the matching rule # Some variables defined automatically by make. echo_inbuilt: echo $(CC) - echo ${CXX)} + echo ${CXX} echo $(FC) - echo ${CFLAGS)} + echo ${CFLAGS} echo $(CPPFLAGS) echo ${CXXFLAGS} echo $(LDFLAGS) diff --git a/markdown.html.markdown b/markdown.html.markdown index a1f5173b35..cf4286e298 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -29,7 +29,7 @@ specific to a certain parser. ## HTML Elements Markdown is a superset of HTML, so any HTML file is valid Markdown. -```markdown +```md You can create HTML elements `

` through `

` easily by prepending the text you want to be in that element by a number of hashes (#). -```markdown +```md # This is an

## This is an

### This is an

@@ -51,7 +51,7 @@ text you want to be in that element by a number of hashes (#). ``` Markdown also provides us with two alternative ways of indicating h1 and h2. -```markdown +```md This is an h1 ============= @@ -63,7 +63,7 @@ This is an h2 Text can be easily styled as italic or bold using markdown. -```markdown +```md *This text is in italics.* _And so is this text._ @@ -78,7 +78,7 @@ __And so is this text.__ In GitHub Flavored Markdown, which is used to render markdown files on GitHub, we also have strikethrough: -```markdown +```md ~~This text is rendered with strikethrough.~~ ``` ## Paragraphs @@ -86,7 +86,7 @@ GitHub, we also have strikethrough: Paragraphs are a one or multiple adjacent lines of text separated by one or multiple blank lines. -```markdown +```md This is a paragraph. I'm typing in a paragraph isn't this fun? Now I'm in paragraph 2. @@ -99,7 +99,7 @@ I'm in paragraph three! Should you ever want to insert an HTML `
` tag, you can end a paragraph with two or more spaces and then begin a new paragraph. -```markdown +```md I end with two spaces (highlight me to see them). There's a
above me! @@ -107,7 +107,7 @@ There's a
above me! Block quotes are easy and done with the > character. -```markdown +```md > This is a block quote. You can either > manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. > It doesn't make a difference so long as they start with a `>`. @@ -121,7 +121,7 @@ Block quotes are easy and done with the > character. ## Lists Unordered lists can be made using asterisks, pluses, or hyphens. -```markdown +```md * Item * Item * Another item @@ -141,7 +141,7 @@ or Ordered lists are done with a number followed by a period. -```markdown +```md 1. Item one 2. Item two 3. Item three @@ -150,7 +150,7 @@ Ordered lists are done with a number followed by a period. You don't even have to label the items correctly and Markdown will still render the numbers in order, but this may not be a good idea. -```markdown +```md 1. Item one 1. Item two 1. Item three @@ -159,7 +159,7 @@ render the numbers in order, but this may not be a good idea. You can also use sublists -```markdown +```md 1. Item one 2. Item two 3. Item three @@ -170,7 +170,7 @@ You can also use sublists There are even task lists. This creates HTML checkboxes. -```markdown +```md Boxes below without the 'x' are unchecked HTML checkboxes. - [ ] First task to complete. - [ ] Second task that needs done @@ -183,7 +183,7 @@ This checkbox below will be a checked HTML checkbox. You can indicate a code block (which uses the `` element) by indenting a line with four spaces or a tab. -```markdown +```md This is code So is this ``` @@ -191,15 +191,15 @@ a line with four spaces or a tab. You can also re-tab (or add an additional four spaces) for indentation inside your code -```markdown +```md my_array.each do |item| puts item end ``` -Inline code can be created using the backtick character ` +Inline code can be created using the backtick character `` ` `` -```markdown +```md John didn't even know what the `go_to()` function did! ``` @@ -220,7 +220,7 @@ highlighting of the language you specify after the \`\`\` Horizontal rules (`
`) are easily added with three or more asterisks or hyphens, with or without spaces. -```markdown +```md *** --- - - - @@ -232,17 +232,17 @@ hyphens, with or without spaces. One of the best things about markdown is how easy it is to make links. Put the text to display in hard brackets [] followed by the url in parentheses () -```markdown +```md [Click me!](http://test.com/) ``` You can also add a link title using quotes inside the parentheses. -```markdown +```md [Click me!](http://test.com/ "Link to Test.com") ``` Relative paths work too. -```markdown +```md [Go to music](/music/). ``` @@ -269,7 +269,7 @@ But it's not that commonly used. ## Images Images are done the same way as links but with an exclamation point in front! -```markdown +```md ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") ``` @@ -281,20 +281,20 @@ And reference style works as expected. ## Miscellany ### Auto-links -```markdown +```md is equivalent to [http://testwebsite.com/](http://testwebsite.com/) ``` ### Auto-links for emails -```markdown +```md ``` ### Escaping characters -```markdown +```md I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. ``` @@ -304,7 +304,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*. In GitHub Flavored Markdown, you can use a `` tag to represent keyboard keys. -```markdown +```md Your computer crashed? Try sending a Ctrl+Alt+Del ``` @@ -313,7 +313,7 @@ Your computer crashed? Try sending a Tables are only available in GitHub Flavored Markdown and are slightly cumbersome, but if you really want it: -```markdown +```md | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Left-aligned | Centered | Right-aligned | @@ -321,7 +321,7 @@ cumbersome, but if you really want it: ``` or, for the same results -```markdown +```md Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop diff --git a/matlab.html.markdown b/matlab.html.markdown index 6dc9f697d3..5790bcc6dd 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -221,11 +221,11 @@ A(1, :) =[] % Delete the first row of the matrix A(:, 1) =[] % Delete the first column of the matrix transpose(A) % Transpose the matrix, which is the same as: -A one -ctranspose(A) % Hermitian transpose the matrix -% (the transpose, followed by taking complex conjugate of each element) -A' % Concise version of complex transpose A.' % Concise version of transpose (without taking complex conjugate) +ctranspose(A) % Hermitian transpose the matrix, which is the same as: +A' % Concise version of complex transpose + % (the transpose, followed by taking complex conjugate of each element) + @@ -374,8 +374,8 @@ disp('Hello World') % Print out a string fprintf % Print to Command Window with more control % Conditional statements (the parentheses are optional, but good style) -if (a > 15) - disp('Greater than 15') +if (a > 23) + disp('Greater than 23') elseif (a == 23) disp('a is 23') else @@ -545,7 +545,7 @@ ans = multiplyLatBy(a,3) % The method can also be called using dot notation. In this case, the object % does not need to be passed to the method. -ans = a.multiplyLatBy(a,1/3) +ans = a.multiplyLatBy(1/3) % Matlab functions can be overloaded to handle objects. % In the method above, we have overloaded how Matlab handles diff --git a/mips.html.markdown b/mips.html.markdown new file mode 100644 index 0000000000..4134d3fad0 --- /dev/null +++ b/mips.html.markdown @@ -0,0 +1,366 @@ +--- +language: "MIPS Assembly" +filename: MIPS.asm +contributors: + - ["Stanley Lim", "https://github.com/Spiderpig86"] +--- + +The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language +is designed to work with the MIPS microprocessor paradigm designed by J. L. +Hennessy in 1981. These RISC processors are used in embedded systems such as +gateways and routers. + +[Read More](https://en.wikipedia.org/wiki/MIPS_architecture) + +```asm +# Comments are denoted with a '#' + +# Everything that occurs after a '#' will be ignored by the assembler's lexer. + +# Programs typically contain a .data and .text sections + +.data # Section where data is stored in memory (allocated in RAM), similar to + # variables in higher level languages + + # Declarations follow a ( label: .type value(s) ) form of declaration + hello_world: .asciiz "Hello World\n" # Declare a null terminated string + num1: .word 42 # Integers are referred to as words + # (32 bit value) + + arr1: .word 1, 2, 3, 4, 5 # Array of words + arr2: .byte 'a', 'b' # Array of chars (1 byte each) + buffer: .space 60 # Allocates space in the RAM + # (not cleared to 0) + + # Datatype sizes + _byte: .byte 'a' # 1 byte + _halfword: .half 53 # 2 bytes + _word: .word 3 # 4 bytes + _float: .float 3.14 # 4 bytes + _double: .double 7.0 # 8 bytes + + .align 2 # Memory alignment of data, where + # number indicates byte alignment in + # powers of 2. (.align 2 represents + # word alignment since 2^2 = 4 bytes) + +.text # Section that contains instructions + # and program logic +.globl _main # Declares an instruction label as + # global, making it accessible to + # other files + + _main: # MIPS programs execute instructions + # sequentially, where the code under + # this label will be executed firsts + + # Let's print "hello world" + la $a0, hello_world # Load address of string stored in + # memory + li $v0, 4 # Load the syscall value (indicating + # type of functionality) + syscall # Perform the specified syscall with + # the given argument ($a0) + + # Registers (used to hold data during program execution) + # $t0 - $t9 # Temporary registers used for + # intermediate calculations inside + # subroutines (not saved across + # function calls) + + # $s0 - $s7 # Saved registers where values are + # saved across subroutine calls. + # Typically saved in stack + + # $a0 - $a3 # Argument registers for passing in + # arguments for subroutines + # $v0 - $v1 # Return registers for returning + # values to caller function + + # Types of load/store instructions + la $t0, label # Copy the address of a value in + # memory specified by the label into + # register $t0 + lw $t0, label # Copy a word value from memory + lw $t1, 4($s0) # Copy a word value from an address + # stored in a register with an offset + # of 4 bytes (addr + 4) + lb $t2, label # Copy a byte value to the lower order + # portion of the register $t2 + lb $t2, 0($s0) # Copy a byte value from the source + # address in $s0 with offset 0 + # Same idea with 'lh' for halfwords + + sw $t0, label # Store word value into memory address + # mapped by label + sw $t0, 8($s0) # Store word value into address + # specified in $s0 and offset of 8 bytes + # Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist + +### Math ### + _math: + # Remember to load your values into a register + lw $t0, num # From the data section + li $t0, 5 # Or from an immediate (constant) + li $t1, 6 + add $t2, $t0, $t1 # $t2 = $t0 + $t1 + sub $t2, $t0, $t1 # $t2 = $t0 - $t1 + mul $t2, $t0, $t1 # $t2 = $t0 * $t1 + div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be + # supported in some versons of MARS) + div $t0, $t1 # Performs $t0 / $t1. Get the quotient + # using 'mflo' and remainder using 'mfhi' + + # Bitwise Shifting + sll $t0, $t0, 2 # Bitwise shift to the left with + # immediate (constant value) of 2 + sllv $t0, $t1, $t2 # Shift left by a variable amount in + # register + srl $t0, $t0, 5 # Bitwise shift to the right (does + # not sign preserve, sign-extends with 0) + srlv $t0, $t1, $t2 # Shift right by a variable amount in + # a register + sra $t0, $t0, 7 # Bitwise arithmetic shift to the right + # (preserves sign) + srav $t0, $t1, $t2 # Shift right by a variable amount + # in a register + + # Bitwise operators + and $t0, $t1, $t2 # Bitwise AND + andi $t0, $t1, 0xFFF # Bitwise AND with immediate + or $t0, $t1, $t2 # Bitwise OR + ori $t0, $t1, 0xFFF # Bitwise OR with immediate + xor $t0, $t1, $t2 # Bitwise XOR + xori $t0, $t1, 0xFFF # Bitwise XOR with immediate + nor $t0, $t1, $t2 # Bitwise NOR + +## BRANCHING ## + _branching: + # The basic format of these branching instructions typically follow + #