Merge branch 'master' into patch-1
6
.github/CODEOWNERS
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
/fr-fr/ @vendethiel
|
||||
/ru-ru/ @Menelion
|
||||
/uk-ua/ @Menelion
|
||||
/zh-cn/ @geoffliu @imba-tjd
|
||||
/zh-tw/ @geoffliu @imba-tjd
|
||||
/ko-kr/ @justin-themedium
|
@ -1,5 +1,5 @@
|
||||
- [ ] I solemnly swear that this is all original content of which I am the original author
|
||||
- [ ] Pull request title is prepended with `[language/lang-code]`
|
||||
- [ ] Pull request title is prepended with `[language/lang-code]` (example `[python/fr-fr]` or `[java/en]`)
|
||||
- [ ] Pull request touches only one file (or a set of logically related files with similar changes made)
|
||||
- [ ] Content changes are aimed at *intermediate to experienced programmers* (this is a poor format for explaining fundamental programming concepts)
|
||||
- [ ] If you've changed any part of the YAML Frontmatter, make sure it is formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown)
|
@ -362,8 +362,6 @@ sqr ;; => #<procedure (sqr x)>
|
||||
;; The CHICKEN core is very minimal, but additional features are provided by library extensions known as Eggs.
|
||||
;; You can install Eggs with 'chicken-install <eggname>' command.
|
||||
|
||||
;; 'numbers' egg provides support for full numeric tower.
|
||||
(require-extension numbers)
|
||||
;; complex numbers
|
||||
3+4i ;; => 3+2i
|
||||
;; Supports fractions without falling back to inexact flonums
|
||||
@ -375,12 +373,12 @@ sqr ;; => #<procedure (sqr x)>
|
||||
(numerator 2/3) ;; => 2
|
||||
|
||||
;; 'utf8' provides unicode support
|
||||
(require-extension utf8)
|
||||
(import utf8)
|
||||
"\u03BBx:(\u03BC\u0251.\u0251\u2192\u0251).xx" ;; => "λx:(μɑ.ɑ→ɑ).xx"
|
||||
|
||||
;; 'posix' provides file I/O and lots of other services for unix-like operating systems
|
||||
;; Some of the functions are not available in Windows system,
|
||||
;; See http://wiki.call-cc.org/man/4/Unit%20posix for more details
|
||||
;; See http://wiki.call-cc.org/man/5/Module%20(chicken%20file%20posix) for more details
|
||||
|
||||
;; Open a file to append, open "write only" and create file if it does not exist
|
||||
(define outfn (file-open "chicken-hen.txt" (+ open/append open/wronly open/creat)))
|
||||
@ -396,14 +394,14 @@ sqr ;; => #<procedure (sqr x)>
|
||||
|
||||
;; CHICKEN also supports SRFI (Scheme Requests For Implementation) extensions
|
||||
;; See 'http://srfi.schemers.org/srfi-implementers.html" to see srfi's supported by CHICKEN
|
||||
(require-extension srfi-1) ;; list library
|
||||
(import srfi-1) ;; list library
|
||||
(filter odd? '(1 2 3 4 5 6 7)) ;; => (1 3 5 7)
|
||||
(count even? '(1 2 3 4 5)) ;; => 2
|
||||
(take '(12 24 36 48 60) 3) ;; => (12 24 36)
|
||||
(drop '(12 24 36 48 60) 2) ;; => (36 48 60)
|
||||
(circular-list 'z 'q) ;; => z q z q ...
|
||||
|
||||
(require-extension srfi-13) ;; string library
|
||||
(import srfi-13) ;; string library
|
||||
(string-reverse "pan") ;; => "nap"
|
||||
(string-index "Turkey" #\k) ;; => 3
|
||||
(string-every char-upper-case? "CHICKEN") ;; => #t
|
||||
@ -448,7 +446,7 @@ sqr ;; => #<procedure (sqr x)>
|
||||
; 9. Modules
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Also See http://wiki.call-cc.org/man/4/Modules
|
||||
;; Also See http://wiki.call-cc.org/man/5/Modules
|
||||
|
||||
;; The 'test' module exports a value named 'hello' and a macro named 'greet'
|
||||
(module test (hello greet)
|
||||
@ -509,11 +507,11 @@ sqr ;; => #<procedure (sqr x)>
|
||||
|
||||
```
|
||||
## Further Reading
|
||||
* [CHICKEN User's Manual](http://wiki.call-cc.org/man/4/The%20User%27s%20Manual).
|
||||
* [CHICKEN User's Manual](https://wiki.call-cc.org/manual).
|
||||
* [R5RS standards](http://www.schemers.org/Documents/Standards/R5RS)
|
||||
|
||||
|
||||
## Extra Info
|
||||
|
||||
* [For programmers of other languages](http://wiki.call-cc.org/chicken-for-programmers-of-other-languages)
|
||||
* [For programmers of other languages](https://wiki.call-cc.org/chicken-for-programmers-of-other-languages)
|
||||
* [Compare CHICKEN syntax with other languages](http://plr.sourceforge.net/cgi-bin/plr/launch.py)
|
||||
|
@ -16,7 +16,7 @@ review them more effectively and/or individually.
|
||||
|
||||
## Style Guidelines
|
||||
|
||||
- **Keep lines of under 80 chars**
|
||||
- **Keep lines under 80 chars**
|
||||
+ Try to keep **line length in code blocks to 80 characters or fewer**.
|
||||
+ Otherwise, the text will overflow and look odd.
|
||||
- **Prefer example to exposition**
|
||||
@ -78,7 +78,7 @@ lang: ep-ep
|
||||
|
||||
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
|
||||
use your judgment when deciding if your contribution constitutes a substantial
|
||||
addition or not.
|
||||
|
||||
## Building the site locally
|
||||
|
@ -17,6 +17,7 @@ contributors:
|
||||
- ["John Detter", "https://github.com/jdetter"]
|
||||
- ["Harry Mumford-Turner", "https://github.com/harrymt"]
|
||||
- ["Martin Nicholson", "https://github.com/mn113"]
|
||||
- ["Mark Grimwood", "https://github.com/MarkGrimwood"]
|
||||
filename: LearnBash.sh
|
||||
translators:
|
||||
- ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
|
||||
@ -27,12 +28,12 @@ for the GNU operating system and as the default shell on most Linux distros.
|
||||
Nearly all examples below can be a part of a shell script
|
||||
or executed directly in the shell.
|
||||
|
||||
[Read more here.](http://www.gnu.org/software/bash/manual/bashref.html)
|
||||
[Read more here.](https://www.gnu.org/software/bash/manual/bashref.html)
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
# First line of the script is the shebang which tells the system how to execute
|
||||
# the script: http://en.wikipedia.org/wiki/Shebang_(Unix)
|
||||
# the script: https://en.wikipedia.org/wiki/Shebang_(Unix)
|
||||
# As you already figured, comments start with #. Shebang is also a comment.
|
||||
|
||||
# Simple hello world example:
|
||||
@ -178,6 +179,19 @@ echo "Always executed" && echo "Only executed if first command does NOT fail"
|
||||
# => Always executed
|
||||
# => Only executed if first command does NOT fail
|
||||
|
||||
# A single ampersand & after a command runs it in the background. A background command's
|
||||
# output is printed to the terminal, but it cannot read from the input.
|
||||
sleep 30 &
|
||||
# List background jobs
|
||||
jobs # => [1]+ Running sleep 30 &
|
||||
# Bring the background job to the foreground
|
||||
fg
|
||||
# Ctrl-C to kill the process, or Ctrl-Z to pause it
|
||||
# Resume a background process after it has been paused with Ctrl-Z
|
||||
bg
|
||||
# Kill job number 2
|
||||
kill %2
|
||||
# %1, %2, etc. can be used for fg and bg as well
|
||||
|
||||
# To use && and || with if statements, you need multiple pairs of square brackets:
|
||||
if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
|
||||
@ -198,7 +212,7 @@ then
|
||||
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.
|
||||
# See https://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'
|
||||
@ -220,7 +234,8 @@ ls -l # Lists every file and directory on a separate line
|
||||
ls -t # Sorts the directory contents by last-modified date (descending)
|
||||
ls -R # Recursively `ls` this directory and all of its subdirectories
|
||||
|
||||
# Results of the previous command can be passed to the next command as input.
|
||||
# Results (stdout) of the previous command can be passed as input (stdin) to the next command
|
||||
# using a pipe |. Commands chained in this way are called a "pipeline", and are run concurrently.
|
||||
# The `grep` command filters the input with provided patterns.
|
||||
# That's how we can list .txt files in the current directory:
|
||||
ls -l | grep "\.txt"
|
||||
@ -260,7 +275,7 @@ 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 ~/Documents/.. # now in home directory (if ~/Documents exists)
|
||||
cd - # change to last directory
|
||||
# => /home/username/Documents
|
||||
|
||||
@ -275,9 +290,13 @@ mkdir -p myNewDir/with/intermediate/directories
|
||||
# if the intermediate directories didn't already exist, running the above
|
||||
# command without the `-p` flag would return an error
|
||||
|
||||
# You can redirect command input and output (stdin, stdout, and stderr).
|
||||
# You can redirect command input and output (stdin, stdout, and stderr)
|
||||
# using "redirection operators". Unlike a pipe, which passes output to a command,
|
||||
# a redirection operator has a command's input come from a file or stream, or
|
||||
# sends its output to a file or stream.
|
||||
|
||||
# Read from stdin until ^EOF$ and overwrite hello.py with the lines
|
||||
# between "EOF":
|
||||
# between "EOF" (which are called a "here document"):
|
||||
cat > hello.py << EOF
|
||||
#!/usr/bin/env python
|
||||
from __future__ import print_function
|
||||
@ -299,6 +318,8 @@ python hello.py 2> "error.err" # redirect error output to error.err
|
||||
|
||||
python hello.py > "output-and-error.log" 2>&1
|
||||
# redirect both output and errors to output-and-error.log
|
||||
# &1 means file descriptor 1 (stdout), so 2>&1 redirects stderr (2) to the current
|
||||
# destination of stdout (1), which has been redirected to output-and-error.log.
|
||||
|
||||
python hello.py > /dev/null 2>&1
|
||||
# redirect all output and errors to the black hole, /dev/null, i.e., no output
|
||||
@ -325,6 +346,9 @@ echo "#helloworld" | tee output.out >/dev/null
|
||||
# WARNING: `rm` commands cannot be undone
|
||||
rm -v output.out error.err output-and-error.log
|
||||
rm -r tempDir/ # recursively delete
|
||||
# You can install the `trash-cli` Python package to have `trash`
|
||||
# which puts files in the system trash and doesn't delete them directly
|
||||
# see https://pypi.org/project/trash-cli/ if you want to be careful
|
||||
|
||||
# Commands can be substituted within other commands using $( ):
|
||||
# The following command displays the number of files and directories in the
|
||||
@ -332,15 +356,15 @@ rm -r tempDir/ # recursively delete
|
||||
echo "There are $(ls | wc -l) items here."
|
||||
|
||||
# The same can be done using backticks `` but they can't be nested -
|
||||
#the preferred way is to use $( ).
|
||||
# the preferred way is to use $( ).
|
||||
echo "There are `ls | wc -l` items here."
|
||||
|
||||
# Bash uses a `case` statement that works similarly to switch in Java and C++:
|
||||
case "$Variable" in
|
||||
#List patterns for the conditions you want to meet
|
||||
# List patterns for the conditions you want to meet
|
||||
0) echo "There is a zero.";;
|
||||
1) echo "There is a one.";;
|
||||
*) echo "It is not null.";;
|
||||
*) echo "It is not null.";; # match everything
|
||||
esac
|
||||
|
||||
# `for` loops iterate for as many arguments given:
|
||||
@ -377,6 +401,13 @@ do
|
||||
cat "$Output"
|
||||
done
|
||||
|
||||
# Bash can also accept patterns, like this to `cat`
|
||||
# all the Markdown files in current directory
|
||||
for Output in ./*.markdown
|
||||
do
|
||||
cat "$Output"
|
||||
done
|
||||
|
||||
# while loop:
|
||||
while [ true ]
|
||||
do
|
||||
@ -392,13 +423,17 @@ function foo ()
|
||||
echo "Arguments work just like script arguments: $@"
|
||||
echo "And: $1 $2..."
|
||||
echo "This is a function"
|
||||
return 0
|
||||
returnValue=0 # Variable values can be returned
|
||||
return $returnValue
|
||||
}
|
||||
# Call the function `foo` with two arguments, arg1 and arg2:
|
||||
foo arg1 arg2
|
||||
# => Arguments work just like script arguments: arg1 arg2
|
||||
# => And: arg1 arg2...
|
||||
# => This is a function
|
||||
# Return values can be obtained with $?
|
||||
resultValue=$?
|
||||
# More than 9 arguments are also possible by using braces, e.g. ${10}, ${11}, ...
|
||||
|
||||
# or simply
|
||||
bar ()
|
||||
@ -419,7 +454,7 @@ tail -n 10 file.txt
|
||||
# prints first 10 lines of file.txt
|
||||
head -n 10 file.txt
|
||||
|
||||
# sort file.txt's lines
|
||||
# print file.txt's lines in sorted order
|
||||
sort file.txt
|
||||
|
||||
# report or omit repeated lines, with -d it reports them
|
||||
@ -431,6 +466,8 @@ cut -d ',' -f 1 file.txt
|
||||
# replaces every occurrence of 'okay' with 'great' in file.txt
|
||||
# (regex compatible)
|
||||
sed -i 's/okay/great/g' file.txt
|
||||
# be aware that this -i flag means that file.txt will be changed
|
||||
# -i or --in-place erase the input file (use --in-place=.backup to keep a back-up)
|
||||
|
||||
# print to stdout all lines of file.txt which match some regex
|
||||
# The example prints lines which begin with "foo" and end in "bar"
|
||||
@ -448,7 +485,7 @@ grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files
|
||||
grep "^foo.*bar$" file.txt | grep -v "baz"
|
||||
|
||||
# if you literally want to search for the string,
|
||||
# and not the regex, use fgrep (or grep -F)
|
||||
# and not the regex, use `fgrep` (or `grep -F`)
|
||||
fgrep "foobar" file.txt
|
||||
|
||||
# The `trap` command allows you to execute a command whenever your script
|
||||
@ -457,6 +494,7 @@ fgrep "foobar" file.txt
|
||||
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM
|
||||
|
||||
# `sudo` is used to perform commands as the superuser
|
||||
# usually it will ask interactively the password of superuser
|
||||
NAME1=$(whoami)
|
||||
NAME2=$(sudo whoami)
|
||||
echo "Was $NAME1, then became more powerful $NAME2"
|
||||
|
@ -2,16 +2,16 @@
|
||||
language: c++
|
||||
filename: learncpp.cpp
|
||||
contributors:
|
||||
- ["Steven Basart", "http://github.com/xksteven"]
|
||||
- ["Steven Basart", "https://github.com/xksteven"]
|
||||
- ["Matt Kline", "https://github.com/mrkline"]
|
||||
- ["Geoff Liu", "http://geoffliu.me"]
|
||||
- ["Connor Waters", "http://github.com/connorwaters"]
|
||||
- ["Ankush Goyal", "http://github.com/ankushg07"]
|
||||
- ["Connor Waters", "https://github.com/connorwaters"]
|
||||
- ["Ankush Goyal", "https://github.com/ankushg07"]
|
||||
- ["Jatin Dhankhar", "https://github.com/jatindhankhar"]
|
||||
---
|
||||
|
||||
C++ is a systems programming language that,
|
||||
[according to its inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote),
|
||||
[according to its inventor Bjarne Stroustrup](https://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote),
|
||||
was designed to
|
||||
|
||||
- be a "better C"
|
||||
@ -37,7 +37,7 @@ one of the most widely-used programming languages.
|
||||
// Just like in C, your program's entry point is a function called
|
||||
// main with an integer return type.
|
||||
// This value serves as the program's exit status.
|
||||
// See http://en.wikipedia.org/wiki/Exit_status for more information.
|
||||
// See https://en.wikipedia.org/wiki/Exit_status for more information.
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
// Command line arguments are passed in by argc and argv in the same way
|
||||
@ -483,7 +483,7 @@ public:
|
||||
void setOwner(const std::string& dogsOwner);
|
||||
|
||||
// Override the behavior of the print function for all OwnedDogs. See
|
||||
// http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
|
||||
// https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
|
||||
// for a more general introduction if you are unfamiliar with
|
||||
// subtype polymorphism.
|
||||
// The override keyword is optional but makes sure you are actually
|
||||
@ -616,7 +616,7 @@ boxOfBox.insert(intBox);
|
||||
// template<typename T>
|
||||
// instead. The 'class' keyword and 'typename' keywords are _mostly_
|
||||
// interchangeable in this case. For the full explanation, see
|
||||
// http://en.wikipedia.org/wiki/Typename
|
||||
// https://en.wikipedia.org/wiki/Typename
|
||||
// (yes, that keyword has its own Wikipedia page).
|
||||
|
||||
// Similarly, a template function:
|
||||
@ -660,7 +660,7 @@ printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!"
|
||||
/////////////////////
|
||||
|
||||
// The standard library provides a few exception types
|
||||
// (see http://en.cppreference.com/w/cpp/error/exception)
|
||||
// (see https://en.cppreference.com/w/cpp/error/exception)
|
||||
// but any type can be thrown as an exception
|
||||
#include <exception>
|
||||
#include <stdexcept>
|
||||
@ -946,7 +946,7 @@ mymap.insert(pair<char,int>('Z',26));
|
||||
// To iterate
|
||||
map<char,int>::iterator it;
|
||||
for (it=mymap.begin(); it!=mymap.end(); ++it)
|
||||
std::cout << it->first << "->" << it->second << std::cout;
|
||||
std::cout << it->first << "->" << it->second << std::endl;
|
||||
// Output:
|
||||
// A->1
|
||||
// Z->26
|
||||
@ -1030,7 +1030,7 @@ sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) {
|
||||
return weight[lhs] < weight[rhs];
|
||||
});
|
||||
// Note we captured "weight" by reference in the above example.
|
||||
// More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
|
||||
// More on Lambdas in C++ : https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
|
||||
|
||||
///////////////////////////////
|
||||
// Range For (C++11 and above)
|
||||
@ -1106,7 +1106,8 @@ f1 = f2;
|
||||
|
||||
#include<tuple>
|
||||
|
||||
// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members,
|
||||
// Conceptually, Tuples are similar to old data structures (C-like structs)
|
||||
// but instead of having named data members,
|
||||
// its elements are accessed by their order in the tuple.
|
||||
|
||||
// We start with constructing a tuple.
|
||||
@ -1195,5 +1196,6 @@ compl 4 // Performs a bitwise not
|
||||
Further Reading:
|
||||
|
||||
* 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 for beginners or experts, covering many modern features and good practices: [LearnCpp.com](https://www.learncpp.com/)
|
||||
* A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb).
|
||||
* Additional resources may be found at [CPlusPlus](http://cplusplus.com).
|
||||
|
180
c.html.markdown
@ -46,31 +46,47 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line...
|
||||
|
||||
// Enumeration constants are also ways to declare constants.
|
||||
// All statements must end with a semicolon
|
||||
enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
|
||||
enum days {SUN, MON, TUE, WED, THU, FRI, SAT};
|
||||
// SUN gets 0, MON gets 1, TUE gets 2, etc.
|
||||
|
||||
// Enumeration values can also be specified
|
||||
enum days {SUN = 1, MON, TUE, WED = 99, THU, FRI, SAT};
|
||||
// MON gets 2 automatically, TUE gets 3, etc.
|
||||
// WED get 99, THU gets 100, FRI gets 101, etc.
|
||||
|
||||
// Import headers with #include
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
// (File names between <angle brackets> are headers from the C standard library.)
|
||||
// For your own headers, use double quotes instead of angle brackets:
|
||||
//#include "my_header.h"
|
||||
// File names between <angle brackets> tell the compiler to look in your system
|
||||
// libraries for the headers.
|
||||
// For your own headers, use double quotes instead of angle brackets, and
|
||||
// provide the path:
|
||||
#include "my_header.h" // local file
|
||||
#include "../my_lib/my_lib_header.h" //relative path
|
||||
|
||||
// Declare function signatures in advance in a .h file, or at the top of
|
||||
// your .c file.
|
||||
void function_1();
|
||||
int function_2(void);
|
||||
|
||||
// Must declare a 'function prototype' before main() when functions occur after
|
||||
// your main() function.
|
||||
// At a minimum, you must declare a 'function prototype' before its use in any function.
|
||||
// Normally, prototypes are placed at the top of a file before any function definition.
|
||||
int add_two_ints(int x1, int x2); // function prototype
|
||||
// although `int add_two_ints(int, int);` is also valid (no need to name the args),
|
||||
// it is recommended to name arguments in the prototype as well for easier inspection
|
||||
|
||||
// Your program's entry point is a function called
|
||||
// main with an integer return type.
|
||||
// Function prototypes are not necessary if the function definition comes before
|
||||
// any other function that calls that function. However, it's standard practice to
|
||||
// always add the function prototype to a header file (*.h) and then #include that
|
||||
// file at the top. This prevents any issues where a function might be called
|
||||
// before the compiler knows of its existence, while also giving the developer a
|
||||
// clean header file to share with the rest of the project.
|
||||
|
||||
// Your program's entry point is a function called "main". The return type can
|
||||
// be anything, however most operating systems expect a return type of `int` for
|
||||
// error code processing.
|
||||
int main(void) {
|
||||
// your program
|
||||
}
|
||||
@ -96,13 +112,14 @@ int main (int argc, char** argv)
|
||||
// For the sake of the tutorial, variables are declared dynamically under
|
||||
// C99-compliant standards.
|
||||
|
||||
// ints are usually 4 bytes
|
||||
// ints are usually 4 bytes (use the `sizeof` operator to check)
|
||||
int x_int = 0;
|
||||
|
||||
// shorts are usually 2 bytes
|
||||
// shorts are usually 2 bytes (use the `sizeof` operator to check)
|
||||
short x_short = 0;
|
||||
|
||||
// chars are guaranteed to be 1 byte
|
||||
// chars are defined as the smallest addressable unit for a processor.
|
||||
// This is usually 1 byte, but for some systems it can be more (ex. for TMS320 from TI it's 2 bytes).
|
||||
char x_char = 0;
|
||||
char y_char = 'y'; // Char literals are quoted with ''
|
||||
|
||||
@ -145,19 +162,25 @@ int main (int argc, char** argv)
|
||||
int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes
|
||||
// (assuming 4-byte words)
|
||||
|
||||
// You can initialize an array to 0 thusly:
|
||||
char my_array[20] = {0};
|
||||
// You can initialize an array of twenty ints that all equal 0 thusly:
|
||||
int 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:
|
||||
// All elements (if any) past the ones in the initializer are initialized to 0:
|
||||
int my_array[5] = {1, 2};
|
||||
// So my_array now has five elements, all but the first two of which are 0:
|
||||
// [1, 2, 0, 0, 0]
|
||||
// NOTE that you get away without explicitly declaring the size
|
||||
// of the array IF you initialize the array on the same line:
|
||||
int my_array[] = {0};
|
||||
// NOTE that, when not declaring the size, the size of the array is the number
|
||||
// of elements in the initializer. With "{0}", my_array is now of size one: [0]
|
||||
// To evaluate the size of the array at run-time, divide its byte size by the
|
||||
// byte size of its element type:
|
||||
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).
|
||||
// WARNING You should evaluate the size *before* you begin passing the array
|
||||
// to functions (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
|
||||
@ -224,24 +247,41 @@ int main (int argc, char** argv)
|
||||
(float)i1 / i2; // => 0.5f
|
||||
i1 / (double)i2; // => 0.5 // Same with double
|
||||
f1 / f2; // => 0.5, plus or minus epsilon
|
||||
// Floating-point numbers and calculations are not exact
|
||||
|
||||
// Floating-point numbers are defined by IEEE 754, thus cannot store perfectly
|
||||
// exact values. For instance, the following does not produce expected results
|
||||
// because 0.1 might actually be 0.099999999999 insided the computer, and 0.3
|
||||
// might be stored as 0.300000000001.
|
||||
(0.1 + 0.1 + 0.1) != 0.3; // => 1 (true)
|
||||
// and it is NOT associative due to reasons mentioned above.
|
||||
1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // => 1 (true)
|
||||
// this notation is scientific notations for numbers: 1e123 = 1*10^123
|
||||
|
||||
// Modulo is there as well
|
||||
11 % 3; // => 2
|
||||
// It is important to note that most all systems have used IEEE 754 to
|
||||
// represent floating points. Even python, used for scientific computing,
|
||||
// eventually calls C which uses IEEE 754. It is mentioned this way not to
|
||||
// indicate that this is a poor implementation, but instead as a warning
|
||||
// that when doing floating point comparisons, a little bit of error (epsilon)
|
||||
// needs to be considered.
|
||||
|
||||
// Modulo is there as well, but be careful if arguments are negative
|
||||
11 % 3; // => 2 as 11 = 2 + 3*x (x=3)
|
||||
(-11) % 3; // => -2, as one would expect
|
||||
11 % (-3); // => 2 and not -2, and it's quite counter intuitive
|
||||
|
||||
// Comparison operators are probably familiar, but
|
||||
// there is no Boolean type in C. We use ints instead.
|
||||
// (Or _Bool or bool in C99.)
|
||||
// (C99 introduced the _Bool type provided in stdbool.h)
|
||||
// 0 is false, anything else is true. (The comparison
|
||||
// operators always yield 0 or 1.)
|
||||
3 == 2; // => 0 (false)
|
||||
3 != 2; // => 1 (true)
|
||||
3 > 2; // => 1
|
||||
3 < 2; // => 0
|
||||
3 > 2; // => 1
|
||||
3 < 2; // => 0
|
||||
2 <= 2; // => 1
|
||||
2 >= 2; // => 1
|
||||
|
||||
// C is not Python - comparisons don't chain.
|
||||
// C is not Python - comparisons do NOT chain.
|
||||
// Warning: The line below will compile, but it means `(0 < a) < 2`.
|
||||
// This expression is always true, because (0 < a) could be either 1 or 0.
|
||||
// In this case it's 1, because (0 < 1).
|
||||
@ -349,25 +389,30 @@ int main (int argc, char** argv)
|
||||
break;
|
||||
}
|
||||
/*
|
||||
using "goto" in C
|
||||
Using "goto" in C
|
||||
*/
|
||||
typedef enum { false, true } bool;
|
||||
// for C don't have bool as data type before C99 :(
|
||||
bool disaster = false;
|
||||
int i, j;
|
||||
for(i=0;i<100;++i)
|
||||
for(j=0;j<100;++j)
|
||||
for(i=0; i<100; ++i)
|
||||
for(j=0; j<100; ++j)
|
||||
{
|
||||
if((i + j) >= 150)
|
||||
disaster = true;
|
||||
if(disaster)
|
||||
goto error;
|
||||
goto error; // exit both for loops
|
||||
}
|
||||
error :
|
||||
error: // this is a label that you can "jump" to with "goto error;"
|
||||
printf("Error occurred at i = %d & j = %d.\n", i, j);
|
||||
/*
|
||||
https://ideone.com/GuPhd6
|
||||
this will print out "Error occurred at i = 51 & j = 99."
|
||||
https://ideone.com/GuPhd6
|
||||
this will print out "Error occurred at i = 51 & j = 99."
|
||||
*/
|
||||
/*
|
||||
it is generally considered bad practice to do so, except if
|
||||
you really know what you are doing. See
|
||||
https://en.wikipedia.org/wiki/Spaghetti_code#Meaning
|
||||
*/
|
||||
|
||||
///////////////////////////////////////
|
||||
@ -378,13 +423,16 @@ int main (int argc, char** argv)
|
||||
// if you want (with some constraints).
|
||||
|
||||
int x_hex = 0x01; // You can assign vars with hex literals
|
||||
// binary is not in the standard, but allowed by some
|
||||
// compilers (x_bin = 0b0010010110)
|
||||
|
||||
// Casting between types will attempt to preserve their numeric values
|
||||
printf("%d\n", x_hex); // => Prints 1
|
||||
printf("%d\n", (short) x_hex); // => Prints 1
|
||||
printf("%d\n", (char) x_hex); // => Prints 1
|
||||
|
||||
// Types will overflow without warning
|
||||
// If you assign a value greater than a types max val, it will rollover
|
||||
// without warning.
|
||||
printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long)
|
||||
|
||||
// For determining the max value of a `char`, a `signed char` and an `unsigned char`,
|
||||
@ -530,7 +578,8 @@ the function are copies of the original arguments (except arrays). Anything you
|
||||
do to the arguments in the function do not change the value of the original
|
||||
argument where the function was called.
|
||||
|
||||
Use pointers if you need to edit the original argument values.
|
||||
Use pointers if you need to edit the original argument values (arrays are always
|
||||
passed in as pointers).
|
||||
|
||||
Example: in-place string reversal
|
||||
*/
|
||||
@ -541,9 +590,11 @@ void str_reverse(char *str_in)
|
||||
char tmp;
|
||||
size_t ii = 0;
|
||||
size_t len = strlen(str_in); // `strlen()` is part of the c standard library
|
||||
// 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
|
||||
// NOTE: length returned by `strlen` DOESN'T
|
||||
// include the terminating NULL byte ('\0')
|
||||
// in C99 and newer versions, you can directly declare loop control variables
|
||||
// in the loop's parentheses. e.g., `for (size_t ii = 0; ...`
|
||||
for (ii = 0; ii < len / 2; ii++) {
|
||||
tmp = str_in[ii];
|
||||
str_in[ii] = str_in[len - ii - 1]; // ii-th char from end
|
||||
str_in[len - ii - 1] = tmp;
|
||||
@ -575,6 +626,24 @@ printf("first: %d\nsecond: %d\n", first, second);
|
||||
// values will be swapped
|
||||
*/
|
||||
|
||||
// Return multiple values.
|
||||
// C does not allow for returning multiple values with the return statement. If
|
||||
// you would like to return multiple values, then the caller must pass in the
|
||||
// variables where they would like the returned values to go. These variables must
|
||||
// be passed in as pointers such that the function can modify them.
|
||||
int return_multiple( int *array_of_3, int *ret1, int *ret2, int *ret3)
|
||||
{
|
||||
if(array_of_3 == NULL)
|
||||
return 0; //return error code (false)
|
||||
|
||||
//de-reference the pointer so we modify its value
|
||||
*ret1 = array_of_3[0];
|
||||
*ret2 = array_of_3[1];
|
||||
*ret3 = array_of_3[2];
|
||||
|
||||
return 1; //return error code (true)
|
||||
}
|
||||
|
||||
/*
|
||||
With regards to arrays, they will always be passed to functions
|
||||
as pointers. Even if you statically allocate an array like `arr[10]`,
|
||||
@ -640,7 +709,7 @@ struct rectangle {
|
||||
|
||||
void function_1()
|
||||
{
|
||||
struct rectangle my_rec;
|
||||
struct rectangle my_rec = { 1, 2 }; // Fields can be initialized immediately
|
||||
|
||||
// Access struct members with .
|
||||
my_rec.width = 10;
|
||||
@ -664,6 +733,16 @@ int area(rect r)
|
||||
return r.width * r.height;
|
||||
}
|
||||
|
||||
// Typedefs can also be defined right during struct definition
|
||||
typedef struct {
|
||||
int width;
|
||||
int height;
|
||||
} rect;
|
||||
// Like before, doing this means one can type
|
||||
rect r;
|
||||
// instead of having to type
|
||||
struct rectangle r;
|
||||
|
||||
// if you have large structs, you can pass them "by pointer" to avoid copying
|
||||
// the whole struct:
|
||||
int areaptr(const rect *r)
|
||||
@ -703,6 +782,10 @@ typedef void (*my_fnp_type)(char *);
|
||||
// my_fnp_type f;
|
||||
|
||||
|
||||
/////////////////////////////
|
||||
// Printing characters with printf()
|
||||
/////////////////////////////
|
||||
|
||||
//Special characters:
|
||||
/*
|
||||
'\a'; // alert (bell) character
|
||||
@ -741,11 +824,12 @@ typedef void (*my_fnp_type)(char *);
|
||||
// Order of Evaluation
|
||||
///////////////////////////////////////
|
||||
|
||||
// From top to bottom, top has higher precedence
|
||||
//---------------------------------------------------//
|
||||
// Operators | Associativity //
|
||||
//---------------------------------------------------//
|
||||
// () [] -> . | left to right //
|
||||
// ! ~ ++ -- + = *(type)sizeof | right to left //
|
||||
// ! ~ ++ -- + = *(type) sizeof | right to left //
|
||||
// * / % | left to right //
|
||||
// + - | left to right //
|
||||
// << >> | left to right //
|
||||
@ -783,8 +867,8 @@ as the C file.
|
||||
/* included into files that include this header. */
|
||||
#include <string.h>
|
||||
|
||||
/* Like c source files macros can be defined in headers and used in files */
|
||||
/* that include this header file. */
|
||||
/* Like for c source files, macros can be defined in headers */
|
||||
/* and used in files that include this header file. */
|
||||
#define EXAMPLE_NAME "Dennis Ritchie"
|
||||
|
||||
/* Function macros can also be defined. */
|
||||
@ -811,7 +895,7 @@ enum traffic_light_state {GREEN, YELLOW, RED};
|
||||
Node createLinkedList(int *vals, int len);
|
||||
|
||||
/* Beyond the above elements, other definitions should be left to a C source */
|
||||
/* file. Excessive includes or definitions should, also not be contained in */
|
||||
/* file. Excessive includes or definitions should also not be contained in */
|
||||
/* a header file but instead put into separate headers or a C file. */
|
||||
|
||||
#endif /* End of the if precompiler directive. */
|
||||
@ -823,7 +907,7 @@ Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://
|
||||
It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some
|
||||
inaccuracies (well, ideas that are not considered good anymore) or now-changed practices.
|
||||
|
||||
Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/).
|
||||
Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/) (not free).
|
||||
|
||||
If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com).
|
||||
|
||||
@ -833,4 +917,4 @@ Readable code is better than clever code and fast code. For a good, sane coding
|
||||
|
||||
Other than that, Google is your friend.
|
||||
|
||||
[1] [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)
|
||||
[1] [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)
|
||||
|
@ -1171,7 +1171,7 @@ You will need to `source util/setchplenv.EXT` from within the Chapel directory
|
||||
(`$CHPL_HOME`) every time your terminal starts so it's suggested that you drop
|
||||
that command in a script that will get executed on startup (like .bashrc).
|
||||
|
||||
Chapel is easily installed with Brew for OS X
|
||||
Chapel is easily installed with Brew for macOS
|
||||
|
||||
1. `brew update`
|
||||
2. `brew install chapel`
|
||||
|
@ -298,8 +298,8 @@ keymap ; => {:a 1, :b 2, :c 3}
|
||||
(as-> [1 2 3] input
|
||||
(map inc input);=> You can use last transform's output at the last position
|
||||
(nth input 2) ;=> and at the second position, in the same expression
|
||||
(conj [4 5 6] input [8 9 10])) ;=> or in the middle !
|
||||
|
||||
(conj [4 5 6] input 8 9 10)) ;=> or in the middle !
|
||||
; Result: [4 5 6 4 8 9 10]
|
||||
|
||||
|
||||
; Modules
|
||||
|
@ -14,7 +14,7 @@ organizations.
|
||||
*COBOL has significant differences between legacy (COBOL-85)
|
||||
*and modern (COBOL-2002 and COBOL-2014) versions.
|
||||
*Legacy versions require columns 1-6 to be blank (they are used
|
||||
*to store the index number of the punched card..)
|
||||
*to store the index number of the punched card).
|
||||
*A '*' in column 7 means a comment.
|
||||
*In legacy COBOL, a comment can only be a full line.
|
||||
*Modern COBOL doesn't require fixed columns and uses *> for
|
||||
@ -44,7 +44,7 @@ organizations.
|
||||
|
||||
*Let's declare some variables.
|
||||
*We do this in the WORKING-STORAGE section within the DATA DIVISION.
|
||||
*Each data item (aka variable) with start with a level number,
|
||||
*Each data item (aka variable) starts with a level number,
|
||||
*then the name of the item, followed by a picture clause
|
||||
*describing the type of data that the variable will contain.
|
||||
*Almost every COBOL programmer will abbreviate PICTURE as PIC.
|
||||
@ -106,7 +106,7 @@ organizations.
|
||||
PROCEDURE DIVISION.
|
||||
FIRST-PARA.
|
||||
DISPLAY 'THIS IS IN FIRST-PARA'.
|
||||
PERFORM THIRD-PARA THRU FOURTH-PARA. *>skip second-para and perfrom 3rd & 4th
|
||||
PERFORM THIRD-PARA THRU FOURTH-PARA. *>skip second-para and perform 3rd & 4th
|
||||
*> then after performing third and fourth,
|
||||
*> return here and continue the program until STOP RUN.
|
||||
|
||||
|
@ -61,8 +61,8 @@ Locate "+".
|
||||
|
||||
(* Calling a function with insufficient number of arguments does not cause
|
||||
an error, it produces a new function. *)
|
||||
Definition make_inc x y := x + y. (* make_inc is int -> int -> int *)
|
||||
Definition inc_2 := make_inc 2. (* inc_2 is int -> int *)
|
||||
Definition make_inc x y := x + y. (* make_inc is nat -> nat -> nat *)
|
||||
Definition inc_2 := make_inc 2. (* inc_2 is nat -> nat *)
|
||||
Compute inc_2 3. (* Evaluates to 5 *)
|
||||
|
||||
|
||||
@ -370,7 +370,7 @@ Close Scope string_scope.
|
||||
power series and results,...)
|
||||
• Relations : Relations (definitions and basic results)
|
||||
• Sorting : Sorted list (basic definitions and heapsort correctness)
|
||||
• Strings : 8-bits characters and strings
|
||||
• Strings : 8-bit characters and strings
|
||||
• Wellfounded : Well-founded relations (basic results)
|
||||
*)
|
||||
|
||||
@ -472,7 +472,7 @@ Proof.
|
||||
intros A B ab. destruct ab as [ a b ]. apply a.
|
||||
Qed.
|
||||
|
||||
(* We can prove easily prove simple polynomial equalities using the
|
||||
(* We can easily prove simple polynomial equalities using the
|
||||
automated tactic ring. *)
|
||||
|
||||
Require Import Ring.
|
||||
|
@ -4,6 +4,7 @@ filename: learncrystal.cr
|
||||
contributors:
|
||||
- ["Vitalii Elenhaupt", "http://veelenga.com"]
|
||||
- ["Arnaud Fernandés", "https://github.com/TechMagister/"]
|
||||
- ["Valentin Baca", "https://github.com/valbaca/"]
|
||||
|
||||
---
|
||||
|
||||
@ -64,24 +65,25 @@ true.class #=> Bool
|
||||
1.5e10.class #=> Float64
|
||||
1.5e-7.class #=> Float64
|
||||
|
||||
# Chars
|
||||
# Chars use 'a' pair of single quotes
|
||||
|
||||
'a'.class #=> Char
|
||||
|
||||
# Octal codepoint
|
||||
'\101' #=> 'A' : Char
|
||||
# Chars are 32-bit unicode
|
||||
'あ' #=> 'あ' : Char
|
||||
|
||||
# Unicode codepoint
|
||||
'\u0041' #=> 'A' : Char
|
||||
|
||||
# Strings
|
||||
# Strings use a "pair" of double quotes
|
||||
|
||||
"s".class #=> String
|
||||
|
||||
# Strings are immutable
|
||||
s = "hello, " #=> "hello, " : String
|
||||
s.object_id #=> 134667712 : UInt64
|
||||
s += "Crystal" #=> "hello, Crystal" : String
|
||||
s += "Crystal"
|
||||
s #=> "hello, Crystal" : String
|
||||
s.object_id #=> 142528472 : UInt64
|
||||
|
||||
# Supports interpolation
|
||||
@ -89,7 +91,8 @@ s.object_id #=> 142528472 : UInt64
|
||||
|
||||
# Multiline string
|
||||
"This is
|
||||
multiline string"
|
||||
multiline string" #=> "This is\n multiline string"
|
||||
|
||||
|
||||
# String with double quotes
|
||||
%(hello "world") #=> "hello \"world\""
|
||||
@ -110,7 +113,7 @@ sentence == "question?" #=> false : Bool
|
||||
# Arrays
|
||||
|
||||
[1, 2, 3].class #=> Array(Int32)
|
||||
[1, "hello", 'x'].class #=> Array(Int32 | String | Char)
|
||||
[1, "hello", 'x'].class #=> Array(Char | Int32 | String)
|
||||
|
||||
# Empty arrays should specify a type
|
||||
[] # Syntax error: for empty arrays use '[] of ElementType'
|
||||
@ -154,24 +157,24 @@ array.includes? 3 #=> true
|
||||
|
||||
# There is a special array syntax with other types too, as long as
|
||||
# they define a .new and a #<< method
|
||||
set = Set{1, 2, 3} #=> [1, 2, 3]
|
||||
set = Set{1, 2, 3} #=> Set{1, 2, 3}
|
||||
set.class #=> Set(Int32)
|
||||
|
||||
# The above is equivalent to
|
||||
set = Set(typeof(1, 2, 3)).new
|
||||
set << 1
|
||||
set << 2
|
||||
set << 3
|
||||
set = Set(typeof(1, 2, 3)).new #=> Set{} : Set(Int32)
|
||||
set << 1 #=> Set{1} : Set(Int32)
|
||||
set << 2 #=> Set{1, 2} : Set(Int32)
|
||||
set << 3 #=> Set{1, 2, 3} : Set(Int32)
|
||||
|
||||
# Hashes
|
||||
|
||||
{1 => 2, 3 => 4}.class #=> Hash(Int32, Int32)
|
||||
{1 => 2, 'a' => 3}.class #=> Hash(Int32 | Char, Int32)
|
||||
{1 => 2, 'a' => 3}.class #=> Hash(Char| Int32, Int32)
|
||||
|
||||
# Empty hashes should specify a type
|
||||
{} # Syntax error
|
||||
{} of Int32 => Int32 # {}
|
||||
Hash(Int32, Int32).new # {}
|
||||
# Empty hashes must specify a type
|
||||
{} # Syntax Error: for empty hashes use '{} of KeyType => ValueType'
|
||||
{} of Int32 => Int32 # {} : Hash(Int32, Int32)
|
||||
Hash(Int32, Int32).new # {} : Hash(Int32, Int32)
|
||||
|
||||
# Hashes can be quickly looked up by key
|
||||
hash = {"color" => "green", "number" => 5}
|
||||
@ -179,6 +182,9 @@ hash["color"] #=> "green"
|
||||
hash["no_such_key"] #=> Missing hash key: "no_such_key" (KeyError)
|
||||
hash["no_such_key"]? #=> nil
|
||||
|
||||
# The type of the returned value is based on all key types
|
||||
hash["number"] #=> 5 : (Int32 | String)
|
||||
|
||||
# Check existence of keys hash
|
||||
hash.has_key? "color" #=> true
|
||||
|
||||
@ -220,7 +226,7 @@ Range.new(1, 10).class #=> Range(Int32, Int32)
|
||||
# Access tuple's value by its index
|
||||
tuple = {:key1, :key2}
|
||||
tuple[1] #=> :key2
|
||||
tuple[2] #=> syntax error : Index out of bound
|
||||
tuple[2] #=> Error: index out of bounds for Tuple(Symbol, Symbol) (2 not in -2..1)
|
||||
|
||||
# Can be expanded into multiple variables
|
||||
a, b, c = {:a, 'b', "c"}
|
||||
@ -246,7 +252,7 @@ elsif false
|
||||
"else-if, optional"
|
||||
else
|
||||
"else, also optional"
|
||||
end
|
||||
end
|
||||
|
||||
puts "if as a suffix" if true
|
||||
|
||||
@ -314,7 +320,7 @@ if a < 3
|
||||
else
|
||||
a = true
|
||||
end
|
||||
typeof a #=> (Bool | String)
|
||||
typeof(a) #=> (Bool | String)
|
||||
|
||||
if a && b
|
||||
# here both a and b are guaranteed not to be Nil
|
||||
@ -388,15 +394,19 @@ dinner #=> "quesadilla"
|
||||
5.even? # false
|
||||
5.odd? # true
|
||||
|
||||
# And if a method ends with an exclamation mark, it does something destructive
|
||||
# like mutate the receiver. Some methods have a ! version to make a change, and
|
||||
# Also by convention, if a method ends with an exclamation mark, it does
|
||||
# something destructive like mutate the receiver.
|
||||
# Some methods have a ! version to make a change, and
|
||||
# a non-! version to just return a new changed version
|
||||
company_name = "Dunder Mifflin"
|
||||
company_name.gsub "Dunder", "Donald" #=> "Donald Mifflin"
|
||||
company_name #=> "Dunder Mifflin"
|
||||
company_name.gsub! "Dunder", "Donald"
|
||||
company_name #=> "Donald Mifflin"
|
||||
fruits = ["grapes", "apples", "bananas"]
|
||||
fruits.sort #=> ["apples", "bananas", "grapes"]
|
||||
fruits #=> ["grapes", "apples", "bananas"]
|
||||
fruits.sort! #=> ["apples", "bananas", "grapes"]
|
||||
fruits #=> ["apples", "bananas", "grapes"]
|
||||
|
||||
# However, some mutating methods do not end in !
|
||||
fruits.shift #=> "apples"
|
||||
fruits #=> ["bananas", "grapes"]
|
||||
|
||||
# Define a class with the class keyword
|
||||
class Human
|
||||
@ -404,7 +414,7 @@ class Human
|
||||
# A class variable. It is shared by all instances of this class.
|
||||
@@species = "H. sapiens"
|
||||
|
||||
# type of name is String
|
||||
# An instance variable. Type of name is String
|
||||
@name : String
|
||||
|
||||
# Basic initializer
|
||||
@ -469,9 +479,9 @@ class TestClass
|
||||
end
|
||||
# Variables that start with a capital letter are constants
|
||||
Var = "I'm a constant"
|
||||
Var = "can't be updated" # Already initialized constant Var
|
||||
Var = "can't be updated" # Error: already initialized constant Var
|
||||
|
||||
# Class is also an object in crystal. So class can have instance variables.
|
||||
# Class is also an object in Crystal. So a class can have instance variables.
|
||||
# Class variable is shared among the class and all of its descendants.
|
||||
|
||||
# base class
|
||||
|
@ -5,44 +5,87 @@ contributors:
|
||||
- ["Dan Turkel", "http://danturkel.com/"]
|
||||
translators:
|
||||
- ["Michal Martinek", "https://github.com/MichalMartinek"]
|
||||
- ["Tomáš Hartman", "https://github.com/tomas-hartman"]
|
||||
filename: markdown-cz.md
|
||||
lang: cs-cz
|
||||
---
|
||||
|
||||
Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná
|
||||
a psatelná syntaxe, která je jednoduše převeditelná do HTML (a dnes i do mnoha
|
||||
dalších formátů)
|
||||
Markdown byl vytvořen Johnem Gruberem v roce 2004 jako značkovací jazyk, který
|
||||
lze snadno číst a psát a který je možné jednoduše převést do HTML (a dnes i do
|
||||
mnoha dalších formátů).
|
||||
|
||||
Implementace markdownu se v různých parserech (syntaktických analyzátorech,
|
||||
které markdown dále zpracovávají) mírně odlišuje. V této příručce se snažíme
|
||||
upozorňovat, kdy se jedná o obecnou vlastnost markdownu a kdy se jedná o
|
||||
specifickou vlastnost daného parseru.
|
||||
|
||||
## Obsah
|
||||
|
||||
- [Obsah](#obsah)
|
||||
- [HTML Elementy](#html-elementy)
|
||||
- [Nadpisy](#nadpisy)
|
||||
- [Jednoduché stylování textu](#jednoduché-stylování-textu)
|
||||
- [Odstavce](#odstavce)
|
||||
- [Blokové citace](#blokové-citace)
|
||||
- [Seznamy](#seznamy)
|
||||
- [Bloky kódu](#bloky-kódu)
|
||||
- [Vodorovná čára (`<hr />`)](#vodorovná-čára-hr-)
|
||||
- [Odkazy](#odkazy)
|
||||
- [Obsahy](#obsahy)
|
||||
- [Obrázky](#obrázky)
|
||||
- [Ostatní](#ostatní)
|
||||
- [Automatické odkazy](#automatické-odkazy)
|
||||
- [Automatické odkazy z emailů](#automatické-odkazy-z-emailů)
|
||||
- [Escapování znaků](#escapování-znaků)
|
||||
- [Klávesové zkratky](#klávesové-zkratky)
|
||||
- [Tabulky](#tabulky)
|
||||
- [Markdownlint](#markdownlint)
|
||||
- [Reference](#reference)
|
||||
|
||||
## HTML Elementy
|
||||
|
||||
Markdown je nadstavba HTML. To znamená, že každý HTML kód je zároveň validním
|
||||
kódem v Markdownu.
|
||||
|
||||
```md
|
||||
<!-- Markdown je nadstavba nad HTML, takže jakýkoliv kód HTML je validní
|
||||
Markdown, to znamená, že můžeme používat HTML elementy, třeba jako komentář, a
|
||||
nebudou ovlivněny parserem Markdownu. Avšak, pokud vytvoříte HTML element v
|
||||
Markdownu, tak nemůžete používat syntaxi Markdownu uvnitř tohoto elementu. -->
|
||||
<!-- To znamená, že v Markdownu můžeme používat HTML elementy jako například
|
||||
komentáře, které nebudou ovlivněny parserem Markdownu. Na druhou stranu to také
|
||||
znamená, že pokud ve svém Markdown kódu vytvoříte HTML element, už v rámci
|
||||
tohoto elementu nelze použít Markdown.
|
||||
|
||||
<!-- Markdown se také mírně liší v jednotlivých interpretacích parseru. Tento
|
||||
návod vás bude upozorňovat, které vlastnosti jsou obecné a které specifické pro
|
||||
konkrétní parser. -->
|
||||
Markdown využívá i tato stránka, a tak by tento text, kdyby nebyl obalen v bloku
|
||||
kódu (viz níže), jako validní HTML komentář vůbec nebyl vidět. -->
|
||||
```
|
||||
|
||||
<!-- Nadpisy -->
|
||||
<!-- Můžete vytvořit HTML elementy <h1> až <h6> jednoduše tak, že text předsadíte
|
||||
počtem křížků (#), podle toho jaké úrovně to má být nadpis -->
|
||||
## Nadpisy
|
||||
|
||||
HTML elementy `<h1>` až `<h6>` vytvoříte jednoduše tak, že nadpisu předsadíte
|
||||
takový počet křížků (#), jaký odpovídá úrovni nadpisu.
|
||||
|
||||
```md
|
||||
# Toto je <h1>
|
||||
## Toto je <h2>
|
||||
### Toto je <h3>
|
||||
#### Toto je <h4>
|
||||
##### Toto je <h5>
|
||||
###### Toto je <h6>
|
||||
```
|
||||
|
||||
<!-- Markdown obsahuje taky dvě další cesty, jak udělat h1 a h2 -->
|
||||
Markdown obsahuje ještě dva další způsoby, jak vytvořit h1 a h2:
|
||||
|
||||
```md
|
||||
Toto je h1
|
||||
==========
|
||||
|
||||
Toto je h2
|
||||
----------
|
||||
```
|
||||
|
||||
<!-- Jednoduché stylování textu -->
|
||||
<!-- Pomocí markdownu můžete text jednoduše označit jako kurzívu či tučný -->
|
||||
## Jednoduché stylování textu
|
||||
|
||||
Pomocí markdownu můžete text jednoduše označit jako kurzívu či tučný text.
|
||||
|
||||
```md
|
||||
*Tento text je kurzívou;*
|
||||
_Stejně jako tento._
|
||||
|
||||
@ -50,47 +93,62 @@ _Stejně jako tento._
|
||||
__Stejně jako tento.__
|
||||
|
||||
***Tento text je obojí***
|
||||
**_Jako tento!_**
|
||||
*__A tento!__*
|
||||
**_Tak jako tento!_**
|
||||
*__Nebo tento!__*
|
||||
```
|
||||
|
||||
<!-- Ve verzi Markdownu od GitHubu, máme k dispozici taky prošktrnutí: -->
|
||||
Ve verzi Markdownu od GitHubu máme k dispozici také přeškrtnutí:
|
||||
|
||||
~~Tento text je prošktrnutý.~~
|
||||
```md
|
||||
~~Tento text je přeškrtnutý.~~
|
||||
```
|
||||
|
||||
<!-- Odstavce jsou jedna nebo více řádek textu, oddělených jednou nebo více prázdnými řádky. -->
|
||||
## Odstavce
|
||||
|
||||
Toto je odstavec. Píši odstavec, není to zábava?
|
||||
Odstavce tvoří jeden nebo více řádků textu, oddělených jedním nebo více
|
||||
prázdnými řádky.
|
||||
|
||||
```md
|
||||
Toto je odstavec. Zde jsem napsal odstavec a je to bezva!
|
||||
|
||||
Teď jsem v odstavci 2.
|
||||
Jsem pořád v odstavci 2!
|
||||
A tady jsem pořád v odstavci 2!
|
||||
|
||||
Ale tady už je odstavec 3.
|
||||
```
|
||||
|
||||
Toto je odstavec 3.
|
||||
|
||||
<!-- Chtěli jste někdy vložit znak <br /> tag? Můžete napsat na konec odstavce
|
||||
dvě nebo více mezer a potom začít nový odstavec. -->
|
||||
Pokud byste chtěli vložit HTML element `<br />`, můžete na konec odstavce napsat
|
||||
dvě nebo více mezer a potom začít nový odstavec.
|
||||
|
||||
```md
|
||||
Tento odstavec končí dvěma mezerami.
|
||||
|
||||
Nad tímto odstavcem je <br />!
|
||||
Nad tímto odstavcem je <br />!
|
||||
```
|
||||
|
||||
<!-- Blokové citace se dělají jednoduše pomocí znaku >. -->
|
||||
### Blokové citace
|
||||
|
||||
Blokové citace se dělají jednoduše uvozením řádku znakem >.
|
||||
|
||||
```md
|
||||
> Toto je bloková citace. Můžete dokonce
|
||||
> manuálně rozdělit řádky, a před každý vložit >, nebo nechat vaše řádky jakkoliv dlouhé, ať se zarovnají sami.
|
||||
> Nedělá to rozdíl, dokud začínáte vždy znakem >.
|
||||
> manuálně rozdělit řádky, a před každý vložit >, nebo nechat vaše řádky
|
||||
> jakkoli dlouhé, ať se zarovnají samy.
|
||||
> Je to jedno, pokud vždy začínají symbolem `>`.
|
||||
|
||||
> Můžu použít více než jednu
|
||||
>> odsazení?
|
||||
> Jak je to úhledné, že?
|
||||
> Použít můžu i více než jednu úroveň
|
||||
>> odsazení.
|
||||
> Co vy na to?
|
||||
```
|
||||
|
||||
<!-- Seznamy -->
|
||||
<!-- Nečíslovaný seznam můžete jednoduše udělat pomocí hvězdiček, plusů, nebo
|
||||
pomlček -->
|
||||
## Seznamy
|
||||
|
||||
Nečíslovaný seznam můžete jednoduše udělat pomocí hvězdiček, plusů nebo pomlček:
|
||||
|
||||
```md
|
||||
* Položka
|
||||
* Položka
|
||||
* Jinná položka
|
||||
* Jiná položka
|
||||
|
||||
nebo
|
||||
|
||||
@ -103,158 +161,246 @@ nebo
|
||||
- Položka
|
||||
- Položka
|
||||
- Další položka
|
||||
```
|
||||
|
||||
<!-- Číslovaný seznam se dělají pomocí čísla a . -->
|
||||
Číslované seznamy se dělají pomocí číslice a `.`.
|
||||
|
||||
```md
|
||||
1. Položka jedna
|
||||
2. Položka dvě
|
||||
3. Položka tři
|
||||
|
||||
<!-- Nemusíte dokonce psát čísla správně a markdown je zobrazi správně,
|
||||
ale nemusí to být vždy dobrý nápad -->
|
||||
<!-- Čísla ani nemusíte psát popořadě. Markdown je umí zobrazit správně, jenom
|
||||
je třeba vždy překontrolovat, že číslování funguje správně. -->
|
||||
|
||||
1. Položka jedna
|
||||
1. Položka dvě
|
||||
1. Položka tři
|
||||
<!-- (Toto zobrazí to samě, jako příklad nadtím.) -->
|
||||
|
||||
<!-- Můžete také tvořit podseznamy -->
|
||||
<!-- (Toto zobrazí to samé, jako příklad nad tím.) -->
|
||||
```
|
||||
|
||||
Můžete také tvořit podseznamy:
|
||||
|
||||
```md
|
||||
1. Položka jedna
|
||||
2. Položka dvě
|
||||
3. Položka tři
|
||||
* Podpoložka
|
||||
* Podpoložka
|
||||
- Podpoložka
|
||||
- Podpoložka
|
||||
4. Položka čtyři
|
||||
```
|
||||
|
||||
<!-- Existují i zašktávací seznamy. Toto vytvoří HTML checkboxy. -->
|
||||
Vytvořit lze i zaškrtávací seznamy. Takto lze vytvořit seznam s HTML checkboxy.
|
||||
(Boxy níže bez 'x' jsou nezaškrtnuté checkboxy.)
|
||||
|
||||
Boxy níže bez 'x' jsou nezašktrnuté checkboxy.
|
||||
- [ ] První úkol
|
||||
- [ ] Druhý úkol
|
||||
Tento box bude zašktrnutý
|
||||
```md
|
||||
- [ ] První úkol, který je třeba dokončit
|
||||
- [ ] Druhý úkol na dodělání
|
||||
Tento box bude zaškrtnutý
|
||||
- [x] Tento úkol byl dokončen
|
||||
```
|
||||
|
||||
<!-- Bloky ködu -->
|
||||
<!-- Můžete označit kód bloku (který používá <code> element) odsazením pomocí 4
|
||||
mezer, nebo tabu -->
|
||||
## Bloky kódu
|
||||
|
||||
Bloky kódu můžete označit tak, že řádek odsadíte čtyřmi mezerami nebo pomocí
|
||||
tabu. Pro interpretaci kódu parser používá `<code>` element.
|
||||
|
||||
```md
|
||||
Toto je kód
|
||||
Stejně jako toto
|
||||
```
|
||||
|
||||
<!-- Můžete dokonce přidat další 4 mezery nebo tab pro další odsazení -->
|
||||
Pro ještě hlubší odsazení můžete přidat další 4 mezery nebo další tab:
|
||||
|
||||
```md
|
||||
moje_pole.each do |i|
|
||||
puts i
|
||||
end
|
||||
```
|
||||
|
||||
<!-- Kód na řádku může být označen pomocí zpětných apostrofů ` -->
|
||||
Jednořádkový kód můžete zabalit do dvou zpětných apostrofů (`) tak, jako
|
||||
kdybyste text normálně stylovali:
|
||||
|
||||
Jan nevědel, jak se dělá `go_to()` funkce!
|
||||
```md
|
||||
Honza neměl tušení, co dělá funkce `go_to()`!
|
||||
```
|
||||
|
||||
<!-- V Markdownu od GitHubu , můžete použít speciální syntaxi pro kód -->
|
||||
V Markdownu od GitHubu, můžete použít speciální syntaxi pro kód:
|
||||
|
||||
\`\`\`ruby <!-- vyjma zpětných lomítek, jenom ```ruby ! -->
|
||||
<pre><code class="highlight">```ruby
|
||||
def neco
|
||||
puts "Ahoj světe!"
|
||||
end
|
||||
\`\`\` <!-- zde taky, žádné zpětná lomítka, pouze ``` -->
|
||||
```</code></pre>
|
||||
|
||||
<!-- Text výše nepotřebuje odsazení a navíc GitHub použije zvýraznění označeného
|
||||
jazyka. -->
|
||||
Text výše nepotřebuje čtyřmezerové odsazení a parser navíc použije zvýraznění
|
||||
syntaxe pro zvolený jazyk.
|
||||
|
||||
<!-- Horizontální čára (<hr />) -->
|
||||
<!-- Horizontální čára se jednoduše přidá pomocí 3 nebo více hvězdiček nebo pomlček
|
||||
s nebo bez mezer. -->
|
||||
## Vodorovná čára (`<hr />`)
|
||||
|
||||
Vodorovnou oddělovací čáru lze snadno přidat pomocí 3 nebo více hvězdiček (nebo
|
||||
pomlček), a to buď s mezerami mezi jednotlivými znaky, nebo bez nich.
|
||||
|
||||
```md
|
||||
***
|
||||
---
|
||||
- - -
|
||||
****************
|
||||
```
|
||||
|
||||
<!-- Odkazy -->
|
||||
<!-- Jedna z nejlepších věcí na Markdownu je, jak jednoduše se dělají odkazy.
|
||||
Dejte text, který chcete zobrazit, do [] následovaný url v závorkách () a je to. -->
|
||||
## Odkazy
|
||||
|
||||
```md
|
||||
<!-- Jedna z nejlepších vlastností Markdownu je, jak snadno lze s jeho pomocí
|
||||
vytvářet odkazy. Text odkazu, který chcete zobrazit vložte do [] a hned za něj
|
||||
v kulatých závorkách () připojte url adresu. -->
|
||||
|
||||
[Klikni na mě!](http://test.com/)
|
||||
|
||||
<!-- Můžete také přidat jméno linku pomocí uvozovek -->
|
||||
|
||||
<!-- V uvozovkách za url můžete přidat název odkazu -->
|
||||
|
||||
[Klikni na mě!](http://test.com/ "Odkaz na Test.com")
|
||||
|
||||
<!-- Relativní cesty fungují taky -->
|
||||
|
||||
<!-- Relativní cesty fungují také -->
|
||||
|
||||
[Jdi na hudbu](/hudba/).
|
||||
|
||||
<!-- Markdown taktéž podporuje reference odkazů. -->
|
||||
|
||||
<!-- Markdown taktéž podporuje referenční odkazy -->
|
||||
|
||||
[Klikni na tento odkaz][link1] pro více informací!
|
||||
[Taky zkontrolujte tento odkaz][neco], když chcete.
|
||||
[Taky zkontrolujte tento odkaz][neco], jestli tedy chcete.
|
||||
|
||||
[link1]: http://test.com/ "Cool!"
|
||||
[neco]: http://neco.czz/ "Dobře!"
|
||||
|
||||
<!-- Titulek může být v apostrofech nebo závorkách, nebo vyjmutý úplně. Reference
|
||||
může být kdekoliv ve vašem dokumentu a identifikátor může být jakýkoliv, dokud
|
||||
je unikátní.-->
|
||||
<!-- Titulek v tomto případě může být v jednoduchých uvozovkách, závorkách, nebo
|
||||
zcela vynechaný. Reference může být kdekoliv ve vašem dokumentu a identifikátory
|
||||
mohou být jakékoli, pokud jsou unikátní. -->
|
||||
|
||||
<!-- Také existuje "implicitní pojmenování", které použije text jako id -->
|
||||
|
||||
<!-- V markdownu existuje rovněž "implicitní pojmenování", které použije text
|
||||
odkazu jako své id -->
|
||||
|
||||
[Toto][] je odkaz..
|
||||
|
||||
[toto]: http://totojelink.cz/
|
||||
|
||||
<!-- Ale toto není zrovna běžné užívané. -->
|
||||
<!-- Ale tento způsob se obvykle nepoužívá. -->
|
||||
```
|
||||
|
||||
<!-- Obrázky -->
|
||||
<!-- Obrázky se dělají stejně jako odkazy, ale s vykřičníkem na začátku -->
|
||||
### Obsahy
|
||||
|
||||
Kombinace seznamů, odkazů a nadpisů využívají také některé parsery pro
|
||||
generování obsahu Markdown souborů. Jako identifikátory slouží jména nadpisů
|
||||
psané malými písmeny, které jsou uvozené křížkem (`#`). Víceslovné nadpisy
|
||||
bývají propojeny pomlčkou (`-`), která někdy nahrazuje i speciální znaky. Jiné
|
||||
speciální znaky mohou být vynechány.
|
||||
|
||||
```md
|
||||
- [Nadpis](#nadpis)
|
||||
- [Víceslovný text](#víceslovný-text)
|
||||
- [Odstavce](#odstavce)
|
||||
- [Podkapitola <h3 />](#podkapitola-h3-)
|
||||
```
|
||||
|
||||
V případě obsahů se v každém případě jedná o nadstavbu, která nemusí všude
|
||||
fungovat stejně.
|
||||
|
||||
## Obrázky
|
||||
|
||||
```md
|
||||
<!-- Obrázky se vytváří stejně jako odkazy, ale s vykřičníkem na začátku -->
|
||||
|
||||
![Toto je atribut alt pro obrázek](http://imgur.com/myimage.jpg "Nepovinný titulek")
|
||||
|
||||
<!-- Reference fungují, jak bychom čekali-->
|
||||
<!-- Reference fungují tak, jak bychom čekali -->
|
||||
|
||||
![Toto je atribut alt][mujobrazek]
|
||||
|
||||
[mujobrazek]: relativni/cesta/obrazek.jpg "a toto by byl titulek"
|
||||
```
|
||||
|
||||
<!-- Ostatní -->
|
||||
<!-- Automatické odkazy -->
|
||||
## Ostatní
|
||||
|
||||
### Automatické odkazy
|
||||
|
||||
```md
|
||||
<http://stranka.cz/>
|
||||
|
||||
je stejné jako
|
||||
|
||||
<http://stranka.cz/> je stejná jako
|
||||
[http://stranka.cz/](http://stranka.cz/)
|
||||
```
|
||||
|
||||
<!-- Automatické odkazy pro emaily-->
|
||||
### Automatické odkazy z emailů
|
||||
|
||||
```md
|
||||
<jmeno@prijmeni.cz>
|
||||
```
|
||||
|
||||
<!-- Escapování znaků -->
|
||||
### Escapování znaků
|
||||
|
||||
Chci napsat *tento text obklopený hvězdičkami*, ale nechci aby to bylo kurzívou, tak udělám: \*tento text obklopený hvězdičkami\*.
|
||||
```md
|
||||
Chci napsat *tento text obklopený hvězdičkami*, ale protože nechci, aby to bylo
|
||||
kurzívou, tak hvězdičky vyescapuji `\`: \*tento text bude obklopený hvězdičkami\*.
|
||||
```
|
||||
|
||||
<!-- Klávesové zkratky -->
|
||||
<!-- V Markdownu od GitHubu, můžete použít tag <kbd> k reprezentování klaves na počítači -->
|
||||
### Klávesové zkratky
|
||||
|
||||
```md
|
||||
<!-- V Markdownu od GitHubu můžete použít tag <kbd> k označení kláves na
|
||||
počítači -->
|
||||
|
||||
Váš počítač přestal pracovat? Zkuste
|
||||
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
||||
```
|
||||
|
||||
<!-- Tabulky -->
|
||||
<!-- Tabulky jsou povolené pouze v Markdownu od GitHubu a jsou trochu podivně,
|
||||
ale když je opravdu chcete: -->
|
||||
### Tabulky
|
||||
|
||||
Tabulky lze využít pouze v Markdownu od GitHubu a jejich syntax je trošku
|
||||
zvláštní. Kdybyste je chtěli použít, vytváří se takto:
|
||||
|
||||
```md
|
||||
| Sloupec1 | Sloupec2 | Sloupec3 |
|
||||
| :----------- | :------: | ------------: |
|
||||
| Vlevo zarovn.| Na střed | Vpravo zarovn.|
|
||||
| blah | blah | blah |
|
||||
|
||||
<!-- nebo, to jde i taky: -->
|
||||
<!-- nebo je jde taky zapsat takto: -->
|
||||
|
||||
Sloupec 1 | Sloupec2 | Sloupec3
|
||||
:-- | :-: | --:
|
||||
Ohh toto je tak ošklivé | radši to | nedělejte
|
||||
|
||||
<!-- Konec -->
|
||||
|
||||
Že se to nedá číst? | No tak to takhle | radši nedělejte.
|
||||
```
|
||||
|
||||
Pro více informací, prozkoumejte oficiální článek o syntaxi od Johna Grubera
|
||||
[zde](http://daringfireball.net/projects/markdown/syntax) a skvělý tahák od Adama Pritcharda [zde](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
||||
## Markdownlint
|
||||
|
||||
Pro usnadnění práce s Markdownem a s cílem sjednotit styl psaní jeho kódu vznikl
|
||||
nástroj `Markdownlint`. Tento nástroj je dostupný i jako plugin pro některé
|
||||
editory kódu (IDE) a lze jej použít jako nástroj pro vytváření a ověřování
|
||||
validity a čitelnosti Markdownu kódu.
|
||||
|
||||
---
|
||||
|
||||
## Reference
|
||||
|
||||
Pro více informací doporučujeme oficiální článek o syntaxi od Johna Grubera
|
||||
[zde](http://daringfireball.net/projects/markdown/syntax) a skvělý tahák od
|
||||
Adama Pritcharda [zde](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
||||
|
||||
---
|
||||
|
||||
> _Pozn. překladatele:_ Tento text vznikl jako překlad původního článku, který
|
||||
> pochází z roku 2013 a kombinace původního českého překladu z roku 2015.
|
||||
> Některé informace v tomto článku, zejména ty, týkající se specifických
|
||||
> vlastností parserů markdownu tak již dnes mohou být zastaralé.
|
||||
|
||||
Aktuální informace o specifických vlastnostech různých implementací Markdownu
|
||||
můžete nalézt zde (v angličtině):
|
||||
|
||||
- [Markdown pro GitHub](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
|
||||
- [Markdown pro GitLab](https://docs.gitlab.com/ee/user/markdown.html)
|
||||
|
@ -12,9 +12,9 @@ contributors:
|
||||
filename: LearnCSharp.cs
|
||||
---
|
||||
|
||||
C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework.
|
||||
C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the cross-platform .NET framework.
|
||||
|
||||
[Read more here.](https://docs.microsoft.com/dotnet/csharp/getting-started/introduction-to-the-csharp-language-and-the-net-framework)
|
||||
[Read more here.](https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/)
|
||||
|
||||
```c#
|
||||
// Single-line comments start with //
|
||||
@ -29,7 +29,7 @@ Multi-line comments look like this
|
||||
/// </summary>
|
||||
/// <param name="firstParam">This is some parameter documentation for firstParam</param>
|
||||
/// <returns>Information on the returned value of a function</returns>
|
||||
public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {}
|
||||
public void MethodOrClassOrOtherWithParsableHelp(string firstParam) { }
|
||||
|
||||
// Specify the namespaces this source code will be using
|
||||
// The namespaces below are all part of the standard .NET Framework Class Library
|
||||
@ -48,6 +48,10 @@ using System.Data.Entity;
|
||||
|
||||
// Namespaces define scope to organize code into "packages" or "modules"
|
||||
// Using this code from another source file: using Learning.CSharp;
|
||||
|
||||
// You can also do this in C# 10, it is called file-scoped namespaces.
|
||||
// namespace Learning.CSharp;
|
||||
|
||||
namespace Learning.CSharp
|
||||
{
|
||||
// Each .cs file should at least contain a class with the same name as the file.
|
||||
@ -341,8 +345,17 @@ on a new line! ""Wow!"", the masses cried";
|
||||
|
||||
// Convert Integer To String
|
||||
// Convert class has a number of methods to facilitate conversions
|
||||
|
||||
// String to int
|
||||
|
||||
// Better
|
||||
bool result = int.TryParse(string, out var integer)
|
||||
int.Parse(string);
|
||||
|
||||
// Not recommended
|
||||
Convert.ToString(123);
|
||||
// or
|
||||
|
||||
// Int to string
|
||||
tryInt.ToString();
|
||||
|
||||
// Casting
|
||||
@ -375,6 +388,9 @@ on a new line! ""Wow!"", the masses cried";
|
||||
Console.Read();
|
||||
} // End main method
|
||||
|
||||
// Available in C# 9 and later, this is basically a syntactic sugar for a class. Records are immutable*.
|
||||
public record ARecord(string Csharp);
|
||||
|
||||
// CONSOLE ENTRY - A console application must have a main method as an entry point
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
@ -744,7 +760,7 @@ on a new line! ""Wow!"", the masses cried";
|
||||
Gitane // 43
|
||||
}
|
||||
// We defined this type inside a Bicycle class, so it is a nested type
|
||||
// Code outside of this class should reference this type as Bicycle.Brand
|
||||
// Code outside of this class should reference this type as Bicycle.BikeBrand
|
||||
|
||||
public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
|
||||
|
||||
@ -1299,16 +1315,27 @@ namespace Csharp7
|
||||
```
|
||||
|
||||
## Topics Not Covered
|
||||
✨ New, 👍 Old, 🎈 LTS, 🔥 Cross-platform, 🎁 Windows-only
|
||||
|
||||
* Attributes
|
||||
* async/await
|
||||
|
||||
* Asynchronous Programming
|
||||
|
||||
* Web Development
|
||||
* ASP.NET MVC & WebApi (new)
|
||||
* ASP.NET Web Forms (old)
|
||||
* WebMatrix (tool)
|
||||
* ASP.NET Core ✨
|
||||
|
||||
* Desktop Development
|
||||
* Windows Presentation Foundation (WPF) (new)
|
||||
* Winforms (old)
|
||||
* Windows Presentation Foundation 👍 🎈 🎁
|
||||
* Universal Windows Platform ✨ 🎁
|
||||
* Uno Platform 🔥 ✨
|
||||
* WinForms 👍 🎈 🎁
|
||||
* Avalonia 🔥 ✨
|
||||
* WinUI ✨ 🎁
|
||||
|
||||
* Cross-platform Development
|
||||
* Xamarin.Forms 👍
|
||||
* MAUI ✨
|
||||
|
||||
|
||||
## Further Reading
|
||||
|
||||
@ -1321,4 +1348,4 @@ namespace Csharp7
|
||||
* [LINQ Pocket Reference](http://shop.oreilly.com/product/9780596519254.do)
|
||||
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
|
||||
* [freeCodeCamp - C# Tutorial for Beginners](https://www.youtube.com/watch?v=GhQdlIFylQ8)
|
||||
|
||||
|
||||
|
@ -77,13 +77,11 @@ example1() {
|
||||
nested1();
|
||||
}
|
||||
|
||||
/// Anonymous functions don't include a name but can take number of arguments
|
||||
/// Anonymous functions don't include a name
|
||||
example2() {
|
||||
//// Explicit return type.
|
||||
nested1(Function<void> fn) {
|
||||
nested1(fn) {
|
||||
fn();
|
||||
}
|
||||
|
||||
nested1(() => print("Example2 nested 1"));
|
||||
}
|
||||
|
||||
@ -717,6 +715,6 @@ main() {
|
||||
## Further Reading
|
||||
|
||||
Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
|
||||
useful Try Dart online.
|
||||
[https://www.dartlang.org](https://www.dartlang.org)
|
||||
[https://try.dartlang.org](https://try.dartlang.org)
|
||||
useful DartPad (a cloud-based Dart coding playground).
|
||||
[https://dart.dev/](https://dart.dev)
|
||||
[https://dartpad.dev/](https://dartpad.dev)
|
||||
|
@ -10,7 +10,7 @@ translators:
|
||||
filename: LearnBash-de.sh
|
||||
---
|
||||
|
||||
Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und Mac OS X ausgeliefert wurde.
|
||||
Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und macOS ausgeliefert wurde.
|
||||
Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder direkt in der Shell ausgeführt werden.
|
||||
|
||||
[Weitere Informationen \(Englisch\)](http://www.gnu.org/software/bash/manual/bashref.html)
|
||||
|
@ -35,6 +35,10 @@ viele Features mit.
|
||||
0x1F # Integer
|
||||
3.0 # Float
|
||||
|
||||
# Für bessere Lesbarkeit des Codes können Unterstriche "_" als Trennzeichen verwendet werden
|
||||
1_000_000 == 1000000 # Integer
|
||||
1_000.567 == 1000.567 # Float
|
||||
|
||||
# Atome, das sind Literale, sind Konstanten mit Namen. Sie starten mit einem
|
||||
# ':'.
|
||||
:hello # Atom
|
||||
|
@ -356,3 +356,6 @@ with builtins; [
|
||||
|
||||
* [Susan Potter - Nix Cookbook - Nix By Example]
|
||||
(https://ops.functionalalgebra.com/nix-by-example/)
|
||||
|
||||
* [Rommel Martinez - A Gentle Introduction to the Nix Family]
|
||||
(https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
|
||||
|
@ -685,4 +685,4 @@ _(z.T. auf Englisch)_
|
||||
- [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/) - Eine ältere [freie Ausgabe](http://ruby-doc.com/docs/ProgrammingRuby/) ist online verfügbar.
|
||||
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Ein von der Community erstellter Ruby coding style guide.
|
||||
- [Try Ruby](http://tryruby.org) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser.
|
||||
- [Try Ruby](https://try.ruby-lang.org/) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser.
|
||||
|
@ -255,7 +255,7 @@ fn main() {
|
||||
|
||||
// `for` Schleife/Iterationen
|
||||
let array = [1, 2, 3];
|
||||
for i in array.iter() {
|
||||
for i in array {
|
||||
println!("{}", i);
|
||||
}
|
||||
|
||||
|
@ -11,7 +11,7 @@ filename: learnswift-de.swift
|
||||
lang: de-de
|
||||
---
|
||||
|
||||
Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und OS X Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
|
||||
Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und macOS Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
|
||||
|
||||
Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via iBooks verfügbar.
|
||||
|
||||
|
@ -3,9 +3,10 @@ language: docker
|
||||
filename: docker.bat
|
||||
contributors:
|
||||
- ["Ruslan López", "http://javapro.org/"]
|
||||
- ["Michael Chen", "https://github.com/ML-Chen"]
|
||||
---
|
||||
|
||||
```
|
||||
```bat
|
||||
:: download, install and run hello-world image
|
||||
docker run hello-world
|
||||
|
||||
@ -37,12 +38,12 @@ docker run hello-world
|
||||
:: For more examples and ideas, visit:
|
||||
:: https://docs.docker.com/get-started/
|
||||
|
||||
:: now lets see currently running images
|
||||
:: now let's see currently running images
|
||||
docker ps
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
:: NAMES
|
||||
|
||||
:: lets see the images we have ran previously
|
||||
:: let's see the images we have ran previously
|
||||
docker ps -a
|
||||
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
@ -54,7 +55,7 @@ docker ps -a
|
||||
:: let's remove our previously generated image
|
||||
docker rm happy_poincare
|
||||
|
||||
:: lets test if it was really deleted
|
||||
:: let's test if it was really deleted
|
||||
docker ps -a
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
:: NAMES
|
||||
@ -89,7 +90,7 @@ docker ps -a
|
||||
:: test_container
|
||||
:: as you can see the name is now what we have specified
|
||||
|
||||
:: retireve logs from a named container
|
||||
:: retrieve logs from a named container
|
||||
docker logs test_container
|
||||
:: Hello from Docker!
|
||||
:: This message shows that your installation appears to be working correctly.
|
||||
@ -143,4 +144,4 @@ docker ps -a
|
||||
:: nifty_goldwasser
|
||||
|
||||
docker rm nifty_goldwasser
|
||||
```
|
||||
```
|
||||
|
221
easylang.html.markdown
Normal file
@ -0,0 +1,221 @@
|
||||
---
|
||||
language: Easylang
|
||||
contributors:
|
||||
- ["chkas", "https://github.com/chkas"]
|
||||
filename: easylang.el
|
||||
---
|
||||
|
||||
**Easylang** is a simple programming language with built-in graphical functions and an easy-to-use and offline usable browser IDE. Its simple syntax and semantics make it well suited as a teaching and learning programming language. You can also use it to write graphical applications that you can embed in a web page.
|
||||
|
||||
*Easylang* is statically typed and has as data types only strings and numbers (floating point), resizeable arrays of strings and numbers and arrays of arrays.
|
||||
|
||||
[The browser IDE](https://easylang.online/ide/) includes various tutorials, including one for beginners.
|
||||
|
||||
```
|
||||
print "Hello world"
|
||||
#
|
||||
# number variable (64 bit floating point)
|
||||
#
|
||||
h = 3.14
|
||||
print h
|
||||
#
|
||||
# string variable
|
||||
#
|
||||
str$ = "monkey"
|
||||
# strings can grow
|
||||
str$ &= " circus"
|
||||
print str$
|
||||
#
|
||||
# blocks end with 'end' or a dot, a newline has no
|
||||
# other meaning than a space
|
||||
#
|
||||
for i = 1 to 5
|
||||
sum += i * i
|
||||
.
|
||||
print sum
|
||||
#
|
||||
# functions have value and reference
|
||||
# parameters, no return values
|
||||
#
|
||||
func gcd a b . res .
|
||||
# a and b are value parameters
|
||||
# res is a reference parameter
|
||||
while b <> 0
|
||||
# h is a local variable, because
|
||||
# it is first used in the function
|
||||
h = b
|
||||
b = a mod b
|
||||
a = h
|
||||
.
|
||||
res = a
|
||||
.
|
||||
call gcd 120 35 r
|
||||
print r
|
||||
#
|
||||
# strings can be concatenated and numbers are
|
||||
# automatically converted to strings
|
||||
#
|
||||
print "1 + 2 = " & 1 + 2
|
||||
#
|
||||
# array of numbers
|
||||
#
|
||||
a[] = [ 2.1 3.14 3 ]
|
||||
#
|
||||
# arrays can grow
|
||||
a[] &= 4
|
||||
print a[]
|
||||
#
|
||||
# arrays, strings and numbers are copied by value
|
||||
#
|
||||
b[] = a[]
|
||||
a[] &= 4
|
||||
print a[] ; print b[]
|
||||
#
|
||||
# array swapping ist fast
|
||||
#
|
||||
swap a[] b[]
|
||||
print a[] ; print b[]
|
||||
#
|
||||
# array of strings
|
||||
#
|
||||
fruits$[] = [ "apple" "banana" "orange" ]
|
||||
#
|
||||
# for-in iterates over the elements of an array
|
||||
#
|
||||
for fruit$ in fruits$[]
|
||||
print fruit$
|
||||
.
|
||||
#
|
||||
# strings are also used for single characters
|
||||
#
|
||||
letters$[] = str_chars "ping"
|
||||
print letters$[]
|
||||
letters$[1] = "o"
|
||||
print str_join letters$[]
|
||||
#
|
||||
# 2-dimensional arrays are arrays of arrays
|
||||
# this defines 3 arrays with length 4
|
||||
#
|
||||
len a[][] 3
|
||||
for i range len a[][]
|
||||
len a[i][] 4
|
||||
.
|
||||
a[1][2] = 99
|
||||
print a[][]
|
||||
#
|
||||
# builtin functions
|
||||
if sin 90 = 1
|
||||
print "angles are in degree"
|
||||
.
|
||||
print pow 2 8
|
||||
# seconds since 1970
|
||||
print floor sys_time
|
||||
# random numbers
|
||||
print randomf
|
||||
print random 6 + 1
|
||||
#
|
||||
# hour and minutes
|
||||
print substr time_str sys_time 11 5
|
||||
#
|
||||
print str_ord "A"
|
||||
print str_chr 65
|
||||
#
|
||||
# set number format
|
||||
numfmt 0 4
|
||||
print sqrt 2
|
||||
print pi
|
||||
print logn 10
|
||||
#
|
||||
a$[] = str_split "10,15,22" ","
|
||||
print a$[]
|
||||
print 2 * number a$[0]
|
||||
print len a$[]
|
||||
print len "Hello"
|
||||
#
|
||||
# With 'break n' you can leave nested loops and a function
|
||||
#
|
||||
names$[] = [ ]
|
||||
func name2id name$ . id .
|
||||
for id range len names$[]
|
||||
if names$[id] = name$
|
||||
# leave loop and function
|
||||
break 2
|
||||
.
|
||||
.
|
||||
names$[] &= name$
|
||||
.
|
||||
call name2id "alice" id ; print id
|
||||
call name2id "bob" id ; print id
|
||||
call name2id "alice" id ; print i
|
||||
#
|
||||
# with 'repeat' you can make loops, which you can leave
|
||||
# in the loop body using 'until'
|
||||
#
|
||||
sum = 0
|
||||
repeat
|
||||
s$ = input
|
||||
until s$ = ""
|
||||
sum += number s$
|
||||
.
|
||||
print "sum: " & sum
|
||||
#
|
||||
# "input" reads a string from the "input_data" section,
|
||||
# if it exists, otherwise via a prompt.
|
||||
#
|
||||
input_data
|
||||
10
|
||||
-2
|
||||
6
|
||||
```
|
||||
|
||||
Built-in graphic primitives and event-driven programming
|
||||
|
||||
```
|
||||
# simple drawing with the mouse
|
||||
#
|
||||
set_linewidth 4
|
||||
set_color 900
|
||||
# the colors are coded from 0 to 999, with
|
||||
# the left digit specifying the red component,
|
||||
# the middle digit the green component and
|
||||
# the right digit the blue component.
|
||||
#
|
||||
on mouse_down
|
||||
down = 1
|
||||
move_pen mouse_x mouse_y
|
||||
# moves the drawing pen to the actual mouse position
|
||||
draw_circle 2
|
||||
.
|
||||
on mouse_up
|
||||
down = 0
|
||||
.
|
||||
on mouse_move
|
||||
if down = 1
|
||||
draw_line mouse_x mouse_y
|
||||
.
|
||||
.
|
||||
```
|
||||
|
||||
```
|
||||
# an animated pendulum
|
||||
#
|
||||
on animate
|
||||
# The animate event occurs after each screen refresh.
|
||||
#
|
||||
clear_screen
|
||||
move_pen 50 50
|
||||
draw_circle 1
|
||||
x = 50 + 40 * sin ang
|
||||
y = 50 - 40 * cos ang
|
||||
draw_line x y
|
||||
draw_circle 5
|
||||
vel += sin ang / 5
|
||||
ang += vel
|
||||
.
|
||||
ang = 10
|
||||
```
|
||||
|
||||
* [More about Easylang](https://easylang.online/)
|
||||
|
||||
* [Source code](https://github.com/chkas/easylang)
|
||||
|
@ -8,7 +8,7 @@ lang: el-gr
|
||||
---
|
||||
|
||||
Η λέξη «bash» είναι ένα από τα ονόματα του unix shell (τερματικός), το οποίο
|
||||
διανέμεται επίσης ως προεπιλεγμένος τερματικός για το λειτουργικό σύστημα GNU, τα Linux και τα Mac OS X.
|
||||
διανέμεται επίσης ως προεπιλεγμένος τερματικός για το λειτουργικό σύστημα GNU, τα Linux και τα macOS.
|
||||
Σχεδόν όλα τα παραδείγματα που ακολουθούν μπορούν να αποτελέσουν μέρος ενός
|
||||
προγράμματος τερματικού (shell script) ή να εκτελεσθούν απευθείας από τον
|
||||
τερματικό.
|
||||
|
381
el-gr/ocaml-gr.html.markdown
Normal file
@ -0,0 +1,381 @@
|
||||
---
|
||||
language: OCaml
|
||||
filename: learnocaml-gr.ml
|
||||
contributors:
|
||||
- ["Daniil Baturin", "http://baturin.org/"]
|
||||
translators:
|
||||
- ["Chariton Charitonidis", "https://github.com/haritonch"]
|
||||
lang: el-gr
|
||||
---
|
||||
|
||||
Η OCaml είναι μία strictly evaluated συναρτησιακή γλώσσα με κάποια στοιχεία
|
||||
προστακτικού προγραμματισμού.
|
||||
|
||||
Μαζί με την StandardML και τις διαλέκτους της, ανήκει στην οικογένεια ML γλωσσών.
|
||||
Η F# είναι επίσης αρκετά επιρρεασμένη από την OCaml.
|
||||
|
||||
Ακριβώς όπως η StandardML, η OCaml διαθέτει έναν interpreter, που μπορεί να
|
||||
χρησιμοποιηθεί διαδραστικά, αλλά και έναν compiler.
|
||||
Το εκτελέσιμο αρχείο του interpreter κανονικά έχει το όνομα "ocaml" και ο compiler
|
||||
έχει το όνομα "ocamlopt".
|
||||
Υπάρχει και ένας bytecode compiler "ocamlc", αλλά δεν υπάρχουν πολλοί λόγοι να το
|
||||
χρησιμοποιήσει κάποιος.
|
||||
|
||||
Είναι ισχυρά και στατικά τυποποιημένη. Παρ'όλα αυτά , δεν χρειάζεται ο
|
||||
προγραμματιστής να δηλώνει τους τύπους, καθώς συμπερασμός τύπων γίνεται με τον
|
||||
αλγόριθμο του συστήματος τύπων Hindley-Milner. Αυτό κάνει τις δηλώσεις τύπων μη
|
||||
αναγκαίες στις περισσότερες περιπτώσεις, αλλά μπορεί να είναι δύσκολο στην αρχή.
|
||||
|
||||
Όταν είμαστε στο toplevel της OCaml (read-eval-print-loop), η OCaml τυπώνει τον
|
||||
τύπο που συμπεραίνει όταν εισάγουμε μια έκφραση.
|
||||
|
||||
```
|
||||
# let inc x = x + 1 ;;
|
||||
val inc : int -> int = <fun>
|
||||
# let a = 99 ;;
|
||||
val a : int = 99
|
||||
```
|
||||
Για ένα source αρχείο μπορούμε να χρησιμοποιούμε την εντολή
|
||||
"ocamlc -i /path/to/file.ml" στο terminal για να τυπώσει όλα τα ονόματα και
|
||||
τους τύπους.
|
||||
|
||||
```
|
||||
$ cat sigtest.ml
|
||||
let inc x = x + 1
|
||||
let add x y = x + y
|
||||
|
||||
let a = 1
|
||||
|
||||
$ ocamlc -i ./sigtest.ml
|
||||
val inc : int -> int
|
||||
val add : int -> int -> int
|
||||
val a : int
|
||||
```
|
||||
|
||||
Σημειώστε ότι τα type signatures των συναρτήσεων με πολλά ορίσματα είναι
|
||||
γραμμένα σε curried form. Μια συνάρτηση με πολλά ορίσματα μπορεί να
|
||||
αναπαρασταθεί ως σύνθεση συναρτήσεων με μόνο ένα όρισμα.
|
||||
Η "f(x,y) = x + y" από το παράδειγμα, όταν εφαρμόζεται στα ορίσματα 2 και 3
|
||||
είναι ισοδύναμη με την εφαρμογή της "f0(y) = 2 + y" στο 3. Γι' αυτό έχει τύπο
|
||||
"int -> int -> int".
|
||||
|
||||
|
||||
```ocaml
|
||||
(*** Comments ***)
|
||||
|
||||
(* Τα σχόλια περικλείονται σε (* και *). Μπορούν να είναι και εμφωλευμένα *)
|
||||
|
||||
(* Δεν υπάρχει ειδικό σύμβολο για σχόλια μιας γραμμής *)
|
||||
|
||||
|
||||
(*** Μεταβλητές και Συναρτήσεις ***)
|
||||
|
||||
(* Οι εκφράσεις διαχωρίζονται από διπλό semicolon, ";;".
|
||||
Σε πολλές περιπτώσεις είναι περιττό, αλλά εδώ θα το χρησιμοποιούμε σε
|
||||
κάθε έκφραση για ευκολότερο copy-paste στο interpreter shell.
|
||||
Το να χρησιμοποιούμε περιττά ;; σε αρχεία κώδικα θεωρείται συνήθως
|
||||
κακό στυλιστικά. *)
|
||||
|
||||
(* Οι δηλώσεις μεταβλητών και συναρτήσεων χρησιμοποιούν το keyword "let" *)
|
||||
let x = 10 ;;
|
||||
|
||||
(* Η OCaml επιτρέπει χαρακτήρες μονών εισαγωγικών σε identifiers.
|
||||
το μονό εισαγωγικό δεν έχει κάποια σημασία σε αυτή την περίπτωση,
|
||||
χρησιμοποιείται συνήθως σε περιπτώσεις που σε άλλες γλώσσες χρησιμοποιούμε
|
||||
ονόματα όπως "foo_tmp". *)
|
||||
let foo = 1 ;;
|
||||
let foo' = foo * 2 ;;
|
||||
|
||||
(* Από τη στιγμή που ο compiler της OCaml συμπεραίνει τους τύπους αυτόματα,
|
||||
κανονικά δεν χρειάζεται να δηλώνουμε ρητά τον τύπο ορισμάτων. Παρ'όλα αυτά
|
||||
μπορούμε να το κάνουμε αν θέλουμε ή χρειάζεται *)
|
||||
let inc_int (x: int) : int = x + 1 ;;
|
||||
|
||||
(* Μία από αυτές τις περιπτώσεις που είναι αναγκαίο να δηλώσουμε ρητά τύπους
|
||||
είναι για να λύσουμε την αμφισημία μεταξύ δύο record types που έχουν πεδία με
|
||||
όμοια ονόματα. Η εναλλακτική είναι να βάλουμε αυτούς τους τύπους σε modules,
|
||||
αλλά και τα δύο αυτά θέματα είναι εκτός του σκοπού αυτού το μαθήματος. *)
|
||||
|
||||
(* Πρέπει να δηλώνουμε ότι μία συνάρτηση είναι αναδρομική με "rec". *)
|
||||
let rec factorial n =
|
||||
if n = 0 then 1
|
||||
else n * factorial (n-1)
|
||||
;;
|
||||
|
||||
(* H εφαρμογή συναρτήσεων συνήθως δεν χρειάζεται παρενθέσεις γύρω από ορίσματα *)
|
||||
let fact_5 = factorial 5 ;;
|
||||
|
||||
(* ...εκτός αν τα ορίσματα είναι εκφράσεις *)
|
||||
let fact_4 = factorial (5-1) ;;
|
||||
let sqr2 = sqr (-2) ;;
|
||||
|
||||
(* Κάθε συνάρητση πρέπει να έχει τουλάχιστον ένα όρισμα.
|
||||
Από τη στιγμή που κάποιες συναρτήσεις, από τη φύση τους, δεν παίρνουν κάποιο
|
||||
όρισμα, υπάρχει ο τύπος "unit" που έχει μόνο μία τιμή,
|
||||
την οποία γράφουμε ως "()". *)
|
||||
let print_hello () = print_endline "hello world" ;;
|
||||
|
||||
(* Προσέχετε ότι πρέπει να γράφουμε το "()" ως όρισμα και όταν την καλούμε. *)
|
||||
print_hello () ;;
|
||||
|
||||
(* Το να καλούμε μια συνάρτηση με λιγότερα ορίσματα από όσα δέχεται
|
||||
δεν προκαλεί πρόβλημα, απλά παράγει μια νέα συνάρτηση. *)
|
||||
let make_inc x y = x + y ;; (* make_inc is int -> int -> int *)
|
||||
let inc_2 = make_inc 2 ;; (* inc_2 is int -> int *)
|
||||
inc_2 3 ;; (* Αποτιμάται σε 5 *)
|
||||
|
||||
(* Μπορούμε να χρησιμοποιούμε πολλές εκφράσεις στο σώμα μιας συνάρτησης.
|
||||
Η αποτίμηση της τελευταίας έκφρασης είναι η τιμή που επιστρέφει η συνάρτηση.
|
||||
Όλες οι ενδιάμεσες εκφράσεις πρέπει να είναι τύπου "unit".
|
||||
Αυτό είναι ιδιαίτερα χρήσιμο όταν γράφουμε σε προστακτικό στυλ, η απλούστερη
|
||||
μορφή αυτού είναι η εισαγωγή ενός debug print. *)
|
||||
let print_and_return x =
|
||||
print_endline (string_of_int x);
|
||||
x
|
||||
;;
|
||||
|
||||
(* Ως συναρτησιακή γλώσσα η OCaml δεν έχει "procedures" (διαδικασίες).
|
||||
Κάθε συνάρτηση πρέπει να επιστρέφει κάτι. Οπότε, συναρτήσεις που δεν
|
||||
επιστρέφουν κάτι και καλούνται μόνο για τις παρενέργειες τους,
|
||||
όπως η print_endline, επιστρέφουν τιμή τύπου "unit". *)
|
||||
|
||||
|
||||
(* Οι ορισμοί μπορούν να γίνουν αλυσιδωτά με τη δομή "let ... in".
|
||||
Αυτό είναι περίπου το ίδιο με το να αναθέτουμε τιμές σε πολλές μεταβλητές
|
||||
πριν τις χρησιμοποιήσουμε σε εκφράσεις σε προστακτικές γλώσσες. *)
|
||||
let x = 10 in
|
||||
let y = 20 in
|
||||
x + y ;;
|
||||
|
||||
(* Εναλλακτικά μπορούμε να χρησιμποιούμε τη δομή "let ... and ... in".
|
||||
Αυτό είναι εξαιρετικά χρήσιμο για αμοιβαία αποκλειόμενες συναρτήσεις,
|
||||
όπυ με "let .. in", ο compiler θα παραπονιόταν για unbound values *)
|
||||
let rec
|
||||
is_even = function
|
||||
| 0 -> true
|
||||
| n -> is_odd (n-1)
|
||||
and
|
||||
is_odd = function
|
||||
| 0 -> false
|
||||
| n -> is_even (n-1)
|
||||
;;
|
||||
|
||||
(* Οι ανώνυμες συναρτήσεις χρησιμοποιούν την εξής σύνταξη: *)
|
||||
let my_lambda = fun x -> x * x ;;
|
||||
|
||||
(*** Τελεστές ***)
|
||||
|
||||
(* Δεν υπάρχει ιδιαίτερη διάκριση ανάμεσα σε τελεστές και συναρτήσεις.
|
||||
Κάθε τελεστής μπορεί να κληθεί ως συνάρτηση. *)
|
||||
|
||||
(+) 3 4 (* Same as 3 + 4 *)
|
||||
|
||||
(* Υπάρχει ένας αριθμός built-in τελεστών. Ένα ασυνήθιστο χαρακτηριστικό είναι
|
||||
ότι η OCaml δεν μπορεί να κάνει έμμεση μετατροπή τύπων
|
||||
ανάμεσα σε ακεραίους και floats, επίσης, χρησιμοποιεί διαφορετικούς τελεστές
|
||||
για τους floats (αριθμούς κινητής υποδιαστολής) *)
|
||||
12 + 3 ;; (* Πρόσθεση ακεραίων. *)
|
||||
12.0 +. 3.0 ;; (* Πρόσθεση κινητής υποδιαστολής. *)
|
||||
|
||||
12 / 3 ;; (* Διαίρεση ακεραίων. *)
|
||||
12.0 /. 3.0 ;; (* Διαίρεση κινητής υποδιαστολής. *)
|
||||
5 mod 2 ;; (* Υπόλοιπο. *)
|
||||
|
||||
(* Το ενός-ορίσματος μείον είναι αξιοσημείωτη εξαίρεση, είναι πολυμορφικό.
|
||||
Ωστόσο, έχει καθαρές μορφές ακεραίων και float. *)
|
||||
- 3 ;; (* Πολυμορφικό, ακέραιοι *)
|
||||
- 4.5 ;; (* Πολυμορφικό, float *)
|
||||
~- 3 (* Μόνο για integer *)
|
||||
~- 3.4 (* Type error *)
|
||||
~-. 3.4 (* Μόνο για float *)
|
||||
|
||||
(* Μπορούμε να ορίζουμε δικούς μας τελεστές ή να ξανα-ορίσουμε υπάρχοντες.
|
||||
Σε αντίθεση με την SML ή τη Haskell, μόνο ορισμένα σύμβολα μπορούν να
|
||||
χρησιμοποιηθούν για ονόματα τελεστών και το πρώτο σύμβολο ορίζει την
|
||||
επιμεριστικότητα και προτεραιότητα πράξεων. *)
|
||||
let (+) a b = a - b ;; (* και καλή τύχη στον επόμενο... *)
|
||||
|
||||
(* Πιο χρήσιμο: ένας τελεστής αντιστρόφου για floats.
|
||||
οι τελεστές ενός-ορίσματος πρέπει να ξεκινούν με "~". *)
|
||||
let (~/) x = 1.0 /. x ;;
|
||||
~/4.0 (* = 0.25 *)
|
||||
|
||||
|
||||
(*** Built-in δομές δεδομένων ***)
|
||||
|
||||
(* Οι λίστες περικλείονται από αγκύλες και τα στοιχεία τους
|
||||
διαχωρίζονται με semicolons. *)
|
||||
let my_list = [1; 2; 3] ;;
|
||||
|
||||
(* Οι tuples (προαιρετικά) περικλείονται από παρενθέσεις, τα στοιχεία τους
|
||||
διαχωρίζονται με κόμματα. *)
|
||||
let first_tuple = 3, 4 ;; (* Έχει τύπο "int * int". *)
|
||||
let second_tuple = (4, 5) ;;
|
||||
|
||||
(* Συνέπεια: αν προσπαθήσεουμε να διαχωρίσουμε τα στοιχεία μιας λίστας
|
||||
με κόμματα, θα πάρουμε μια λίστα με ένα tuple ως στοιχείο.
|
||||
Μπορεί να την πατήσουμε εύκολα έτσι. *)
|
||||
let bad_list = [1, 2] ;; (* Becomes [(1, 2)] *)
|
||||
|
||||
(* Μπρούμε να προσπελάσουμε στοιχεία μιας λίστας με τη συνάρτηση List.nth. *)
|
||||
List.nth my_list 1 ;;
|
||||
|
||||
(* Yπάρχουν συναρτήσεις ανώτερης τάξης για λίστες, όπως οι map και filter. *)
|
||||
List.map (fun x -> x * 2) [1; 2; 3] ;;
|
||||
List.filter (fun x -> x mod 2 = 0) [1; 2; 3; 4] ;;
|
||||
|
||||
(* Μπορούμε να προσθέτουμε στοιχεία στην αρχή μιας λίστας με τον
|
||||
constructor "::", συνήθως αναφέρεται ως "cons". *)
|
||||
1 :: [2; 3] ;; (* Αποτέλεσμα: [1; 2; 3] *)
|
||||
|
||||
(* Οι πίνακες Arrays περικλείονται από [| |] *)
|
||||
let my_array = [| 1; 2; 3 |] ;;
|
||||
|
||||
(* Προσπελαύνουμε στοιχεία ενός πίνακα ως εξής: *)
|
||||
my_array.(0) ;;
|
||||
|
||||
|
||||
(*** Strings και Χαρακτήρες ***)
|
||||
|
||||
(* Χρησιμοποιούμε διπλά εισαγωγικά για τα string literals. *)
|
||||
let my_str = "Hello world" ;;
|
||||
|
||||
(* Μονά εισαγωγικά για τα literals χαρακτήρων. *)
|
||||
let my_char = 'a' ;;
|
||||
|
||||
(* Τα μονά και τα διπλά εισαγωγικά δεν είναι ισοδύναμα. *)
|
||||
let bad_str = 'syntax error' ;; (* Syntax error. *)
|
||||
|
||||
(* Αυτό μας δίνει ένα string με έναν χαρακτήρα και όχι εναν χαρακτήρα. *)
|
||||
let single_char_str = "w" ;;
|
||||
|
||||
(* Τα strings παρατίθενται με τον τελεστή "^". *)
|
||||
let some_str = "hello" ^ "world" ;;
|
||||
|
||||
(* Τα strings δεν είναι πίνακες από χαρακτήρες όπως στην C.
|
||||
Δεν μπορούμε να ανακατεύουμε strings με χαρακτήρες σε εκφράσεις.
|
||||
Μπορούμε να μετατρέπουμε χαρακτήρες σε strings με "String.make 1 my_char".
|
||||
Υπάρχουν πιο βολικές συναρτήσεις για αυτό το σκοπό σε πρόσθετες βιβλιοθήκες,
|
||||
όπως η Core.Std που μπορεί να μην έχουν εγκατασταθεί/φορτωθεί by default. *)
|
||||
let ocaml = (String.make 1 'O') ^ "Caml" ;;
|
||||
|
||||
(* Υπάρχει και μια συνάρτηση printf. *)
|
||||
Printf.printf "%d %s" 99 "bottles of beer" ;;
|
||||
|
||||
(* Υπάρχουν και συναρτήσεις read/write χωρίς μορφοποίηση. *)
|
||||
print_string "hello world\n" ;;
|
||||
print_endline "hello world" ;;
|
||||
let line = read_line () ;;
|
||||
|
||||
|
||||
(*** User-defined τύποι δεδομένων ***)
|
||||
|
||||
(* Μπορούμε να ορίζουμε τύπους δεδομένων με τη δομή "type some_type".
|
||||
Όπως σε αυτό τον άχρηστο τύπο που αντιγράφει τους ακεραίους: *)
|
||||
type my_int = int ;;
|
||||
|
||||
(* Πιο ενδιαφέροντες τύποι περιλαμβάνουν τους λεγόμενους type constructors.
|
||||
Αυτοί πρέπει να ξεκινούν με κεφαλαίο γράμμα. *)
|
||||
type ml = OCaml | StandardML ;;
|
||||
let lang = OCaml ;; (* Έχει τύπο "ml". *)
|
||||
|
||||
(* Οι type constructors δε χρειάζεται να είναι κενοί. *)
|
||||
type my_number = PlusInfinity | MinusInfinity | Real of float ;;
|
||||
let r0 = Real (-3.4) ;; (* Έχει τύπο "my_number". *)
|
||||
|
||||
(* Μπορούν να χρησιμοποιηθούν για πολυμορφική αριθμιτική *)
|
||||
type number = Int of int | Float of float ;;
|
||||
|
||||
(* Σημείο στο επίπεδο, βασικά ένα tuple περιορισμένου συγκεκριμένου τύπου *)
|
||||
type point2d = Point of float * float ;;
|
||||
let my_point = Point (2.0, 3.0) ;;
|
||||
|
||||
(* Οι τύποι μπορούν να είναι παραμετροποιημένοι, όπως σε αυτόν τον τύπο για
|
||||
λίστες λίστών με οτιδήποτε τύπου στοιχεία. Το 'a μπορεί να αντικατασταθεί από
|
||||
οποιονδήποτε τύπο. *)
|
||||
type 'a list_of_lists = 'a list list ;;
|
||||
type int_list_list = int list_of_lists ;;
|
||||
|
||||
(* Οι τύποι μπορούν επίσης να ορίζονται αναδρομικά. Σαν αυτόν εδώ τον τύπο που
|
||||
είναι ανάλογος της built in λίστας από ακεραίους. *)
|
||||
type my_int_list = EmptyList | IntList of int * my_int_list ;;
|
||||
let l = IntList (1, EmptyList) ;;
|
||||
|
||||
|
||||
(*** Ταίριασμα Προτύπων - Pattern Matching ***)
|
||||
|
||||
(* Το ταίριασμα προτύπων είναι κάπως σαν το switch statement σε προστακτικές
|
||||
γλώσσες προγραμματισμού, αλλά παρέχει πολύ μεγαλύτερη εκφραστική ισχύ.
|
||||
|
||||
Παρόλο που φαίνεται περίπλοκο, στην πραγματικότητα είναι απλώς ταίριασμα
|
||||
ενός ορίσματος με μια συγκεκριμένη τιμή, ένα κατηγόρημα ή έναν type constructor
|
||||
Το σύστημα τύπων είναι αυτό που το κάνει τόσο ισχυρό. *)
|
||||
|
||||
(** Ταίριασμα με ακριβείς τιμές. **)
|
||||
|
||||
let is_zero x =
|
||||
match x with
|
||||
| 0 -> true
|
||||
| _ -> false (* Το "_" σημαίνει "οτιδήποτε άλλο". *)
|
||||
;;
|
||||
|
||||
(* Εναλλακτικά μπορούμε να χρησιμοποιούμε το keyword "function". *)
|
||||
let is_one = function
|
||||
| 1 -> true
|
||||
| _ -> false
|
||||
;;
|
||||
|
||||
(* Ταίριασμα με κατηγορήματα, γνωστό και ως "guarded pattern matching". *)
|
||||
let abs x =
|
||||
match x with
|
||||
| x when x < 0 -> -x
|
||||
| _ -> x
|
||||
;;
|
||||
|
||||
abs 5 ;; (* 5 *)
|
||||
abs (-5) ;; (* 5 πάλι *)
|
||||
|
||||
(** Ταίριασμα με type constructors **)
|
||||
|
||||
type animal = Dog of string | Cat of string ;;
|
||||
|
||||
let say x =
|
||||
match x with
|
||||
| Dog x -> x ^ " says woof"
|
||||
| Cat x -> x ^ " says meow"
|
||||
;;
|
||||
|
||||
say (Cat "Fluffy") ;; (* "Fluffy says meow". *)
|
||||
|
||||
(** Διάσχιση δομών δεδομένων με ταίριασμα προτύπων **)
|
||||
|
||||
(* Οι αναδρομικοί τύποι μπορούν να διασχιστούν εύκολα με ταίριασμα προτύπων.
|
||||
Ας δούμε πώς μπορούμε να διασχίσουμε μια λίστα.
|
||||
Παρόλο που το built-in cons ("::") μοιάζει με infix τελεστή,
|
||||
στην πραγματικότητα είναι ένας type constructor και μπορεί να
|
||||
ταιριαστεί όπως όλοι οι type constructors. *)
|
||||
let rec sum_list l =
|
||||
match l with
|
||||
| [] -> 0
|
||||
| head :: tail -> head + (sum_list tail)
|
||||
;;
|
||||
|
||||
sum_list [1; 2; 3] ;; (* Αποτιμάται σε 6 *)
|
||||
|
||||
(* Η built-in συνταξη των cons εμποδίζει τη δομή λίγο, γι αυτό θα φτιάξουμε
|
||||
το δικό μας τύπο λίστας για την παρουσίαση. *)
|
||||
type int_list = Nil | Cons of int * int_list ;;
|
||||
let rec sum_int_list l =
|
||||
match l with
|
||||
| Nil -> 0
|
||||
| Cons (head, tail) -> head + (sum_int_list tail)
|
||||
;;
|
||||
|
||||
let t = Cons (1, Cons (2, Cons (3, Nil))) ;;
|
||||
sum_int_list t ;;
|
||||
```
|
||||
|
||||
## Περισσότερα για την OCaml
|
||||
|
||||
* Επισκεφθείτε την επίσημη σελίδα της OCaml για να κατεβάσετε τον compiler και να διαβάσετε το documentation: <http://ocaml.org/>
|
||||
* Δοκιμάστε διαδραστικά μαθήματα και έναν web-based interpreter από την OCaml Pro: <http://try.ocamlpro.com/>
|
@ -242,7 +242,7 @@ fn main() {
|
||||
|
||||
// Βρόγχοι `for`
|
||||
let array = [1, 2, 3];
|
||||
for i in array.iter() {
|
||||
for i in array {
|
||||
println!("{}", i);
|
||||
}
|
||||
|
||||
|
@ -3,7 +3,7 @@ category: tool
|
||||
tool: vim
|
||||
contributors:
|
||||
- ["RadhikaG", "https://github.com/RadhikaG"]
|
||||
filename: LearnVim.txt
|
||||
filename: LearnVim-gr.txt
|
||||
lang: el-gr
|
||||
---
|
||||
|
||||
|
@ -33,7 +33,7 @@ and many more features.
|
||||
0x1F # integer
|
||||
3.0 # float
|
||||
|
||||
# Atoms, that are literals, a constant with name. They start with `:`.
|
||||
# Atoms are constants whose values are their own name. They start with `:`.
|
||||
:hello # atom
|
||||
|
||||
# Tuples that are stored contiguously in memory.
|
||||
|
@ -18,7 +18,7 @@ Tutorial de Shell en español.
|
||||
|
||||
Bash es el nombre del shell de unix, el cual también es distribuido como
|
||||
el shell del sistema operativo GNU. También es el shell
|
||||
por defecto de Linux y Mac OS X. Casi todos los ejemplos abajo pueden
|
||||
por defecto de Linux y macOS. Casi todos los ejemplos abajo pueden
|
||||
ser parte de un script shell o ser ejecutados directamente en la terminal.
|
||||
|
||||
[Leer más aquí.](http://www.gnu.org/software/bash/manual/bashref.html)
|
||||
|
@ -8,6 +8,7 @@ contributors:
|
||||
- ["Connor Waters", "http://github.com/connorwaters"]
|
||||
translators:
|
||||
- ["Gerson Lázaro", "https://gersonlazaro.com"]
|
||||
- ["Diego Ramirez", "https://DiddiLeija.github.io"]
|
||||
lang: es-es
|
||||
---
|
||||
|
||||
@ -101,8 +102,8 @@ void print(int myInt)
|
||||
|
||||
int main()
|
||||
{
|
||||
print("Hello"); // Resolves to void print(const char*)
|
||||
print(15); // Resolves to void print(int)
|
||||
print("Hello"); // Corresponde a void print(const char*)
|
||||
print(15); // Corresponde a void print(int)
|
||||
}
|
||||
|
||||
////////////////////////////////////
|
||||
@ -114,7 +115,7 @@ int main()
|
||||
|
||||
void doSomethingWithInts(int a = 1, int b = 4)
|
||||
{
|
||||
// Hacer algo con los enteros aqui
|
||||
// Hacer algo con los enteros aquí
|
||||
}
|
||||
|
||||
int main()
|
||||
@ -134,7 +135,7 @@ void invalidDeclaration(int a = 1, int b) // Error!
|
||||
// Espacios de nombre
|
||||
/////////////////////
|
||||
|
||||
// Espacios de nombres proporcionan ámbitos separados para variable, función y
|
||||
// Los espacios de nombres proporcionan ámbitos separados para variable, función y
|
||||
// otras declaraciones.
|
||||
// Los espacios de nombres se pueden anidar.
|
||||
|
||||
@ -184,7 +185,7 @@ int main()
|
||||
|
||||
#include <iostream> // Incluir para el flujo de entrada/salida
|
||||
|
||||
using namespace std; // Los streams estan en std namespace (libreria estandar)
|
||||
using namespace std; // Los streams estan en el espacio de nombre std (libreria estandar)
|
||||
|
||||
int main()
|
||||
{
|
||||
@ -208,7 +209,7 @@ int main()
|
||||
// Las cadenas en C++ son objetos y tienen muchas funciones
|
||||
#include <string>
|
||||
|
||||
using namespace std; // Strings también estan en namespace std
|
||||
using namespace std; // Las cadenas también estan en el nombre de espacio std
|
||||
|
||||
string myString = "Hola";
|
||||
string myOtherString = " Mundo";
|
||||
@ -252,7 +253,7 @@ fooRef = bar;
|
||||
const string& barRef = bar; // Crea una referencia constante a bar.
|
||||
// Como en C, los valores constantes (y punteros y referencias) no pueden ser
|
||||
// modificados.
|
||||
barRef += ". Hola!"; // Error, referencia constante no puede ser modificada.
|
||||
barRef += ". Hola!"; // Error, una referencia constante no puede ser modificada.
|
||||
|
||||
// Sidetrack: Antes de hablar más sobre referencias, hay que introducir un
|
||||
// concepto llamado objeto temporal. Supongamos que tenemos el siguiente código:
|
||||
@ -264,7 +265,7 @@ string retVal = tempObjectFun();
|
||||
// - Una nueva cadena se construye con el objeto devuelto como argumento al
|
||||
// constructor
|
||||
// - El objeto devuelto es destruido
|
||||
// El objeto devuelto se llama objeto temporal. Objetos temporales son
|
||||
// El objeto devuelto se llama objeto temporal. Los objetos temporales son
|
||||
// creados cada vez que una función devuelve un objeto, y es destruido en el
|
||||
// fin de la evaluación de la expresión que encierra (Bueno, esto es lo que la
|
||||
// norma dice, pero los compiladores están autorizados a cambiar este
|
||||
@ -295,7 +296,7 @@ void someFun(string&& s) { ... } // Referencia a objeto temporal
|
||||
|
||||
string foo;
|
||||
someFun(foo); // Llama la función con referencia regular
|
||||
someFun(tempObjectFun()); // Llama la versión con referencia temporal
|
||||
someFun(tempObjectFun()); // Llama la función con referencia temporal
|
||||
|
||||
// Por ejemplo, puedes ver estas dos versiones de constructores para
|
||||
// std::basic_string:
|
||||
@ -305,7 +306,7 @@ basic_string(basic_string&& other);
|
||||
// La idea es que si estamos construyendo una nueva cadena de un objeto temporal
|
||||
// (que va a ser destruido pronto de todos modos), podemos tener un constructor
|
||||
// mas eficiente que "rescata" partes de esa cadena temporal. Usted verá este
|
||||
// Concepto denominado "movimiento semántico".
|
||||
// concepto denominado "movimiento semántico".
|
||||
|
||||
////////////////////////////////////////////
|
||||
// Clases y programación orientada a objetos
|
||||
@ -322,9 +323,7 @@ class Dog {
|
||||
int weight;
|
||||
|
||||
// Todos los miembros siguientes de este son públicos
|
||||
// Hasta que se encuentre "private" o "protected".
|
||||
// All members following this are public
|
||||
// until "private:" or "protected:" is found.
|
||||
// hasta que se encuentre "private" o "protected".
|
||||
public:
|
||||
|
||||
// Constructor por defecto
|
||||
@ -339,8 +338,8 @@ public:
|
||||
|
||||
void setWeight(int dogsWeight);
|
||||
// Funciones que no modifican el estado del objeto
|
||||
// Deben marcarse como const.
|
||||
// Esto le permite llamarlas si se envia una referencia constante al objeto.
|
||||
// deben marcarse como const.
|
||||
// Esto le permite llamarlas si se envía una referencia constante al objeto.
|
||||
// También tenga en cuenta que las funciones deben ser declaradas
|
||||
// explícitamente como _virtual_ para que sea reemplazada en las clases
|
||||
// derivadas.
|
||||
@ -357,8 +356,8 @@ public:
|
||||
// Esto permite paradigmas potentes como RAII
|
||||
// (mira abajo)
|
||||
// El destructor debe ser virtual si una clase es dervada desde el;
|
||||
// Si no es virtual, entonces la clase derivada destructor
|
||||
// No será llamada si el objeto se destruye a través de una referencia de
|
||||
// Si no es virtual, entonces la clase destructora derivada
|
||||
// no será llamada si el objeto se destruye a través de una referencia de
|
||||
// la clase base o puntero.
|
||||
virtual ~Dog();
|
||||
|
||||
@ -373,7 +372,7 @@ Dog::Dog()
|
||||
}
|
||||
|
||||
// Objetos (tales como cadenas) deben ser pasados por referencia
|
||||
// Si los estas modificando o referencia constante en caso contrario.
|
||||
// si los estás modificando, o referencia constante en caso contrario.
|
||||
void Dog::setName(const std::string& dogsName)
|
||||
{
|
||||
name = dogsName;
|
||||
@ -413,9 +412,9 @@ class OwnedDog : public Dog {
|
||||
// Reemplaza el comportamiento de la función de impresión
|
||||
// de todos los OwnedDogs. Mira
|
||||
// http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
|
||||
// Para una introducción más general si no está familiarizado con el
|
||||
// para una introducción más general si no está familiarizado con el
|
||||
// polimorfismo de subtipo.
|
||||
// La palabra clave override es opcional, pero asegura que estás
|
||||
// La palabra clave override es opcional, pero asegúrate de que estás
|
||||
// reemplazando el método de una clase base.
|
||||
void print() const override;
|
||||
|
||||
@ -460,8 +459,8 @@ public:
|
||||
// pero inicializa el punto al valor por defecto (0, 0)
|
||||
Point() { };
|
||||
|
||||
// The following syntax is known as an initialization list
|
||||
// and is the proper way to initialize class member values
|
||||
// La siguiente sintaxis se conoce como lista de inicialización
|
||||
// y es la forma correcta de inicializar los valores de los miembros de la clase
|
||||
Point (double a, double b) :
|
||||
x(a),
|
||||
y(b)
|
||||
@ -474,7 +473,7 @@ public:
|
||||
Point& operator+=(const Point& rhs);
|
||||
|
||||
// También tendría sentido añadir los operadores - y -=,
|
||||
// Pero vamos a omitirlos por razones de brevedad.
|
||||
// pero vamos a omitirlos por razones de brevedad.
|
||||
};
|
||||
|
||||
Point Point::operator+(const Point& rhs) const
|
||||
@ -496,7 +495,7 @@ int main () {
|
||||
// Llama al operador + de Point
|
||||
// Point llama la función + con right como parámetro
|
||||
Point result = up + right;
|
||||
// Prints "Result is upright (1,1)"
|
||||
// Imprime "Result is upright (1,1)"
|
||||
cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
|
||||
return 0;
|
||||
}
|
||||
@ -525,7 +524,7 @@ public:
|
||||
// plantilla con parámetros sustituidos, por lo que la definición completa
|
||||
// de la clase debe estar presente en cada invocación.
|
||||
// Es por esto que usted verá clases de plantilla definidas
|
||||
// Enteramente en archivos de cabecera.
|
||||
// enteramente en archivos de cabecera.
|
||||
|
||||
//Para crear una instancia de una clase de plantilla en la pila:
|
||||
Box<int> intBox;
|
||||
@ -544,7 +543,7 @@ boxOfBox.insert(intBox);
|
||||
|
||||
// A veces verás
|
||||
// template<typename T>
|
||||
// en su lugar. La palabra clave "class" y las palabras clave "typename" son
|
||||
// en su lugar. La palabra clave "class" y la palabra clave "typename" son
|
||||
// mayormente intercambiables en este caso. Para la explicación completa, mira
|
||||
// http://en.wikipedia.org/wiki/Typename
|
||||
// (sí, esa palabra clave tiene su propia página de Wikipedia).
|
||||
@ -568,7 +567,7 @@ Dog fluffy;
|
||||
fluffy.setName("Fluffy")
|
||||
barkThreeTimes(fluffy); // Imprime "Fluffy barks" 3 veces.
|
||||
|
||||
Los parámetros de la plantilla no tienen que ser las clases:
|
||||
// Los parámetros de la plantilla no tienen que ser las clases:
|
||||
template<int Y>
|
||||
void printMessage() {
|
||||
cout << "Aprende C++ en " << Y << " minutos!" << endl;
|
||||
@ -604,7 +603,7 @@ printMessage<10>(); // Prints "Aprende C++ rapido en solo 10 minutos!"
|
||||
//Todas las excepciones lanzadas dentro del bloque _try_ pueden ser
|
||||
// capturados por los siguientes manejadores _catch_.
|
||||
try {
|
||||
// No asignar excepciones en el heap usando _new_.
|
||||
// No asigne excepciones en el heap usando _new_.
|
||||
throw std::runtime_error("Ocurrió un problema");
|
||||
}
|
||||
|
||||
@ -629,10 +628,10 @@ catch (...)
|
||||
// (Adquisición de recursos es inicialización).
|
||||
// A menudo se considera el paradigma más poderoso en C++
|
||||
// Y el concepto es simple: un constructor de un objeto
|
||||
// Adquiere recursos de ese objeto y el destructor les libera.
|
||||
// adquiere recursos de ese objeto y el destructor les libera.
|
||||
|
||||
// Para entender cómo esto es útil,
|
||||
// Considere una función que utiliza un identificador de archivo C:
|
||||
// considere una función que utiliza un identificador de archivo C:
|
||||
void doSomethingWithAFile(const char* filename)
|
||||
{
|
||||
// Para empezar, asuma que nada puede fallar.
|
||||
@ -691,11 +690,11 @@ bool doSomethingWithAFile(const char* filename)
|
||||
|
||||
failure:
|
||||
fclose(fh);
|
||||
return false; // Propagate el error
|
||||
return false; // Propaga el error
|
||||
}
|
||||
|
||||
// Si las funciones indican errores mediante excepciones,
|
||||
// Las cosas son un poco más claras, pero pueden optimizarse mas.
|
||||
// las cosas son un poco más claras, pero pueden optimizarse más.
|
||||
void doSomethingWithAFile(const char* filename)
|
||||
{
|
||||
FILE* fh = fopen(filename, "r"); // Abrir el archivo en modo lectura
|
||||
@ -732,9 +731,9 @@ void doSomethingWithAFile(const std::string& filename)
|
||||
|
||||
// Esto tiene ventajas _enormes_:
|
||||
// 1. No importa lo que pase,
|
||||
// El recurso (en este caso el manejador de archivo) será limpiado.
|
||||
// el recurso (en este caso el manejador de archivo) será limpiado.
|
||||
// Una vez que escribes el destructor correctamente,
|
||||
// Es _imposible_ olvidar cerrar el identificador y permitir
|
||||
// es _imposible_ olvidar cerrar el identificador y permitir
|
||||
// fugas del recurso.
|
||||
// 2. Tenga en cuenta que el código es mucho más limpio.
|
||||
// El destructor se encarga de cerrar el archivo detrás de cámaras
|
||||
|
167
es-es/docker-es.html.markdown
Normal file
@ -0,0 +1,167 @@
|
||||
---
|
||||
language: docker
|
||||
filename: docker-es.bat
|
||||
contributors:
|
||||
- ["Ruslan López", "http://javapro.org/"]
|
||||
- ["Michael Chen", "https://github.com/ML-Chen"]
|
||||
lang: es-es
|
||||
---
|
||||
|
||||
```bat
|
||||
:: descargar, instalar y ejecutar la imágen del hola mundo
|
||||
docker run hello-world
|
||||
|
||||
:: Si esta es la primera vez, deberíais de poder ver el mensaje
|
||||
:: Unable to find image 'hello-world:latest' locally
|
||||
:: latest: Pulling from library/hello-world
|
||||
:: 1b930d010525: Pull complete
|
||||
:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064
|
||||
:: Status: Downloaded newer image for hello-world:latest
|
||||
::
|
||||
:: Hello from Docker!
|
||||
:: This message shows that your installation appears to be working correctly.
|
||||
::
|
||||
:: To generate this message, Docker took the following steps:
|
||||
:: 1. The Docker client contacted the Docker daemon.
|
||||
:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
|
||||
:: (amd64)
|
||||
:: 3. The Docker daemon created a new container from that image which runs the
|
||||
:: executable that produces the output you are currently reading.
|
||||
:: 4. The Docker daemon streamed that output to the Docker client, which sent it
|
||||
:: to your terminal.
|
||||
::
|
||||
:: To try something more ambitious, you can run an Ubuntu container with:
|
||||
:: $ docker run -it ubuntu bash
|
||||
::
|
||||
:: Share images, automate workflows, and more with a free Docker ID:
|
||||
:: https://hub.docker.com/
|
||||
::
|
||||
:: For more examples and ideas, visit:
|
||||
:: https://docs.docker.com/get-started/
|
||||
:: El susodicho mensaje se podría traducir como:
|
||||
::
|
||||
:: Hola desde Docker!
|
||||
:: Este mensaje muestra que su instalación parece estar funcionando crrectamente.
|
||||
::
|
||||
:: Para generar este mensaje, Docker realizó los siguientes pasos:
|
||||
:: 1. El cliente de Docker contactó a Docker daemon.
|
||||
:: 2. El Docker daemon obtubo la imágen "hello-world" desde Docker Hub.
|
||||
:: (amd64)
|
||||
:: 3. El Docker daemon creó un nuevo contenedor a partir de esa imagen con la cual ejecuta el
|
||||
:: ejecutable que produce la salida que estás leyendo.
|
||||
:: 4. El Docker daemon transmitió dicha salida el cliente Docker, el cual
|
||||
:: la envió a tu terminal.
|
||||
::
|
||||
:: Para intentar algo más ambicioso, puede correr un contenedor Ubuntu mediante:
|
||||
:: $ docker run -it ubuntu bash
|
||||
::
|
||||
:: Comparte imágenes, automatice flujos y más con un Docker ID gratuito:
|
||||
:: https://hub.docker.com/
|
||||
|
||||
:: ahora veamos las imágenes que se están ejecutando actualmente
|
||||
docker ps
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
:: NAMES
|
||||
|
||||
:: veamos las imágenes que hemos ejecutado previamente
|
||||
docker ps -a
|
||||
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
:: NAMES
|
||||
:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago
|
||||
:: happy_poincare
|
||||
:: la parte del nombre se genera automáticamente, así que probablemente sea diferente para vos
|
||||
|
||||
:: eliminemos nuestra imagen previamente generada
|
||||
docker rm happy_poincare
|
||||
|
||||
:: verifiquemos si realmente fue borrada
|
||||
docker ps -a
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
:: NAMES
|
||||
|
||||
:: especifiquemos un nombre personalizado para el contenedor
|
||||
docker run --name test_container hello-world
|
||||
:: Hello from Docker!
|
||||
:: This message shows that your installation appears to be working correctly.
|
||||
::
|
||||
:: To generate this message, Docker took the following steps:
|
||||
:: 1. The Docker client contacted the Docker daemon.
|
||||
:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
|
||||
:: (amd64)
|
||||
:: 3. The Docker daemon created a new container from that image which runs the
|
||||
:: executable that produces the output you are currently reading.
|
||||
:: 4. The Docker daemon streamed that output to the Docker client, which sent it
|
||||
:: to your terminal.
|
||||
::
|
||||
:: To try something more ambitious, you can run an Ubuntu container with:
|
||||
:: $ docker run -it ubuntu bash
|
||||
::
|
||||
:: Share images, automate workflows, and more with a free Docker ID:
|
||||
:: https://hub.docker.com/
|
||||
::
|
||||
:: For more examples and ideas, visit:
|
||||
:: https://docs.docker.com/get-started/
|
||||
|
||||
docker ps -a
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
:: NAMES
|
||||
:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago
|
||||
:: test_container
|
||||
:: tal como podeis ver el nombre es el que especificamos
|
||||
|
||||
:: obtener los registros de un contenedor nombrado
|
||||
docker logs test_container
|
||||
:: Hello from Docker!
|
||||
:: This message shows that your installation appears to be working correctly.
|
||||
::
|
||||
:: To generate this message, Docker took the following steps:
|
||||
:: 1. The Docker client contacted the Docker daemon.
|
||||
:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
|
||||
:: (amd64)
|
||||
:: 3. The Docker daemon created a new container from that image which runs the
|
||||
:: executable that produces the output you are currently reading.
|
||||
:: 4. The Docker daemon streamed that output to the Docker client, which sent it
|
||||
:: to your terminal.
|
||||
::
|
||||
:: To try something more ambitious, you can run an Ubuntu container with:
|
||||
:: $ docker run -it ubuntu bash
|
||||
::
|
||||
:: Share images, automate workflows, and more with a free Docker ID:
|
||||
:: https://hub.docker.com/
|
||||
::
|
||||
:: For more examples and ideas, visit:
|
||||
:: https://docs.docker.com/get-started/
|
||||
|
||||
docker rm test_container
|
||||
|
||||
docker run ubuntu
|
||||
:: Unable to find image 'ubuntu:latest' locally
|
||||
:: latest: Pulling from library/ubuntu
|
||||
:: 2746a4a261c9: Pull complete
|
||||
:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4
|
||||
:: Status: Downloaded newer image for ubuntu:latest
|
||||
|
||||
docker ps -a
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
:: NAMES
|
||||
:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago
|
||||
:: relaxed_nobel
|
||||
|
||||
:: ejecutando un contenedor en modo interactivo
|
||||
docker run -it ubuntu
|
||||
:: root@e2cac48323d2:/# uname
|
||||
:: Linux
|
||||
:: root@e2cac48323d2:/# exit
|
||||
:: exit
|
||||
|
||||
docker rm relaxed_nobel
|
||||
|
||||
docker ps -a
|
||||
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
|
||||
:: NAMES
|
||||
:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago
|
||||
:: nifty_goldwasser
|
||||
|
||||
docker rm nifty_goldwasser
|
||||
```
|
@ -31,7 +31,7 @@ esto
|
||||
% Dos símbolos de porcentaje denotan el comienzo de una nueva sección de código.
|
||||
% Secciones de código individuales pueden ser ejecutadas moviendo el cursor hacia la sección,
|
||||
% seguida por un clic en el botón de “Ejecutar Sección”
|
||||
% o usando Ctrl+Shift+Enter (Windows) o Cmd+Shift+Return (OS X)
|
||||
% o usando Ctrl+Shift+Enter (Windows) o Cmd+Shift+Return (macOS)
|
||||
|
||||
%% Este es el comienzo de una sección de código
|
||||
% Una forma de usar las secciones es separar un código de inicio costoso que no cambia, como cargar datos
|
||||
|
@ -9,7 +9,7 @@ translators:
|
||||
lang: es-es
|
||||
filename: LearnObjectiveC-es.m
|
||||
---
|
||||
Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos OS X y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch.
|
||||
Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos macOS y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch.
|
||||
Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk".
|
||||
|
||||
|
||||
|
@ -225,7 +225,7 @@ fn main() {
|
||||
|
||||
// bucles `for`
|
||||
let array = [1, 2, 3];
|
||||
for i in array.iter() {
|
||||
for i in array {
|
||||
println!("{}", i);
|
||||
}
|
||||
|
||||
|
@ -11,7 +11,7 @@ lang: es-es
|
||||
filename: learnswift-es.swift
|
||||
---
|
||||
|
||||
Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado
|
||||
Swift es un lenguaje de programación para el desarrollo en iOS y macOS creado
|
||||
por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra
|
||||
el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia
|
||||
de desarrolladores de Apple.
|
||||
|
@ -12,7 +12,7 @@ TypeScript es un lenguaje cuyo objetivo es facilitar el desarrollo de aplicacion
|
||||
TypeScript añade conceptos comunes como clases, módulos, interfaces, genéricos y (opcionalmente) tipeo estático a JavaScript.
|
||||
Es un superset de JavaScript: todo el código JavaScript es código válido en TypeScript de manera que se puede integrar fácilmente a cualquier proyecto . El compilador TypeScript emite JavaScript.
|
||||
|
||||
Este artículo se enfocará solo en la sintáxis extra de TypeScript, y no en [JavaScript] (../javascript/).
|
||||
Este artículo se enfocará solo en la sintáxis extra de TypeScript, y no en [JavaScript] (../javascript-es/).
|
||||
|
||||
Para probar el compilador de TypeScript, diríjase al [Área de Pruebas] (http://www.typescriptlang.org/Playground) donde podrá tipear código, y ver como se auto-completa al tiempo que ve el código emitido JavaScript.
|
||||
|
||||
|
@ -605,4 +605,4 @@ Something.new.qux # => 'qux'
|
||||
- [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/) - Vanhempi, mutta [ilmainen painos](http://ruby-doc.com/docs/ProgrammingRuby/) on luettavissa netissä
|
||||
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Yhteisön luoma Ruby-tyyliopas
|
||||
- [Try Ruby](http://tryruby.org) - Rubyn perusteet interaktiivisesti
|
||||
- [Try Ruby](https://try.ruby-lang.org/) - Rubyn perusteet interaktiivisesti
|
||||
|
313
fish.html.markdown
Normal file
@ -0,0 +1,313 @@
|
||||
---
|
||||
category: tool
|
||||
tool: fish
|
||||
contributors:
|
||||
- ["MySurmise", "https://github.com/MySurmise"]
|
||||
filename: learn.fish
|
||||
---
|
||||
|
||||
Fish (**f**riendly **i**nteractive **sh**ell) is the name of an exotic shell. That is a shell with a syntax that is derived from neither the Bourne-Shell nor the C-Shell.
|
||||
|
||||
The advantage of fish is that many features that you want in a modern shell come out-of-the-box, so you don't have to install additional software like zsh and oh-my-zsh.
|
||||
|
||||
Examples of these features are autosuggestions, 24-bit colors, Man Page Completions (meaning fish automatically parses your man pages and suggests additional options for your commands) or the ability to make options through a web page (when a GUI is installed).
|
||||
|
||||
It was released in February 2005.
|
||||
|
||||
[Read more](https://fishshell.com/docs/current/language.html)
|
||||
|
||||
[Installation guide](https://github.com/fish-shell/fish-shell#getting-fish)
|
||||
|
||||
|
||||
# Guide
|
||||
|
||||
Be sure you have the newest fish shell. This was made with version 3.3.0. To test, type:
|
||||
> fish -v
|
||||
|
||||
To start the fish shell, type:
|
||||
> fish
|
||||
|
||||
to exit, type:
|
||||
> exit
|
||||
|
||||
or press <kbd>Ctrl + D</kbd>
|
||||
|
||||
Now, right out of the gate, there's one annoying thing in fish. It's the welcome message. Who needs that, right? When your shell is started, just type:
|
||||
> set -U fish_greeting ""
|
||||
|
||||
To set that to the wanted value, .
|
||||
|
||||
|
||||
If you want to execute a single command written in bash, without switching to that shell, you can type:
|
||||
> bash -c 'echo "fish is better than bash"'
|
||||
|
||||
In fish, you can use single or double quotes.
|
||||
The escape character is a `\`
|
||||
|
||||
You can change your configuration of fish either by editing the config file
|
||||
> vim ~/.config/fish/config.fish
|
||||
|
||||
or by opening the aforementioned web settings:
|
||||
|
||||
>fish_config
|
||||
|
||||
Adding something to your fish PATH Variable is easy:
|
||||
> fish_path_add ~/cowsay
|
||||
|
||||
Can you do that with bash, huh? No, you always have to look it up... It's just that easy!
|
||||
|
||||
But there's more. Most fish-specific commands start, you guessed it, with 'fish'. Just type in `fish` and press <kbd>TAB</kbd>. And there you have one of the many cool features of fish: The autocompletion that **just works.**
|
||||
Now you can navigate with <kbd>TAB</kbd>, <kbd>Shift + TAB</kbd> and your Arrow-Keys <kbd>←</kbd><kbd>↑</kbd><kbd>→</kbd><kbd>↓</kbd>.
|
||||
|
||||
To get help, contact your local psychiatrist or type `man`. That will bring up the manual for that command, for example:
|
||||
> man set
|
||||
|
||||
If you finally tried fish, you can see something other in fish that's really cool. Everything has cool colors, if you type in something wrong, it is red, without even executing, if you put something in quotes, you see where it ends and why that quote doesn't work, because there's another qoutation mark in the quote at position 26.
|
||||
|
||||
fish has even more cool things, like wildcards.
|
||||
For example, type
|
||||
> ls *.fish
|
||||
|
||||
That will list all fish files in your current directory.
|
||||
|
||||
You can have multiple wildcards per command or even a recursive wildcard, `**`, which basically means it includes files and directories, that fit.
|
||||
For example the following command would return (in your case):
|
||||
> ls ~/images/**.jpg
|
||||
|
||||
```
|
||||
~/images/nudes/pewdiepie.jpg
|
||||
~/images/nudes/peppa.jpg
|
||||
~/images/screenshots/2020-42-69.jpg
|
||||
~/images/omegalul.jpg
|
||||
```
|
||||
|
||||
Of course, you can also pipe the output of a command to another command
|
||||
|
||||
>echo sick egg, nadia. no u do really goofy shit. | grep [udense]
|
||||
|
||||
write to a file:
|
||||
|
||||
>echo This\ is\ text > file.txt
|
||||
|
||||
(noticed the escape character?)
|
||||
Add to a file:
|
||||
|
||||
>echo This\ is\ a\ line >> file.txt
|
||||
|
||||
>echo This\ is\ a\ second\ line >> file.txt
|
||||
|
||||
For Autocompletion, just always press <kbd>TAB</kbd>. You will be surprised how many things fish knows.
|
||||
|
||||
To use variables, just type `$VAR`, like in bash.
|
||||
|
||||
> echo "My home is $HOME"
|
||||
|
||||
> My home is /home/myuser
|
||||
|
||||
Here comes a difference between single and double quotes. If you use a variable in single quotes, it will not substitute it.
|
||||
|
||||
> echo 'My home is $HOME'
|
||||
|
||||
> My home is $HOME
|
||||
|
||||
More on variables later.
|
||||
|
||||
To execute two commands, separate them with `;`
|
||||
> echo Lol; echo this is fun
|
||||
|
||||
The status code of the last command is stored in `$status`
|
||||
|
||||
You can use && for two commands that depend on each other.
|
||||
|
||||
> set var lol && echo $var
|
||||
|
||||
You can also use and,
|
||||
which executes if the previous command was successful
|
||||
|
||||
or
|
||||
which executes if the previous command was not successful
|
||||
|
||||
and not
|
||||
which inverts the exit status of a command.
|
||||
|
||||
For example:
|
||||
|
||||
|
||||
> if not echo It's very late I should not waste my time with this
|
||||
|
||||
>> echo Nobody heard you
|
||||
|
||||
>end
|
||||
|
||||
(You can of course do all of that in the shell)
|
||||
|
||||
|
||||
---
|
||||
Now let's start with the scripting part of fish.
|
||||
|
||||
As with every shell, you can not only execute commands in the shell, but also as files, saved as a `.fish` file.
|
||||
(You can also execute `.sh` files with fish syntax, but I always use `.fish` for fish-syntax scripts to distinguish them from bash script files)
|
||||
|
||||
```bash
|
||||
# This is a comment in fish.
|
||||
#
|
||||
# If you execute a file without specifying an interpreter,
|
||||
# meaning the software that runs your script, you need to tell the shell,
|
||||
# where that interpreter is.
|
||||
# For fish you just add the following comment as the first line in your script:
|
||||
|
||||
#!/bin/fish
|
||||
|
||||
# When executing via e.g. fish /path/to/script.fish
|
||||
# you don't need that, because you specified fish as an interpreter
|
||||
|
||||
# Let's start with variables.
|
||||
# for use inside a program, you can use the syntax
|
||||
set name = 'My Variable'
|
||||
|
||||
|
||||
# use
|
||||
set -x name value
|
||||
# to eXport
|
||||
set -e name
|
||||
# to Erase
|
||||
|
||||
# a variable set with a space doesn't get sent as two arguments, but as one, as you would expect it.
|
||||
set turtlefolder 'Turtle Folder'
|
||||
mkdir $turtlefolder
|
||||
|
||||
# This will create one folder, as expected, not two, like in bash...
|
||||
# Who would even want that? tHiS iS a fEaTurE, nOt a bUg...
|
||||
|
||||
# you can even have lists as variables. This actually makes sense, because if you want to have a variable that would create two folders, you just give mkdir a list of your foldernames.
|
||||
|
||||
# you can then count the entries in that list with:
|
||||
count $PATH
|
||||
|
||||
# Not only is everything awesome, but in fish, everything is also a list.
|
||||
# So $PWD for example is a list of length 1.
|
||||
# To make a list, just give the set command multiple arguments:
|
||||
set list entry1 entry2 entry3
|
||||
# that way you can also append something to an existing variable:
|
||||
set PATH $PATH ~/cowsay/
|
||||
|
||||
# But, as previously mentioned, we also have a simpler way to do that specifically in fish.
|
||||
# As with every Array/List, you can access it with
|
||||
$listvar[2]
|
||||
# there's also ranges with
|
||||
$listvar[1..5]
|
||||
# and you can use negative numbers like
|
||||
$listvar[-1]
|
||||
# e.g to access the last element.
|
||||
|
||||
|
||||
|
||||
# You can also do fancy cartesian products when you combine two list variables:
|
||||
set a 1 2 3
|
||||
set 1 a b c
|
||||
echo $a$1
|
||||
# Will output : 1a 2a 3a 1b 2b 3b 1c 2c 3c
|
||||
|
||||
# Of course, if you separate them, it will see them as two separate arguments and echo them one after the other. THAT is expected behavior @bash.
|
||||
|
||||
# There are also other useful things, like command substitutions. For example, when you want to output the returns of two commands in one line. In bash you would do that with
|
||||
echo "`ls` is in $PWD"
|
||||
# or
|
||||
echo "$(ls) is in $PWD"
|
||||
|
||||
# if you ask me, that's unnecessary. I always type in the wrong apostrophe. Why not just use two parenthesis, like in fish?
|
||||
echo (ls) is in $PWD
|
||||
|
||||
# Yep, that easy. And thanks to fish's highlighting you can instantly see, if you typed it in correctly.
|
||||
|
||||
# And, as you would expect, if you ask me, your commands don't work in quotes. I mean why bash? Ok I'll stop now. But in fish, just do:
|
||||
echo (ls)" is in $PWD"
|
||||
# or
|
||||
set myvar "The file"(ls -a)" is in the directory $PWD"
|
||||
# will make a List with the string and all files. Try it out. Isn't that cool?
|
||||
|
||||
# And to separate these variables in separate arguments, just put a space between them:
|
||||
|
||||
set myvar "The files" (ls -a) " are in the directory $PWD"
|
||||
|
||||
# There's also if, else if, else
|
||||
if grep fish /etc/shells
|
||||
echo Found fish
|
||||
else if grep bash /etc/shells
|
||||
echo Found bash
|
||||
else
|
||||
echo Got nothing
|
||||
end
|
||||
|
||||
# A little weird is that you compare stuff with one = sign , of course because we don't need it to set variables, but still... and the keyword "test":
|
||||
if test $var = "test"
|
||||
echo yes
|
||||
else
|
||||
echo no
|
||||
end
|
||||
|
||||
# Of course, there's also switch case with
|
||||
switch $OS
|
||||
case Linux
|
||||
echo "you're good"
|
||||
case Windows
|
||||
echo "install Gentoo"
|
||||
case Arch
|
||||
echo "I use arch btw"
|
||||
case '*'
|
||||
echo "what OS is $OS, please?"
|
||||
end
|
||||
|
||||
|
||||
# functions in fish get their arguments through the $argv variable. The syntax is following:
|
||||
|
||||
function print
|
||||
echo $argv
|
||||
end
|
||||
|
||||
# There are also events, like the "fish_exit"-event (What may that be, hmm?).
|
||||
|
||||
# You can use them by adding them to the function definition:
|
||||
|
||||
function on_exit --on-event fish_exit
|
||||
echo fish is now exiting
|
||||
end
|
||||
|
||||
# find events with the command
|
||||
functions --handlers
|
||||
|
||||
|
||||
# You can use the functions command to learn more about, well, functions.
|
||||
# For example you can print the source code of every function:
|
||||
functions cd
|
||||
functions print
|
||||
# or get the names of all functions:
|
||||
functions
|
||||
|
||||
# There's while Loops, of course
|
||||
while test $var = lol
|
||||
echo lol
|
||||
end
|
||||
|
||||
# for Loops (with wildcards, they are even cooler):
|
||||
for image in *.jpg
|
||||
echo $image
|
||||
end
|
||||
|
||||
# there's an equivalent to the range(0, 5) in Python, so you can also do the standard for loops with numbers:
|
||||
|
||||
set files (ls)
|
||||
for number in (seq 10)
|
||||
echo "$files[$number] is file number $number"
|
||||
end
|
||||
|
||||
# Cool!
|
||||
|
||||
# The bashrc equivalent is not fishrc, but the previously mentioned config.fish file in ~/.config/fish/
|
||||
|
||||
# To add a function to fish, though, you should create a simple .fish file in that directory. Don't just paste that function in the config.fish. That's ugly.
|
||||
|
||||
# If you have more, just add it, but those are the most important basics.
|
||||
|
||||
```
|
||||
|
@ -443,6 +443,7 @@ end module fruity
|
||||
For more information on Fortran:
|
||||
|
||||
+ [wikipedia](https://en.wikipedia.org/wiki/Fortran)
|
||||
+ [Fortran-lang Organization](https://fortran-lang.org/)
|
||||
+ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features)
|
||||
+ [fortranwiki.org](http://fortranwiki.org)
|
||||
+ [www.fortran90.org/](http://www.fortran90.org)
|
||||
|
@ -67,21 +67,21 @@ f(n) = 3log n + 100
|
||||
g(n) = log n
|
||||
```
|
||||
|
||||
Est-ce que `f(n)` O(g(n))?
|
||||
Est-ce que `3 log n + 100` O(log n)?
|
||||
Est-ce que `f(n)` est égal à O(g(n))?
|
||||
Est-ce que `3 log n + 100` est égal à O(log n)?
|
||||
Regardons maintenant la définition de Big-O.
|
||||
|
||||
```
|
||||
3log n + 100 <= c * log n
|
||||
```
|
||||
|
||||
Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > <sub>0</sub>?
|
||||
Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > n<sub>0</sub>?
|
||||
|
||||
```
|
||||
3log n + 100 <= 150 * log n, n > 2 (Indéfini avec n = 1)
|
||||
```
|
||||
|
||||
Oui ! La définition de Big-O a été satisfaite, donc `f(n)` is O(g(n)).
|
||||
Oui ! La définition de Big-O a été satisfaite, donc `f(n)` est égal à O(g(n)).
|
||||
|
||||
*Exemple 2*
|
||||
|
||||
@ -90,15 +90,15 @@ f(n) = 3*n^2
|
||||
g(n) = n
|
||||
```
|
||||
|
||||
Est-ce que `f(n)` O(g(n))?
|
||||
Est-ce que `3 * n^2` O(n)?
|
||||
Est-ce que `f(n)` est égal à O(g(n))?
|
||||
Est-ce que `3 * n^2` est égal à O(n)?
|
||||
Regardons de nouveau la définition de Big-O.
|
||||
|
||||
```
|
||||
3 * n^2 <= c * n
|
||||
```
|
||||
|
||||
Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > <sub>0</sub>?
|
||||
Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > n<sub>0</sub>?
|
||||
Non, il n'en existe pas. `f(n)` n'est pas égal à O(g(n)).
|
||||
|
||||
### Big-Omega
|
||||
|
@ -17,7 +17,7 @@ lang: fr-fr
|
||||
---
|
||||
|
||||
Bash est le nom du shell UNIX, qui était aussi distribué avec le système
|
||||
d’exploitation GNU et est le shell par défaut sur Linux et Mac OS X.
|
||||
d’exploitation GNU et est le shell par défaut sur Linux et macOS.
|
||||
|
||||
Presque tous les exemples ci-dessous peuvent être écrits dans un script shell
|
||||
ou exécutés directement dans le terminal.
|
||||
|
@ -31,7 +31,7 @@ Les commentaires sur plusieurs lignes ressemblent à ceci.
|
||||
/**
|
||||
* Les commentaires de la JavaDoc ressemblent à ceci. Ils sont utilisés pour
|
||||
* décrire la classe et ses différents attributs.
|
||||
* Attributs principaux:
|
||||
* Attributs principaux :
|
||||
*
|
||||
* @author Nom (et information de contact comme l'email) de(s) auteur(s).
|
||||
* @version Version actuelle du programme.
|
||||
@ -82,7 +82,7 @@ public class JavaFr {
|
||||
*/
|
||||
|
||||
// Utilisez Scanner pour lire l'entrée
|
||||
// Nécessite: import java.util.Scanner;
|
||||
// Nécessite : import java.util.Scanner;
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
// Lire une chaîne de caractères
|
||||
@ -160,7 +160,7 @@ public class JavaFr {
|
||||
// L est utilisé pour indiquer que la variable est de type long;
|
||||
// le nombre serait traité comme un int sans le L
|
||||
|
||||
// Note: byte, short, int et long sont signés. Ils peuvent avoir des
|
||||
// Note : byte, short, int et long sont signés. Ils peuvent avoir des
|
||||
// valeurs positives et négatives.
|
||||
// Il n'existe pas de variantes non-signées.
|
||||
// char, toutefois, est non-signé sur 16 bits
|
||||
@ -203,7 +203,7 @@ public class JavaFr {
|
||||
|
||||
// BigDecimal - entier immuable et positif de taille arbitraire
|
||||
//
|
||||
// BigDecimal comprend deux parties: une entier de taille arbitraire
|
||||
// BigDecimal comprend deux parties : une entier de taille arbitraire
|
||||
// (BigInteger) et un entier de 32 bits représantant la position de la
|
||||
// virgule.
|
||||
//
|
||||
@ -240,13 +240,13 @@ public class JavaFr {
|
||||
// C'est la manière la plus simple et optimisé par le compilateur
|
||||
String plusConcatenated = "Strings can " + "be concatenated " + "via + operator.";
|
||||
System.out.println(plusConcatenated);
|
||||
// Affiche: Strings can be concatenated via + operator.
|
||||
// Affiche : Strings can be concatenated via + operator.
|
||||
|
||||
// #2 - avec StringBuilder
|
||||
// Cette méthode ne nécessite pas d'objet String intermédiaire. Elle
|
||||
// stocke juste les différentes chaînes de caractères et les assemble
|
||||
// lorsque la méthode toString() est appelée.
|
||||
// Attention: Cette classe n'est pas thread-safe (l'objet ne peut pas être partagé
|
||||
// Attention : Cette classe n'est pas thread-safe (l'objet ne peut pas être partagé
|
||||
// entre les threads). Une alternative
|
||||
// (avec un impact sur les performances) thread-safe est d'utiliser la
|
||||
// classe StringBuffer.
|
||||
@ -255,7 +255,7 @@ public class JavaFr {
|
||||
builderConcatenated.append("can use ");
|
||||
builderConcatenated.append("the StringBuilder class.");
|
||||
System.out.println(builderConcatenated.toString()); // only now is the string built
|
||||
// Affiche: You can use the StringBuilder class.
|
||||
// Affiche : You can use the StringBuilder class.
|
||||
|
||||
// StringBuffer est efficace quand la chaîne de caractères n'est pas
|
||||
// utilisée avec la fin de sa construction.
|
||||
@ -276,7 +276,7 @@ public class JavaFr {
|
||||
// #3 - avec la méthode format() de la classe String.
|
||||
// Une autre alternative. Rapide et lisible.
|
||||
String.format("%s may prefer %s.", "Or you", "String.format()");
|
||||
// Affiche: Or you may prefer String.format().
|
||||
// Affiche : Or you may prefer String.format().
|
||||
|
||||
// Tableau
|
||||
// La taille du tableau doit être précisée à l'instantiation
|
||||
@ -419,7 +419,7 @@ public class JavaFr {
|
||||
System.out.println("fooFor Value: " + fooFor);
|
||||
|
||||
// Fin d'une boucle for avec un label
|
||||
outer:
|
||||
outer :
|
||||
for (int i = 0; i < 10; i++) {
|
||||
for (int j = 0; j < 10; j++) {
|
||||
if (i == 5 && j ==5) {
|
||||
@ -433,9 +433,9 @@ public class JavaFr {
|
||||
// La boucle for est également capable d'itérer aussi bien sur un
|
||||
// tableau que sur des objets qui implémentent l'interface Iterable.
|
||||
int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||
// De la forme: for (<object> : <iterable>)
|
||||
// Lu comme: "Pour chaque élément du tableau"
|
||||
// note: le type doit correspondre à celui de l'objet itérable
|
||||
// De la forme : for (<object> : <iterable>)
|
||||
// Lu comme : "Pour chaque élément du tableau"
|
||||
// note : le type doit correspondre à celui de l'objet itérable
|
||||
for (int bar : fooList) {
|
||||
System.out.println(bar);
|
||||
//Itère 9 fois et affiche les chiffres de 1 à 9
|
||||
@ -511,7 +511,7 @@ public class JavaFr {
|
||||
// Convert Integer To String
|
||||
Integer.toString(123); // retourne un object String correspondant à"123"
|
||||
|
||||
// Pour les autres conversions, référer vous aux classes suivantes:
|
||||
// Pour les autres conversions, référer vous aux classes suivantes :
|
||||
// Double
|
||||
// Long
|
||||
// String
|
||||
@ -537,7 +537,7 @@ public class JavaFr {
|
||||
|
||||
// Initialisation avec double accolades
|
||||
// Le langage Java ne permet pas de créer des collections statiques d'une
|
||||
// manière simple. Généralement, on utilise la forme suivante:
|
||||
// manière simple. Généralement, on utilise la forme suivante :
|
||||
private static final Set<String> COUNTRIES = new HashSet<String>();
|
||||
static {
|
||||
COUNTRIES.add("DENMARK");
|
||||
@ -566,7 +566,7 @@ public class JavaFr {
|
||||
// Cependant, il est préférable de séparer les
|
||||
// classes dans des fichiers différents.
|
||||
|
||||
// Syntaxe de déclaration des classes:
|
||||
// Syntaxe de déclaration des classes :
|
||||
// <public/private/protected> class <Nom de la classe> {
|
||||
// // Les attributs, les constructeurs et les méthodes de la classe vont ici.
|
||||
// // Les functions de classes sont appelées méthode.
|
||||
@ -575,11 +575,11 @@ public class JavaFr {
|
||||
class Bicycle {
|
||||
|
||||
// Attributs et variables de la classe Bicycle
|
||||
public int cadence; // Public: Peut être accesible depuis n'importe où
|
||||
private int speed; // Private: Accisible depuis la classe
|
||||
protected int gear; // Protected: Accisible depuis la classe et ses sous-
|
||||
public int cadence; // Public : Peut être accesible depuis n'importe où
|
||||
private int speed; // Private : Accisible depuis la classe
|
||||
protected int gear; // Protected : Accisible depuis la classe et ses sous-
|
||||
// classes
|
||||
String name; // default: Uniquement accesible depuis ce package
|
||||
String name; // default : Uniquement accesible depuis ce package
|
||||
static String className; // Variable de classe static
|
||||
|
||||
// Bloc static
|
||||
@ -595,7 +595,7 @@ class Bicycle {
|
||||
// Ceci est le constructeur de la classe Bicycle
|
||||
public Bicycle() {
|
||||
// Vous pouvez aussie appeler un autre constructeur. Par exemple en
|
||||
// appelant le constructeur de la classe mère (voir héritage):
|
||||
// appelant le constructeur de la classe mère (voir héritage) :
|
||||
// this(1, 50, 5, "Bontrager");
|
||||
gear = 1;
|
||||
cadence = 50;
|
||||
@ -665,7 +665,7 @@ class PennyFarthing extends Bicycle {
|
||||
// Ici nous modifions la méthode setGear() de la classe mère. Il faut donc
|
||||
// utiliser l'annotation @Overide. Pour en savoir plus sur les annotations,
|
||||
// consulter la documention officiel (en anglais) :
|
||||
// out: http://docs.oracle.com/javase/tutorial/java/annotations/
|
||||
// out : http://docs.oracle.com/javase/tutorial/java/annotations/
|
||||
@Override
|
||||
public void setGear(int gear) {
|
||||
this.gear = 0;
|
||||
@ -719,7 +719,7 @@ public class Fruit implements Edible, Digestible {
|
||||
}
|
||||
|
||||
// En Java, on peut hériter uniquement d'une classe mais on peut implémenter
|
||||
// plusieurs interfaces:
|
||||
// plusieurs interfaces :
|
||||
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
||||
InterfaceTwo {
|
||||
@Override
|
||||
@ -734,7 +734,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
||||
|
||||
// Classes abstraites
|
||||
|
||||
// Syntaxe de déclaration:
|
||||
// Syntaxe de déclaration :
|
||||
// <niveau d'accès> abstract class <nom de la classe abstraite> extends <nom de la
|
||||
// classe mère abstraite> {
|
||||
// // Constantes et variables
|
||||
@ -758,7 +758,7 @@ public abstract class Animal
|
||||
public void eat()
|
||||
{
|
||||
System.out.println("I am an animal and I am Eating.");
|
||||
// Note: On peut accéder à une variable privée ici.
|
||||
// Note : On peut accéder à une variable privée ici.
|
||||
age = 30;
|
||||
}
|
||||
|
||||
@ -790,7 +790,7 @@ class Dog extends Animal
|
||||
// age = 30; ==> ERREUR! age est privé et n'est pas accesible.
|
||||
}
|
||||
|
||||
// NOTE: Vous obtiendrez une erreur si vous utilisé l'annotation @Override
|
||||
// NOTE : Vous obtiendrez une erreur si vous utilisé l'annotation @Override
|
||||
// ici car Java n'autorise pas la surcharge de méthodes statiques. Ce qui ce
|
||||
// passe est appelé "method hiding". Si vous voulez en savoir plus,
|
||||
// consultez cette discussion (en anglais) :
|
||||
@ -828,7 +828,7 @@ public final class SaberToothedCat extends Animal
|
||||
// Méthodes final
|
||||
public abstract class Mammal()
|
||||
{
|
||||
// Syntaxe:
|
||||
// Syntaxe :
|
||||
// <niveau d'accès> final <type de retour> <nom de la fonction>(<arguments>)
|
||||
|
||||
// Les méthodes déclarées comme final ne peuvent pas être surchargées par
|
||||
@ -846,13 +846,13 @@ public abstract class Mammal()
|
||||
// des valeurs pédéfinies pour celle-ci. En Java, les variables constantes sont
|
||||
// notées en majuscules.
|
||||
// On définie un type enum en utilisant le mot clé enum. Par exemple pour les
|
||||
// jours de l'année:
|
||||
// jours de la semaine :
|
||||
public enum Day {
|
||||
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
|
||||
THURSDAY, FRIDAY, SATURDAY
|
||||
}
|
||||
|
||||
// On l'utilise ainsi:
|
||||
// On l'utilise ainsi :
|
||||
public class EnumTest {
|
||||
// On utilise notre énumération
|
||||
Day day;
|
||||
@ -889,7 +889,7 @@ public class EnumTest {
|
||||
|
||||
// Le type enum permet de faire bien plus que ce qui est montré ici. Il ne se
|
||||
// limite pas à une liste de constante mais peut inclure des champs et méthodes.
|
||||
// Vous pouvez en savoir plus ici (en anglais):
|
||||
// Vous pouvez en savoir plus ici (en anglais) :
|
||||
//https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
|
||||
|
||||
```
|
||||
@ -899,7 +899,7 @@ public class EnumTest {
|
||||
Les liens ci-dessous sont données si vous souhaitez approfondir sur le sujet,
|
||||
n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
|
||||
|
||||
**Guides officiels d'Oracle**:
|
||||
**Guides officiels d'Oracle** :
|
||||
|
||||
* [Java Tutorial Trail from Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html)
|
||||
|
||||
@ -918,7 +918,7 @@ n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
|
||||
|
||||
* [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
|
||||
|
||||
* Nouvelles fonctionnalités Java 8:
|
||||
* Nouvelles fonctionnalités Java 8 :
|
||||
* [Lambda expressions (functional programming)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)
|
||||
* [Date and time API (java.time package)](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html)
|
||||
|
||||
@ -928,7 +928,7 @@ n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
|
||||
|
||||
* [Codingbat.com](http://codingbat.com/java)
|
||||
|
||||
**Livres**:
|
||||
**Livres** :
|
||||
|
||||
* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
|
||||
|
||||
|
@ -10,7 +10,7 @@ filename: LearnObjectiveC-fr.m
|
||||
lang: fr-fr
|
||||
---
|
||||
|
||||
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
|
||||
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations macOS et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
|
||||
|
||||
```objective-c
|
||||
// Les commentaires sur une seule ligne commencent par //
|
||||
@ -30,7 +30,7 @@ ceci
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MaClasse.h"
|
||||
|
||||
// Si vous activez les modules dans les projets iOS >= 7 ou Mac OS X >= 10.9
|
||||
// Si vous activez les modules dans les projets iOS >= 7 ou OS X >= 10.9
|
||||
// dans Xcode 5, vous pouvez importer les frameworks comme cela :
|
||||
@import Foundation;
|
||||
|
||||
|
@ -221,7 +221,7 @@ fn main() {
|
||||
|
||||
// `for` boucles / itération
|
||||
let array = [1, 2, 3];
|
||||
for i in array.iter() {
|
||||
for i in array {
|
||||
println!("{}", i);
|
||||
}
|
||||
|
||||
|
134
fr-fr/set-theory-fr.html.markdown
Normal file
@ -0,0 +1,134 @@
|
||||
```
|
||||
---
|
||||
category: tool
|
||||
lang: fr-fr
|
||||
name: Set theory
|
||||
contributors:
|
||||
- ["kieutrang", "https://github.com/kieutrang1729"]
|
||||
---
|
||||
La théorie des ensembles est une branche des mathématiques qui étudie les ensembles, leurs opérations et leurs propriétés.
|
||||
|
||||
* Un ensemble est une collection d'éléments disjoints.
|
||||
|
||||
## Symboles de base
|
||||
|
||||
### Opérateurs
|
||||
* l'opérateur réunion, `∪`, signifie "ou" ;
|
||||
* l'opérateur intersection, `∩`, signifie "et" ;
|
||||
* l'opérateur différence, `\`, signifie "sans", (lire "A moins B") ;
|
||||
* l'opérateur complémentaire, `'`, signifie "le complémentaire de" ;
|
||||
* l'opérateur croix, `×`, signifie "le produit cartésien de".
|
||||
|
||||
### Autres symboles
|
||||
* le symbole deux-points, `:`, signifie "tel que" ;
|
||||
* le symbole d'appartenance, `∈`, signifie "appartient à" ;
|
||||
* le symbole sous-ensemble, `⊆`, signifie "est un sous-ensemble de" ;
|
||||
* le symbole sous-ensemble propre, `⊂`, signifie "est un sous-ensemble de mais n'est pas égal à".
|
||||
|
||||
### Ensembles importants
|
||||
* `∅`, l'ensemble vide, c'est-à-dire l'ensemble ne contenant aucun élément ;
|
||||
* `ℕ`, l'ensemble des nombres naturels ;
|
||||
* `ℤ`, l'ensemble des entiers ;
|
||||
* `ℚ`, l'ensemble des nombres rationnels ;
|
||||
* `ℝ`, l'ensemble des nombres réels.
|
||||
|
||||
Quelques mise en gardes sur les ensembles definis ci-dessus:
|
||||
1. Même si l'ensemble vide ne contient aucun élément, il est lui-même un sous-ensemble de n'importe quel ensemble.
|
||||
2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitment si l'auteur considère le zéro comme nombre naturel ou pas.
|
||||
|
||||
|
||||
### Cardinalité
|
||||
|
||||
La cardinalité, ou taille, d'un ensemble est déterminée par le nombre d'éléments dans l'ensemble. L'opérateur de cardinalité s'écrit, `| ... |`.
|
||||
Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`.
|
||||
|
||||
### L'ensemble vide
|
||||
* L'ensemble vide peut se définir en comprehension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`.
|
||||
* il n'y a qu'un seul ensemble vide.
|
||||
* l'ensemble vide est sous-ensemble de tout ensemble.
|
||||
* la cardinalité de l'ensemble vide est 0, ou `|∅| = 0`.
|
||||
|
||||
## Notation ensembliste
|
||||
|
||||
### Définition par extension
|
||||
|
||||
Un ensemble peut être defini en extension par une liste de tous les éléments qui sont contenus dans l'ensemble. Par exemple, `S = { a, b, c, d }`.
|
||||
|
||||
Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatres premiers.
|
||||
|
||||
### Définition par comprehension
|
||||
|
||||
C'est une notation plus descriptif qui permet de définir un ensemble à l'aide d'un sujet et d'une propriété, et il est noté `S = { sujet : propriété }`. Par exemple,
|
||||
|
||||
```
|
||||
A = { x : x est une voyelle } = { a, e, i, o, u, y}
|
||||
B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
|
||||
C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
|
||||
```
|
||||
|
||||
On peut même appliquer une fonction au sujet, e.g.
|
||||
|
||||
```
|
||||
D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
|
||||
```
|
||||
|
||||
## Relations
|
||||
|
||||
### Appartenance
|
||||
|
||||
* Si l'élement `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`.
|
||||
* Si l'élement `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`.
|
||||
|
||||
### Égalité
|
||||
|
||||
* On dit que deux ensembles `A` et `B` sont égaux s'ils contiennent les mêmes éléments, et on le note `A = B`.
|
||||
* Les ensembles n'ont pas de notion d'ordre, par exemple `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`.
|
||||
* Un élément ne peut apparaître qu'au plus une seule fois - il n'y a jamais de répétition, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`.
|
||||
* Deux ensembles `A` and `B` sont égaux si et seulement si `A ⊆ B` and `B ⊆ A`.
|
||||
|
||||
## Ensemble puissance
|
||||
* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité d'`A` est `n`, la cardinalité de `P(A)` est `2^n`.
|
||||
|
||||
```
|
||||
P(A) = { x : x ⊆ A }
|
||||
```
|
||||
|
||||
## Opérations ensemblistes
|
||||
### Réunion
|
||||
La réunion de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments qui appartient à `A` ou à `B`.
|
||||
|
||||
```
|
||||
A ∪ B = { x : x ∈ A ∪ x ∈ B }
|
||||
```
|
||||
|
||||
### Intersection
|
||||
L'intersection de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments qui appartient à la fois à `A` et à `B`.
|
||||
|
||||
```
|
||||
A ∩ B = { x : x ∈ A, x ∈ B }
|
||||
```
|
||||
|
||||
### Différence
|
||||
La différence de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments de l'ensemble `A` qui n'appartient pas à `B`.
|
||||
|
||||
```
|
||||
A \ B = { x : x ∈ A, x ∉ B }
|
||||
```
|
||||
|
||||
### Différence symétrique
|
||||
Le différence symétrique de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments de `A` et `B` qui n'apparaissent pas dans leur intersection.
|
||||
|
||||
```
|
||||
A △ B = { x : ((x ∈ A) ∩ (x ∉ B)) ∪ ((x ∈ B) ∩ (x ∉ A)) }
|
||||
|
||||
A △ B = (A \ B) ∪ (B \ A)
|
||||
```
|
||||
|
||||
### Produit cartésien
|
||||
Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous les couples dont la première élément appartient à `A` et la deuxième à `B`.
|
||||
|
||||
```
|
||||
A × B = { (x, y) | x ∈ A, y ∈ B }
|
||||
```
|
||||
|
||||
```
|
@ -12,7 +12,7 @@ TypeScript est un langage visant à faciliter le développement d'applications l
|
||||
TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionnel) à JavaScript.
|
||||
C'est une surcouche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur.
|
||||
|
||||
Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/).
|
||||
Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript-fr/).
|
||||
|
||||
Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et accéder directement au rendu JavaScript.
|
||||
|
||||
|
322
gdscript.html.markdown
Normal file
@ -0,0 +1,322 @@
|
||||
---
|
||||
language: GDScript
|
||||
contributors:
|
||||
- ["Wichamir", "https://github.com/Wichamir/"]
|
||||
filename: learngdscript.gd
|
||||
---
|
||||
|
||||
GDScript is a dynamically typed scripting language made specifically for
|
||||
free and open source game engine Godot. GDScript's syntax is similar to
|
||||
Python's. Its main advantages are ease of use and tight integration with
|
||||
the engine. It's a perfect fit for game development.
|
||||
|
||||
## Basics
|
||||
|
||||
```nim
|
||||
# Single-line comments are written using hash symbol.
|
||||
"""
|
||||
Multi-line
|
||||
comments
|
||||
are
|
||||
written
|
||||
using
|
||||
docstrings.
|
||||
"""
|
||||
|
||||
# Script file is a class in itself and you can optionally define a name for it.
|
||||
class_name MyClass
|
||||
|
||||
# Inheritance
|
||||
extends Node2D
|
||||
|
||||
# Member variables
|
||||
var x = 8 # int
|
||||
var y = 1.2 # float
|
||||
var b = true # bool
|
||||
var s = "Hello World!" # String
|
||||
var a = [1, false, "brown fox"] # Array - similar to list in Python,
|
||||
# it can hold different types
|
||||
# of variables at once.
|
||||
var d = {
|
||||
"key" : "value",
|
||||
42 : true
|
||||
} # Dictionary holds key-value pairs.
|
||||
var p_arr = PoolStringArray(["Hi", "there", "!"]) # Pool arrays can
|
||||
# only hold a certain type.
|
||||
|
||||
# Built-in vector types:
|
||||
var v2 = Vector2(1, 2)
|
||||
var v3 = Vector3(1, 2, 3)
|
||||
|
||||
# Constants
|
||||
const ANSWER_TO_EVERYTHING = 42
|
||||
const BREAKFAST = "Spam and eggs!"
|
||||
|
||||
# Enums
|
||||
enum { ZERO, ONE , TWO, THREE }
|
||||
enum NamedEnum { ONE = 1, TWO, THREE }
|
||||
|
||||
# Exported variables are visible in the inspector.
|
||||
export(int) var age
|
||||
export(float) var height
|
||||
export var person_name = "Bob" # Export type hints are unnecessary
|
||||
# if you set a default value.
|
||||
|
||||
# Functions
|
||||
func foo():
|
||||
pass # pass keyword is a placeholder for future code
|
||||
|
||||
func add(first, second):
|
||||
return first + second
|
||||
|
||||
# Printing values
|
||||
func printing():
|
||||
print("GDScript ", "is ", " awesome.")
|
||||
prints("These", "words", "are", "divided", "by", "spaces.")
|
||||
printt("These", "words", "are", "divided", "by", "tabs.")
|
||||
printraw("This gets printed to system console.")
|
||||
|
||||
# Math
|
||||
func doing_math():
|
||||
var first = 8
|
||||
var second = 4
|
||||
print(first + second) # 12
|
||||
print(first - second) # 4
|
||||
print(first * second) # 32
|
||||
print(first / second) # 2
|
||||
print(first % second) # 0
|
||||
# There are also +=, -=, *=, /=, %= etc.,
|
||||
# however no ++ or -- operators.
|
||||
print(pow(first, 2)) # 64
|
||||
print(sqrt(second)) # 2
|
||||
printt(PI, TAU, INF, NAN) # built-in constants
|
||||
|
||||
# Control flow
|
||||
func control_flow():
|
||||
x = 8
|
||||
y = 2 # y was originally a float,
|
||||
# but we can change it's type to int
|
||||
# using the power of dynamic typing!
|
||||
|
||||
if x < y:
|
||||
print("x is smaller than y")
|
||||
elif x > y:
|
||||
print("x is bigger than y")
|
||||
else:
|
||||
print("x and y are equal")
|
||||
|
||||
var a = true
|
||||
var b = false
|
||||
var c = false
|
||||
if a and b or not c: # alternatively you can use &&, || and !
|
||||
print("This is true!")
|
||||
|
||||
for i in range(20): # GDScript's range is similar to Python's
|
||||
print(i) # so this will print numbers from 0 to 19
|
||||
|
||||
for i in ["two", 3, 1.0]: # iterating over an array
|
||||
print(i)
|
||||
|
||||
while x > y:
|
||||
printt(x, y)
|
||||
y += 1
|
||||
|
||||
x = 2
|
||||
y = 10
|
||||
while x < y:
|
||||
x += 1
|
||||
if x == 6:
|
||||
continue # 6 won't get printed because of continue statement
|
||||
prints("x is equal to:", x)
|
||||
if x == 7:
|
||||
break # loop will break on 7, so 8, 9 and 10 won't get printed
|
||||
|
||||
match x:
|
||||
1:
|
||||
print("Match is similar to switch.")
|
||||
2:
|
||||
print("However you don't need to put cases before each value.")
|
||||
3:
|
||||
print("Furthermore each case breaks on default.")
|
||||
break # ERROR! Break statement is unnecessary!
|
||||
4:
|
||||
print("If you need fallthrough use continue.")
|
||||
continue
|
||||
_:
|
||||
print("Underscore is a default case.")
|
||||
|
||||
# ternary operator (one line if-else statement)
|
||||
prints("x is", "positive" if x >= 0 else "negative")
|
||||
|
||||
# Casting
|
||||
func casting_examples():
|
||||
var i = 42
|
||||
var f = float(42) # cast using variables constructor
|
||||
var b = i as bool # or using "as" keyword
|
||||
|
||||
# Override functions
|
||||
# By a convention built-in overridable functions start with an underscore,
|
||||
# but in practice you can override virtually any function.
|
||||
|
||||
# _init is called when object gets initialized
|
||||
# This is the object's constructor.
|
||||
func _init():
|
||||
# Initialize object's internal stuff here.
|
||||
pass
|
||||
|
||||
# _ready gets called when script's node and
|
||||
# its children have entered the scene tree.
|
||||
func _ready():
|
||||
pass
|
||||
|
||||
# _process gets called on every frame.
|
||||
func _process(delta):
|
||||
# The delta argument passed to this function is a number of seconds,
|
||||
# which passed between the last frame and the current one.
|
||||
print("Delta time equals: ", delta)
|
||||
|
||||
# _physics_process gets called on every physics frame.
|
||||
# That means delta should be constant.
|
||||
func _physics_process(delta):
|
||||
# Simple movement using vector addition and multiplication.
|
||||
var direction = Vector2(1, 0) # or Vector2.RIGHT
|
||||
var speed = 100.0
|
||||
self.global_position += direction * speed * delta
|
||||
# self refers to current class instance
|
||||
|
||||
# When overriding you can call parent's function using the dot operator
|
||||
# like here:
|
||||
func get_children():
|
||||
# Do some additional things here.
|
||||
var r = .get_children() # call parent's implementation
|
||||
return r
|
||||
|
||||
# Inner class
|
||||
class InnerClass:
|
||||
extends Object
|
||||
|
||||
func hello():
|
||||
print("Hello from inner class!")
|
||||
|
||||
func use_inner_class():
|
||||
var ic = InnerClass.new()
|
||||
ic.hello()
|
||||
ic.free() # use free for memory cleanup
|
||||
```
|
||||
|
||||
## Accessing other nodes in the scene tree
|
||||
|
||||
```nim
|
||||
extends Node2D
|
||||
|
||||
var sprite # This variable will hold the reference.
|
||||
|
||||
# You can get references to other nodes in _ready.
|
||||
func _ready() -> void:
|
||||
# NodePath is useful for accessing nodes.
|
||||
# Create NodePath by passing String to its constructor:
|
||||
var path1 = NodePath("path/to/something")
|
||||
# Or by using NodePath literal:
|
||||
var path2 = @"path/to/something"
|
||||
# NodePath examples:
|
||||
var path3 = @"Sprite" # relative path, immediate child of the current node
|
||||
var path4 = @"Timers/Firerate" # relative path, child of the child
|
||||
var path5 = @".." # current node's parent
|
||||
var path6 = @"../Enemy" # current node's sibling
|
||||
var path7 = @"/root" # absolute path, equivalent to get_tree().get_root()
|
||||
var path8 = @"/root/Main/Player/Sprite" # absolute path to Player's Sprite
|
||||
var path9 = @"Timers/Firerate:wait_time" # accessing properties
|
||||
var path10 = @"Player:position:x" # accessing subproperties
|
||||
|
||||
# Finally, to get a reference use one of these:
|
||||
sprite = get_node(@"Sprite") as Sprite # always cast to the type you expect
|
||||
sprite = get_node("Sprite") as Sprite # here String gets
|
||||
# implicitly casted to NodePath
|
||||
sprite = get_node(path3) as Sprite
|
||||
sprite = get_node_or_null("Sprite") as Sprite
|
||||
sprite = $Sprite as Sprite
|
||||
|
||||
func _process(delta):
|
||||
# Now we can reuse the reference in other places.
|
||||
prints("Sprite has global_position of", sprite.global_position)
|
||||
|
||||
# Use onready keyword to assign a value to
|
||||
# a variable just before _ready executes.
|
||||
# This is a commonly used syntax sugar.
|
||||
onready var tween = $Tween as Tween
|
||||
|
||||
# You can export NodePath, so you can assign it within the inspector.
|
||||
export var nodepath = @""
|
||||
onready var reference = get_node(nodepath) as Node
|
||||
```
|
||||
|
||||
## Signals
|
||||
|
||||
Signal system is Godot's implementation of the observer programming
|
||||
pattern. Here's an example:
|
||||
|
||||
```nim
|
||||
class_name Player extends Node2D
|
||||
|
||||
var hp = 10
|
||||
|
||||
signal died() # define signal
|
||||
signal hurt(hp_old, hp_new) # signals can take arguments
|
||||
|
||||
func apply_damage(dmg):
|
||||
var hp_old = hp
|
||||
hp -= dmg
|
||||
emit_signal("hurt", hp_old, hp) # emit signal and pass arguments
|
||||
if hp <= 0:
|
||||
emit_signal("died")
|
||||
|
||||
func _ready():
|
||||
# connect signal "died" to function "_on_death" defined in self
|
||||
self.connect("died", self, "_on_death")
|
||||
|
||||
func _on_death():
|
||||
self.queue_free() # destroy Player on death
|
||||
```
|
||||
|
||||
## Type hints
|
||||
|
||||
GDScript can optionally use static typing.
|
||||
|
||||
```nim
|
||||
extends Node
|
||||
|
||||
var x: int # define typed variable
|
||||
var y: float = 4.2
|
||||
var z := 1.0 # infer type based on default value using := operator
|
||||
|
||||
onready var node_ref_typed := $Child as Node
|
||||
|
||||
export var speed := 50.0
|
||||
|
||||
const CONSTANT := "Typed constant."
|
||||
|
||||
func _ready() -> void:
|
||||
# function returns nothing
|
||||
x = "string" # ERROR! Type can't be changed!
|
||||
return
|
||||
|
||||
func join(arg1: String, arg2: String) -> String:
|
||||
# function takes two Strings and returns a String
|
||||
return arg1 + arg2
|
||||
|
||||
func get_child_at(index: int) -> Node:
|
||||
# function takes an int and returns a Node
|
||||
return get_children()[index]
|
||||
|
||||
signal example(arg: int) # ERROR! Signals can't take typed arguments!
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
|
||||
* [Godot's Website](https://godotengine.org/)
|
||||
* [Godot Docs](https://docs.godotengine.org/en/stable/)
|
||||
* [Getting started with GDScript](https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/index.html)
|
||||
* [NodePath](https://docs.godotengine.org/en/stable/classes/class_nodepath.html)
|
||||
* [Signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html)
|
||||
* [GDQuest](https://www.gdquest.com/)
|
||||
* [GDScript.com](https://gdscript.com/)
|
@ -179,7 +179,7 @@ func learnNamedReturns(x, y int) (z int) {
|
||||
|
||||
// Go is fully garbage collected. It has pointers but no pointer arithmetic.
|
||||
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
|
||||
// Unlike in C/Cpp taking and returning an address of a local varible is also safe.
|
||||
// Unlike in C/Cpp taking and returning an address of a local variable is also safe.
|
||||
func learnMemory() (p, q *int) {
|
||||
// Named return values p and q have type pointer to int.
|
||||
p = new(int) // Built-in function new allocates memory.
|
||||
@ -190,6 +190,7 @@ func learnMemory() (p, q *int) {
|
||||
return &s[3], &r // & takes the address of an object.
|
||||
}
|
||||
|
||||
// Use the aliased math library (see imports, above)
|
||||
func expensiveComputation() float64 {
|
||||
return m.Exp(10)
|
||||
}
|
||||
@ -474,8 +475,9 @@ documentation](http://golang.org/pkg/) and the source code comes up!
|
||||
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
|
||||
|
||||
There are many excellent conference talks and video tutorials on Go available on YouTube, and here are three playlists of the very best, tailored for beginners, intermediate, and advanced Gophers respectively:
|
||||
* [Golang University 101](https://www.youtube.com/playlist?list=PLEcwzBXTPUE9V1o8mZdC9tNnRZaTgI-1P) introduces fundamental Go concepts and shows you how to use the Go tools to create and manage Go code
|
||||
* [Golang University 201](https://www.youtube.com/playlist?list=PLEcwzBXTPUE_5m_JaMXmGEFgduH8EsuTs) steps it up a notch, explaining important techniques like testing, web services, and APIs
|
||||
* [Golang University 301](https://www.youtube.com/watch?v=YHRO5WQGh0k&list=PLEcwzBXTPUE8KvXRFmmfPEUmKoy9LfmAf) dives into more advanced topics like the Go scheduler, implementation of maps and channels, and optimisation techniques
|
||||
|
||||
- [Golang University 101](https://www.youtube.com/playlist?list=PLEcwzBXTPUE9V1o8mZdC9tNnRZaTgI-1P) introduces fundamental Go concepts and shows you how to use the Go tools to create and manage Go code
|
||||
- [Golang University 201](https://www.youtube.com/playlist?list=PLEcwzBXTPUE_5m_JaMXmGEFgduH8EsuTs) steps it up a notch, explaining important techniques like testing, web services, and APIs
|
||||
- [Golang University 301](https://www.youtube.com/playlist?list=PLEcwzBXTPUE8KvXRFmmfPEUmKoy9LfmAf) dives into more advanced topics like the Go scheduler, implementation of maps and channels, and optimisation techniques
|
||||
|
||||
Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information.
|
||||
|
@ -41,6 +41,8 @@ False
|
||||
-- Boolean operations
|
||||
not True -- False
|
||||
not False -- True
|
||||
True && False -- False
|
||||
True || False -- True
|
||||
1 == 1 -- True
|
||||
1 /= 1 -- False
|
||||
1 < 10 -- True
|
||||
|
86
hd-hd/json-hd.html.markdown
Normal file
@ -0,0 +1,86 @@
|
||||
---
|
||||
language: json
|
||||
contributors:
|
||||
- ["Anna Harren", "https://github.com/iirelu"]
|
||||
- ["Marco Scannadinari", "https://github.com/marcoms"]
|
||||
- ["himanshu", "https://github.com/himanshu81494"]
|
||||
- ["Michael Neth", "https://github.com/infernocloud"]
|
||||
- ["Athanasios Emmanouilidis", "https://github.com/athanasiosem"]
|
||||
translators:
|
||||
- ["Namami Shanker", "https://github.com/NamamiShanker"]
|
||||
lang: hd-hd
|
||||
---
|
||||
|
||||
जैसन(JSON) इस अत्यंत सरल डाटा-इंटरचेंज फॉर्मेट है| जैसा [json.org](https://json.org) कहती है, ये इंसानो के पढ़ने और लिखने के लिए भी आसान है और और मशीन के लिए इसे पार्स और उतपन्न करना भी बेहद सरल है|
|
||||
|
||||
जैसन(JSON) के एक अंश को इनमे से किसी एक का प्रतिनिधित्व(represent) करना चाहिए:
|
||||
|
||||
* एक नाम/वैल्यू जोड़े का कलेक्शन (`{ }`). कई दूसरी भाषाओ में इसे ऑब्जेक्ट, रिकॉर्ड, स्ट्रक्ट, डिक्शनरी, हैश टेबल, कीड लिस्ट, या असोसिएटिव ऐरे का भी नाम दिया जाता है|
|
||||
* वैल्यूज की एक व्यवस्थित लिस्ट(ordered list) (`[ ]`). कई दूसरी भाषाओ में इसे ऐरे, वेक्टर, लिस्ट, या सीक्वेंस भी कहा जाता है|
|
||||
|
||||
जैसन(JSON) अपने शुद्धतम रूप में कमैंट्स सपोर्ट नहीं करता है, पर ज़्यादातर पारसर C स्टाइल की कमैंट्स (`//`, `/* */`) सपोर्ट करेंगे| कुछ पारसर्स अंतिम कॉमा भी स्वीकार करते हैं (जब आप किसी ऐरे के अंतिम एलिमेंट या किसी ऑब्जेक्ट की अंतिम प्रॉपर्टी के बार एक कॉमा छोड़ देते हैं), पर ऐसी गलतियों से बचना चाहिए बेहतर कम्पेटिबिलिटी के लिए|
|
||||
|
||||
ये उदाहरण १०० प्रतिशत मान्य जैसन(JSON) है| किस्मत से, जैसन(JSON) डॉक्यूमेंट को पढ़ के ही आप इसे समझ जायेंगे|
|
||||
|
||||
समर्थित डाटा टाइप्स:
|
||||
|
||||
* स्ट्रिंग्स(Strings): `"नमस्ते"`, `"\"एक उद्धरण\""`, `"\u0abe"`, `"नयी पंक्ति|\n"`
|
||||
* अंक(Numbers): `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
|
||||
* ऑब्जेक्ट्स(Objects): `{ "की": "मूल्य" }`
|
||||
* ऐरे(Arrays): `["बहुत सारे मूल्य"]`
|
||||
* विविध(Miscellaneous): `true`, `false`, `null`
|
||||
|
||||
```json
|
||||
{
|
||||
"की": "मूल्य",
|
||||
|
||||
"की": "हमेशा दोहरे उद्धरण चिह्नों में संलग्न होना चाहिए",
|
||||
"अंक": 0,
|
||||
"स्ट्रिंग्स": "नमस्ते| यूनिकोड और \"एस्केप\" सीक्वेंस की अनुमति है|",
|
||||
"बूलियन है?": true,
|
||||
"शून्यता ": null,
|
||||
|
||||
"बड़े अंक": 1.2e+100,
|
||||
|
||||
"ऑब्जेक्ट्स": {
|
||||
"टिप्पणी": "आपके जैसन(JSON) ऑब्जेक्ट को ज़्यादातर ऑब्जेक्ट से ही ढांचा मिलेगा|",
|
||||
|
||||
"ऐरे": [0, 1, 2, 3, "ऐरे में आप कुछ भी रख सकते हैं|", 5],
|
||||
|
||||
"एक और ऑब्जेक्ट": {
|
||||
"टिप्पणी": "आप एक ऑब्जेक्ट दूसरे ऑब्जेक्ट के अंदर रख सकते हैं| ये बहुत उपयोगी होता है|"
|
||||
}
|
||||
},
|
||||
|
||||
"फ़र्ज़ी": [
|
||||
{
|
||||
"पोटेशियम के स्रोत": ["केला"]
|
||||
},
|
||||
[
|
||||
[1, 0, 0, 0],
|
||||
[0, 1, 0, 0],
|
||||
[0, 0, 1, "नव"],
|
||||
[0, 0, 0, 1]
|
||||
]
|
||||
],
|
||||
|
||||
"वैकल्पिक शैली": {
|
||||
"टिप्पणी": "ये देखिये!"
|
||||
, "कॉमा के स्थान": "से फरक नहीं पड़ता, अगर आपने उसे अगली की से पहले लगाया है तो वो मान्य है|"
|
||||
, "एक और टिप्पणी": "कितनी अच्छी बात है"
|
||||
},
|
||||
|
||||
|
||||
|
||||
"खाली स्थान": "से फरक नहीं पड़ता",
|
||||
|
||||
|
||||
|
||||
"ये काफी छोटा था :>": "और ख़तम| अब आपको जैसन(JSON) के बारे में सब कुछ पता है|"
|
||||
}
|
||||
```
|
||||
|
||||
## और जानकारी के लिए
|
||||
|
||||
* [JSON.org](https://json.org) पूरा जैसन(JSON) फ्लोचार्ट के माध्यम से खूबसूरत तरह से दर्शित|
|
||||
* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) जैसन(JSON) का एक संक्षिप्त परिचय|
|
@ -123,7 +123,7 @@ CHIP And {
|
||||
PARTS:
|
||||
// Insert I and K into the nand gate and store the output in an internal
|
||||
// wire called notOut.
|
||||
Nand(a=i,b=b,out=notOut);
|
||||
Nand(a=i,b=k,out=notOut);
|
||||
|
||||
// Use the not gate we constructed to invert notOut and send to the AND
|
||||
// output.
|
||||
@ -228,4 +228,4 @@ Good luck and happy coding!
|
||||
|
||||
* [Hardware Description Language](https://en.wikipedia.org/wiki/Hardware_description_language)
|
||||
|
||||
* [HDL Programming Fundamentals](https://www.electronicdesign.com/products/hdl-programming-fundamentals)
|
||||
* [HDL Programming Fundamentals](https://www.electronicdesign.com/products/hdl-programming-fundamentals)
|
||||
|
@ -8,11 +8,11 @@ translators:
|
||||
- ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
|
||||
---
|
||||
|
||||
HTML stands for HyperText Markup Language.
|
||||
HTML stands for Hypertext Markup Language.
|
||||
|
||||
It is a language which allows us to write pages for the world wide web.
|
||||
It is a language which allows us to write pages for the World Wide Web.
|
||||
It is a markup language, it enables us to write webpages using code to indicate
|
||||
how text and data should be displayed. In fact, html files are simple text
|
||||
how text and data should be displayed. In fact, HTML files are simple text
|
||||
files.
|
||||
|
||||
What is this markup? It is a method of organising the page's data by
|
||||
@ -171,6 +171,6 @@ HTML is written in files ending with `.html` or `.htm`. The mime type is
|
||||
**HTML is NOT a programming language**
|
||||
## To Learn More
|
||||
|
||||
* [wikipedia](https://en.wikipedia.org/wiki/HTML)
|
||||
* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML)
|
||||
* [W3School](http://www.w3schools.com/html/html_intro.asp)
|
||||
* [Wikipedia](https://en.wikipedia.org/wiki/HTML)
|
||||
* [HTML Tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML)
|
||||
* [W3Schools](http://www.w3schools.com/html/html_intro.asp)
|
||||
|
@ -619,4 +619,4 @@ Sesuatu.new.qux # => 'qux'
|
||||
- [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/) - Edisi lama yang [gratis](http://ruby-doc.com/docs/ProgrammingRuby/) tersedia online.
|
||||
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Panduan penulisan kode Ruby oleh komunitas.
|
||||
- [Try Ruby](http://tryruby.org) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser.
|
||||
- [Try Ruby](https://try.ruby-lang.org/) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser.
|
||||
|
BIN
images/solidity/copy-address.png
Normal file
After Width: | Height: | Size: 74 KiB |
BIN
images/solidity/metamask-kovan.png
Normal file
After Width: | Height: | Size: 164 KiB |
BIN
images/solidity/remix-add-token.png
Normal file
After Width: | Height: | Size: 93 KiB |
BIN
images/solidity/remix-choose-file.png
Normal file
After Width: | Height: | Size: 464 KiB |
BIN
images/solidity/remix-compile.png
Normal file
After Width: | Height: | Size: 739 KiB |
BIN
images/solidity/remix-deploy.png
Normal file
After Width: | Height: | Size: 738 KiB |
BIN
images/solidity/remix-interact.png
Normal file
After Width: | Height: | Size: 774 KiB |
BIN
images/solidity/remix-solidity.png
Normal file
After Width: | Height: | Size: 336 KiB |
BIN
images/solidity/remix-testnet.png
Normal file
After Width: | Height: | Size: 850 KiB |
BIN
images/solidity/send-link.png
Normal file
After Width: | Height: | Size: 118 KiB |
@ -22,7 +22,7 @@ translators:
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X.
|
||||
Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e macOS.
|
||||
Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell.
|
||||
|
||||
[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html)
|
||||
|
@ -650,4 +650,4 @@ Something.new.qux #=> 'qux'
|
||||
- [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.
|
||||
- [Try Ruby](https://try.ruby-lang.org/) - Imparare le basi del linguaggio di programmazion Ruby, interattivamente nel browser.
|
||||
|
@ -229,7 +229,7 @@ fn main() {
|
||||
|
||||
// Ciclo/iterazione con `for`
|
||||
let array = [1, 2, 3];
|
||||
for i in array.iter() {
|
||||
for i in array {
|
||||
println!("{}", i);
|
||||
}
|
||||
|
||||
|
275
ja-jp/vim-jp.html.markdown
Normal file
@ -0,0 +1,275 @@
|
||||
---
|
||||
category: tool
|
||||
tool: vim
|
||||
contributors:
|
||||
- ["RadhikaG", "https://github.com/RadhikaG"]
|
||||
translators:
|
||||
- ["Kota Kato", "https://github.com/kato-k"]
|
||||
filename: LearnVim-jp.txt
|
||||
lang: ja-jp
|
||||
---
|
||||
|
||||
|
||||
[Vim](http://www.vim.org)
|
||||
(Vi IMproved) は、Unix用の人気なエディタである vi のクローンです。
|
||||
これは、速度と生産性を高めることを目的に設計されたエディタであり、
|
||||
ほとんどのUnix互換のシステムに組込まれています。
|
||||
ファイル内の特定の位置に移動したり、素早く編集したりするための多数のキーバインドを持ちます。
|
||||
|
||||
`vimtutor`はあなたに`Vim`の使い方を教える素晴しいアプリケーションです。
|
||||
Vimパッケージのインストール時に一緒に付属しますので、
|
||||
コマンドラインで「vimtutor」を実行するだけで、このチュートリアルを開けるはずです。
|
||||
これは、`vim`の全ての主要機能を説明します。
|
||||
|
||||
訳注) 日本語で`vimtutor`を利用するには、「vimtutor ja」を実行しなければならない場合があります。
|
||||
|
||||
## 基本のVim操作
|
||||
|
||||
```
|
||||
vim <filename> # <filename>をVimで開く
|
||||
:help <topic> # <topic>についての組み込みドキュメントが存在する場合、
|
||||
# それを開く
|
||||
:q # Vimを終了する
|
||||
:w # 編集中のファイルを保存する
|
||||
:wq # ファイルを保存して、Vimを終了する
|
||||
ZZ # ファイルを保存して、Vimを終了する。:xと同様
|
||||
:q! # ファイルを保存せずにVimを終了する
|
||||
# :q を ! *強制的に* 実行するため保存せずにVimが終了します
|
||||
ZQ # ファイルを保存せずにVimを終了する
|
||||
:x # 変更点がある時、ファイルを保存してVimを終了する
|
||||
|
||||
u # Undo
|
||||
CTRL+R # Redo
|
||||
|
||||
h # 左に一文字移動
|
||||
j # 一行下に移動
|
||||
k # 一行上に移動
|
||||
l # 右に一文字移動
|
||||
|
||||
Ctrl+B # ウィンドウを一画面上に移動
|
||||
Ctrl+F # ウィンドウを一画面下に移動
|
||||
Ctrl+D # ウィンドウを半画面上に移動
|
||||
Ctrl+U # ウィンドウを半画面下に移動
|
||||
|
||||
# 行内を移動する
|
||||
|
||||
0 # 行頭に移動
|
||||
$ # 行末に移動
|
||||
^ # 行の初めの非空白文字に移動
|
||||
|
||||
# テキストの検索
|
||||
|
||||
/word # カーソル以降に出現する全ての一致をハイライト
|
||||
?word # カーソル以前に出現する全ての一致をハイライト
|
||||
n # カーソルを次の一致に移動
|
||||
N # カーソルを前の一致に移動
|
||||
|
||||
:%s/foo/bar/g # 全ての行について「foo」を「bar」に置換
|
||||
:s/foo/bar/g # 現在の行について「foo」を「bar」に置換
|
||||
:%s/\n/\r/g # 改行文字の置換
|
||||
|
||||
# 文字への移動
|
||||
|
||||
f<character> # 前方の<character>に移動する
|
||||
t<character> # 前方の<character>の一文字前に移動する
|
||||
|
||||
# 例
|
||||
f< # 前方の < に移動
|
||||
t< # 前方の < の一文字前に移動
|
||||
|
||||
# 単語ごとの移動
|
||||
|
||||
w # 一単語前に移動
|
||||
b # 一単語後ろに移動
|
||||
e # 現在の単語の後部に移動
|
||||
|
||||
# 移動のためのキーバインド
|
||||
|
||||
gg # ファイルの先頭に移動
|
||||
G # ファイルの最後に移動
|
||||
:NUM # ファイルのNUM行に移動(NUMは任意の行数)
|
||||
H # カーソルをウィンドウ上部に移動
|
||||
M # カーソルをウィンドウ中央に移動
|
||||
L # カーソルをウィンドウ下部に移動
|
||||
```
|
||||
|
||||
## ヘルプドキュメント:
|
||||
|
||||
Vimには`:help <topic>`でアクセスできるヘルプドキュメントが組込まれています。
|
||||
例えば、`:help navigation`はカーソルを移動する方法についてのドキュメントを開きます。
|
||||
|
||||
`:help`はオプション無しでも利用できます。
|
||||
これにより、Vimにより親しみやすくすることを目的としたデフォルトのヘルプダイアログが開かれます。
|
||||
|
||||
## モード:
|
||||
|
||||
Vimは**モード**の概念に基づいています。
|
||||
|
||||
- Command Mode - Vimはこのモードで起動し、移動とコマンドの実行に使われます
|
||||
- Insert Mode - ファイルに変更を加えるのに使われます
|
||||
- Visual Mode - テキストをハイライトしてオペレータを適用するために使われます
|
||||
- Ex Mode - コマンドを入力するための「:」プロンプトで使われます
|
||||
|
||||
```
|
||||
i # カーソル位置の前からInsert Modeに入る
|
||||
a # カーソル位置の後ろからInsert Modeに入る
|
||||
v # Visual Modeに入る
|
||||
: # Ex Modeに入る
|
||||
<esc> # 現在のモードからコマンドモードに「脱出」
|
||||
|
||||
# テキストのコピーと貼り付け
|
||||
|
||||
y # 選択された対象をヤンクする
|
||||
yy # 現在の行をヤンクする
|
||||
d # 選択された対象を削除する
|
||||
dd # 現在の行を削除する
|
||||
p # ヤンクされたテキストをカーソルの後ろに貼り付ける
|
||||
P # ヤンクされたテキストをのカーソルの前に貼り付ける
|
||||
x # カーソル位置の文字を削除
|
||||
```
|
||||
|
||||
## Vimの「文法」
|
||||
|
||||
Vimの操作は「動詞・修飾子・名詞」形式のコマンドとして考えることができます。
|
||||
|
||||
- 動詞 - 動作
|
||||
- 修飾子 - 動作の実行方法
|
||||
- 名詞 - 動作が作用するオブジェクト
|
||||
|
||||
「動詞・修飾子・名詞」関するいくつかの重要な例:
|
||||
|
||||
```
|
||||
# '動詞'
|
||||
|
||||
d # 削除
|
||||
c # 変更
|
||||
y # ヤンク (コピー)
|
||||
v # ビジュアル選択
|
||||
|
||||
# '修飾子'
|
||||
|
||||
i # 内部
|
||||
a # 周り
|
||||
NUM # 回数 (NUMは任意の番号)
|
||||
f # 任意の一文字まで
|
||||
t # 任意の一文字の手前まで
|
||||
/ # カーソル以降の任意の文字列まで
|
||||
? # カーソル以前の任意の文字列まで
|
||||
|
||||
# '名詞'
|
||||
|
||||
w # 単語
|
||||
s # 文
|
||||
p # 段落
|
||||
b # ブロック
|
||||
|
||||
# 「文」の例
|
||||
|
||||
d2w # 削除 2 単語 (2単語を削除)
|
||||
cis # 変更 内部 文 (文の内部を変更)
|
||||
yip # ヤンク 内部 段落 (段落の内部をヤンク)
|
||||
ct< # 変更 手前 < (<の手前まで変更)
|
||||
d$ # 削除 行末まで (行末まで削除)
|
||||
```
|
||||
|
||||
## いくつかのショートカットと小技
|
||||
|
||||
<!--TODO: Add more!-->
|
||||
```
|
||||
> # 選択部を1ブロックインデント
|
||||
< # 選択部を1ブロックデインデント
|
||||
:earlier 15m # ファイルを15分前の状態に戻す
|
||||
:later 15m # 上記のコマンドの逆
|
||||
ddp # 連続する行を入れ替え
|
||||
. # 前回の動作を繰り返す
|
||||
:w !sudo tee % # 編集中のファイルを管理者として保存
|
||||
:set syntax=c # 「C言語」のシンタックスハイライトを利用する
|
||||
:sort # 全ての行をソートする
|
||||
:sort! # 全ての行を降順にソートする
|
||||
:sort u # 全ての行をソートして重複を削除する
|
||||
~ # 選択部分の大文字小文字を入れ替える
|
||||
u # 選択部分を小文字にする
|
||||
U # 選択部分を大文字にする
|
||||
J # 現在の行と次の行を結合する
|
||||
|
||||
# テキストの折り畳み
|
||||
zf # 選択したテキストを折り畳む
|
||||
zo # 折り畳みを開く
|
||||
zc # 折り畳みを閉じる
|
||||
zR # 全ての折り畳みを開く
|
||||
zM # 全ての折り畳みを閉じる
|
||||
```
|
||||
|
||||
## マクロ
|
||||
|
||||
マクロは基本的に記録可能なアクションです。
|
||||
マクロの記録を開始すると、記録を停止するまで**全て**の操作とコマンドが記録されます。
|
||||
マクロを呼びだすと、まったく同じ一連の操作とコマンドが文書に再度適用されます。
|
||||
|
||||
```
|
||||
qa # 「a」という名前のマクロの記録を開始する
|
||||
q # 記録を停止する
|
||||
@a # 「a」マクロを再生する
|
||||
```
|
||||
|
||||
### ~/.vimrc の設定
|
||||
|
||||
ファイル.vimrcは起動時にVimの設定として利用されます
|
||||
|
||||
次は~/.vimrcファイルのサンプルです
|
||||
|
||||
```
|
||||
" Example ~/.vimrc
|
||||
" 2015.10
|
||||
|
||||
" Required for vim to be iMproved
|
||||
set nocompatible
|
||||
|
||||
" 自動インデントなどを利用するために、ファイル名からファイルタイプを決定する
|
||||
filetype indent plugin on
|
||||
|
||||
" シンタックスハイライトを利用する
|
||||
syntax on
|
||||
|
||||
" より良いコマンドライン補完
|
||||
set wildmenu
|
||||
|
||||
" 大文字を利用しない場合、検索で大文字・小文字を区別しない
|
||||
set ignorecase
|
||||
set smartcase
|
||||
|
||||
" ファイル固有のインデントが有効でない場合、現在行のインデントを継続する
|
||||
set autoindent
|
||||
|
||||
" 行番号の表示
|
||||
set number
|
||||
|
||||
" インデントに関するオプション
|
||||
|
||||
" TAB文字の幅
|
||||
set tabstop=4
|
||||
|
||||
" 編集中TABキーを押した際の挙動
|
||||
set softtabstop=4
|
||||
|
||||
" << >> を利用した再インデント時のスペースの数
|
||||
set shiftwidth=4
|
||||
|
||||
" TABキーをスペースに変換する
|
||||
set expandtab
|
||||
|
||||
" 賢いTAB機能を有効にする
|
||||
set smarttab
|
||||
```
|
||||
|
||||
### 参考文献
|
||||
|
||||
[Vim | Home](http://www.vim.org/index.php)
|
||||
|
||||
`$ vimtutor`
|
||||
|
||||
[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/)
|
||||
|
||||
[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
|
||||
|
||||
[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim)
|
@ -18,7 +18,7 @@ As we only have a scant *y* minutes, we'll survey the basics here and
|
||||
leave the remaining details for the manual. So please, keep your arms and
|
||||
legs inside the vehicle at all times, and on with the scenic tour!
|
||||
|
||||
```janet
|
||||
```python
|
||||
# A comment.
|
||||
|
||||
# Some literal values.
|
||||
|
@ -510,10 +510,12 @@ public class LearnJava {
|
||||
|
||||
// toString returns this Object's string representation.
|
||||
System.out.println("trek info: " + trek.toString());
|
||||
} // End main method
|
||||
|
||||
private static class TestInitialization {
|
||||
// Double Brace Initialization
|
||||
// The Java Language has no syntax for how to create static Collections
|
||||
// in an easy way. Usually you end up in the following way:
|
||||
// Before Java 11, the Java Language had no syntax for how to create
|
||||
// static Collections in an easy way. Usually you end up like this:
|
||||
private static final Set<String> COUNTRIES = new HashSet<String>();
|
||||
static {
|
||||
COUNTRIES.add("DENMARK");
|
||||
@ -521,10 +523,10 @@ public class LearnJava {
|
||||
COUNTRIES.add("FINLAND");
|
||||
}
|
||||
|
||||
// But there's a nifty way to achieve the same thing in an
|
||||
// easier way, by using something that is called Double Brace
|
||||
// Initialization.
|
||||
private static final Set<String> COUNTRIES = new HashSet<String>() {{
|
||||
// There's a nifty way to achieve the same thing,
|
||||
// by using something that is called Double Brace Initialization.
|
||||
private static final Set<String> COUNTRIES_DOUBLE_BRACE =
|
||||
new HashSet<String>() {{
|
||||
add("DENMARK");
|
||||
add("SWEDEN");
|
||||
add("FINLAND");
|
||||
@ -535,8 +537,45 @@ public class LearnJava {
|
||||
// is called when the anonymous inner class is created.
|
||||
// This does not only work for Collections, it works for all
|
||||
// non-final classes.
|
||||
|
||||
|
||||
} // End main method
|
||||
// Another option was to initialize the Collection from an array,
|
||||
// using Arrays.asList() method:
|
||||
private static final List<String> COUNTRIES_AS_LIST =
|
||||
Arrays.asList("SWEDEN", "DENMARK", "NORWAY");
|
||||
// This has one catch: the list we get is internally backed by the array,
|
||||
// and since arrays can't change their size, the list backed by the array
|
||||
// is not resizeable, which means we can't add new elements to it:
|
||||
public static void main(String[] args) {
|
||||
COUNTRIES.add("FINLAND"); // throws UnsupportedOperationException!
|
||||
// However, we can replace elements by index, just like in array:
|
||||
COUNTRIES.set(1, "FINLAND");
|
||||
System.out.println(COUNTRIES); // prints [SWEDEN, FINLAND, NORWAY]
|
||||
}
|
||||
// The resizing problem can be circumvented
|
||||
// by creating another Collection from the List:
|
||||
private static final Set<String> COUNTRIES_SET =
|
||||
new HashSet<>(Arrays.asList("SWEDEN", "DENMARK", "NORWAY"));
|
||||
// It's perfectly fine to add anything to the Set of COUNTRIES now.
|
||||
} // End TestInitialization class
|
||||
|
||||
private static class TestJava11Initialization {
|
||||
// Since Java 11, there is a convenient option to initialize Collections:
|
||||
// Set.of() and List.of() methods.
|
||||
private static final Set<String> COUNTRIES =
|
||||
Set.of("SWEDEN", "DENMARK", "NORWAY");
|
||||
// There is a massive catch, though: Lists and Sets initialized like this
|
||||
// 1) are immutable
|
||||
// 2) can't contain null elements (even check for null elements fails)!
|
||||
public static void main(String[] args) {
|
||||
COUNTRIES.add("FINLAND"); // throws UnsupportedOperationException
|
||||
COUNTRIES.remove("NORWAY"); // throws UnsupportedOperationException
|
||||
COUNTRIES.contains(null); // throws NullPointerException
|
||||
}
|
||||
private static final Set<String> COUNTRIES_WITH_NULL =
|
||||
Set.of("SWEDEN", null, "NORWAY"); // throws NullPointerException
|
||||
|
||||
} // End TestJava11Initialization class
|
||||
} // End LearnJava class
|
||||
|
||||
// You can include other, non-public outer-level classes in a .java file,
|
||||
|
@ -590,7 +590,7 @@ if (Object.create === undefined){ // don't overwrite it if it exists
|
||||
// ES6 Additions
|
||||
|
||||
// The "let" keyword allows you to define variables in a lexical scope,
|
||||
// as opposed to a block scope like the var keyword does.
|
||||
// as opposed to a function scope like the var keyword does.
|
||||
let name = "Billy";
|
||||
|
||||
// Variables defined with let can be reassigned new values.
|
||||
|
@ -124,7 +124,7 @@ local obj5 = {
|
||||
};
|
||||
assert obj5 == {};
|
||||
|
||||
# a jsonnet doucment have to evaluate to something
|
||||
# a jsonnet document has to evaluate to something
|
||||
# be it an object, list, number or just string literal
|
||||
"FIN"
|
||||
|
||||
|
@ -11,7 +11,7 @@ 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.
|
||||
|
||||
This is based on Julia 1.0.0
|
||||
This is based on Julia version 1.0.0.
|
||||
|
||||
```julia
|
||||
# Single line comments start with a hash (pound) symbol.
|
||||
@ -83,7 +83,7 @@ false
|
||||
1 > 10 # => false
|
||||
2 <= 2 # => true
|
||||
2 >= 2 # => true
|
||||
# Comparisons can be chained
|
||||
# Comparisons can be chained, like in Python but unlike many other languages
|
||||
1 < 2 < 3 # => true
|
||||
2 < 3 < 2 # => false
|
||||
|
||||
@ -93,28 +93,29 @@ false
|
||||
# Character literals are written with '
|
||||
'a'
|
||||
|
||||
# Strings are UTF8 encoded. Only if they contain only ASCII characters can
|
||||
# they be safely indexed.
|
||||
ascii("This is a string")[1]
|
||||
# Strings are UTF8 encoded, so strings like "π" or "☃" are not directly equivalent
|
||||
# to an array of single characters.
|
||||
# Only if they contain only ASCII characters can they be safely indexed.
|
||||
ascii("This is a string")[1] # => 'T'
|
||||
# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase)
|
||||
# Julia indexes from 1
|
||||
# Beware, Julia indexes everything from 1 (like MATLAB), not 0 (like most languages).
|
||||
# Otherwise, iterating over strings is recommended (map, for loops, etc).
|
||||
|
||||
# String can be compared lexicographically
|
||||
"good" > "bye" # => true
|
||||
# String can be compared lexicographically, in dictionnary order:
|
||||
"good" > "bye" # => true
|
||||
"good" == "good" # => true
|
||||
"1 + 2 = 3" == "1 + 2 = $(1 + 2)" # => true
|
||||
|
||||
# $ can be used for string interpolation:
|
||||
# $(..) can be used for string interpolation:
|
||||
"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
|
||||
# You can put any Julia expression inside the parentheses.
|
||||
|
||||
# Printing is easy
|
||||
println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you!
|
||||
println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you!
|
||||
|
||||
# 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
|
||||
using Printf # this is how you load (or import) a module
|
||||
@printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000
|
||||
|
||||
|
||||
####################################################
|
||||
@ -123,7 +124,7 @@ using Printf
|
||||
|
||||
# You don't declare variables before assigning to them.
|
||||
someVar = 5 # => 5
|
||||
someVar # => 5
|
||||
someVar # => 5
|
||||
|
||||
# Accessing a previously unassigned variable is an error
|
||||
try
|
||||
@ -137,9 +138,10 @@ end
|
||||
SomeOtherVar123! = 6 # => 6
|
||||
|
||||
# You can also use certain unicode characters
|
||||
# here ☃ is a Unicode 'snowman' characters, see http://emojipedia.org/%E2%98%83%EF%B8%8F if it displays wrongly here
|
||||
☃ = 8 # => 8
|
||||
# These are especially handy for mathematical notation
|
||||
2 * π # => 6.283185307179586
|
||||
# These are especially handy for mathematical notation, like the constant π
|
||||
2 * π # => 6.283185307179586
|
||||
|
||||
# A note on naming conventions in Julia:
|
||||
#
|
||||
@ -171,7 +173,7 @@ matrix = [1 2; 3 4] # => 2×2 Array{Int64,2}: [1 2; 3 4]
|
||||
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!
|
||||
# By convention, the exclamation mark '!'' is appended to names of functions
|
||||
# By convention, the exclamation mark '!' is appended to names of functions
|
||||
# that modify their arguments
|
||||
push!(a, 1) # => [1]
|
||||
push!(a, 2) # => [1,2]
|
||||
@ -202,10 +204,10 @@ 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 Array{Int64,1}: [5,4,6]
|
||||
sort(arr) # => [4,5,6]
|
||||
arr # => [5,4,6]
|
||||
sort!(arr) # => [4,5,6]
|
||||
arr # => [4,5,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
|
||||
@ -238,7 +240,7 @@ 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[1:3] # => [1, 2, 3]
|
||||
a[2:end] # => [2, 3, 4, 5]
|
||||
|
||||
# Remove elements from an array by index with splice!
|
||||
@ -276,15 +278,15 @@ in(2, tup) # => true
|
||||
|
||||
# You can unpack tuples into variables
|
||||
a, b, c = (1, 2, 3) # => (1,2,3)
|
||||
a # => 1
|
||||
b # => 2
|
||||
c # => 3
|
||||
a # => 1
|
||||
b # => 2
|
||||
c # => 3
|
||||
|
||||
# Tuples are created even if you leave out the parentheses
|
||||
d, e, f = 4, 5, 6 # => (4,5,6)
|
||||
d # => 4
|
||||
e # => 5
|
||||
f # => 6
|
||||
d # => 4
|
||||
e # => 5
|
||||
f # => 6
|
||||
|
||||
# A 1-element tuple is distinct from the value it contains
|
||||
(1,) == 1 # => false
|
||||
@ -292,8 +294,8 @@ f # => 6
|
||||
|
||||
# Look how easy it is to swap two values
|
||||
e, d = d, e # => (5,4)
|
||||
d # => 5
|
||||
e # => 4
|
||||
d # => 5
|
||||
e # => 4
|
||||
|
||||
# Dictionaries store mappings
|
||||
emptyDict = Dict() # => Dict{Any,Any} with 0 entries
|
||||
@ -375,7 +377,8 @@ end
|
||||
# Iterable types include Range, Array, Set, Dict, and AbstractString.
|
||||
for animal = ["dog", "cat", "mouse"]
|
||||
println("$animal is a mammal")
|
||||
# You can use $ to interpolate variables or expression into strings
|
||||
# You can use $ to interpolate variables or expression into strings.
|
||||
# In this special case, no need for parenthesis: $animal and $(animal) give the same
|
||||
end
|
||||
# => dog is a mammal
|
||||
# => cat is a mammal
|
||||
@ -408,7 +411,7 @@ end
|
||||
let x = 0
|
||||
while x < 4
|
||||
println(x)
|
||||
x += 1 # Shorthand for x = x + 1
|
||||
x += 1 # Shorthand for in place increment: x = x + 1
|
||||
end
|
||||
end
|
||||
# => 0
|
||||
|
@ -2,19 +2,22 @@
|
||||
language: yaml
|
||||
filename: learnyaml-kr.yaml
|
||||
contributors:
|
||||
- ["Leigh Brenecki", "https://github.com/adambrenecki"]
|
||||
- ["Suhas SG", "https://github.com/jargnar"]
|
||||
- ["Leigh Brenecki", "https://github.com/adambrenecki"]
|
||||
- ["Suhas SG", "https://github.com/jargnar"]
|
||||
translators:
|
||||
- ["Wooseop Kim", "https://github.com/linterpreteur"]
|
||||
- ["Wooseop Kim", "https://github.com/linterpreteur"]
|
||||
- ["Justin Yang", "https://github.com/justin-themedium"]
|
||||
lang: ko-kr
|
||||
---
|
||||
|
||||
YAML은 인간이 직접 쓰고 읽을 수 있도록 설계된 데이터 직렬화 언어입니다.
|
||||
|
||||
YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미를 준 JSON의 엄격한 수퍼셋입니다.
|
||||
하지만 파이썬과는 달리 YAML은 탭 문자를 전혀 허용하지 않습니다.
|
||||
하지만 파이썬과는 달리 YAML은 탭 문자를 들여쓰기에 사용하지 않습니다.
|
||||
|
||||
```yaml
|
||||
--- # 문서 시작
|
||||
|
||||
# YAML의 주석은 이런 식입니다.
|
||||
|
||||
############
|
||||
@ -22,19 +25,23 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
|
||||
############
|
||||
|
||||
# 문서 내내 이어질 루트 객체는 맵입니다.
|
||||
# 맵은 다른 언어의 딕셔너리, 해시, 혹은 객체에 해당됩니다.
|
||||
# 맵은 다른 언어의 딕셔너리, 해시, 혹은 객체에 해당합니다.
|
||||
키: 값
|
||||
다른_키: 다른 값이 여기 옵니다.
|
||||
숫자_값: 100
|
||||
# 숫자 1을 값으로 가지기 위해서는 따옴표에 담아야 합니다.
|
||||
# 그러지 않는다면 YAML 파서는 그것을 참 값을 가지는 불리언으로 해석할 것입니다.
|
||||
과학적_표기법: 1e+12
|
||||
# 숫자 1은 불리언이 아닌 값으로 처리됩니다. 불리언으로 처리하고 싶다면
|
||||
# true를 사용하세요.
|
||||
불리언: true
|
||||
널_값: null
|
||||
띄어서 쓴 키: 값
|
||||
# 문자열에 따옴표를 칠 필요는 없습니다. 하지만 칠 수도 있습니다.
|
||||
하지만: "따옴표에 담은 문자열"
|
||||
"키도 따옴표에 담을 수 있습니다.": "키에 ':'을 넣고 싶다면 유용합니다."
|
||||
하지만: '따옴표에 담은 문자열'
|
||||
'키도 따옴표에 담을 수 있습니다.': "키에 ':'을 넣고 싶다면 유용합니다."
|
||||
작은 따옴표: '는 ''하나''의 이스케이프 패턴을 갖습니다'
|
||||
큰 따옴표: "는 많이 갖습니다. \", \0, \t, \u263A, \x0d\x0a == \r\n, 그리고 더."
|
||||
# UTF-8/16/32 문자는 인코딩되어야 합니다.
|
||||
첨자 2: \u00B2
|
||||
|
||||
# 여러 줄의 문자열은 (|을 이용한) '리터럴 블락' 혹은 (>을 이용한) '접은 블락'으로
|
||||
# 쓸 수 있습니다.
|
||||
@ -59,12 +66,12 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
|
||||
# 모임 형 #
|
||||
##########
|
||||
|
||||
# 중첩은 들여쓰기로 가능합니다.
|
||||
# 중첩은 들여쓰기를 사용합니다. 2칸 띄어쓰기가 많이 쓰입니다(필수는 아닙니다).
|
||||
중첩된_맵:
|
||||
키: 값
|
||||
다른_키: 다른 값
|
||||
다른_중첩된_맵:
|
||||
안녕: 안녕
|
||||
키: 값
|
||||
다른_키: 다른 값
|
||||
다른_중첩된_맵:
|
||||
안녕: 안녕
|
||||
|
||||
# 맵은 반드시 문자열 키를 가지는 것은 아닙니다.
|
||||
0.25: 실수형 키
|
||||
@ -72,28 +79,31 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
|
||||
# 키는 여러 줄에 걸친 객체와 같이 복합적일 수도 있습니다.
|
||||
# ?와 그 뒤의 띄어쓰기로 복합 키의 시작을 나타냅니다.
|
||||
? |
|
||||
여러 줄짜리
|
||||
키
|
||||
여러 줄짜리
|
||||
키
|
||||
: 그리고 그 값
|
||||
|
||||
# YAML은 복합 키 문법으로 연속열 간의 매핑을 지원합니다.
|
||||
# YAML은 복합 키 문법으로 연속열 간의 매핑도 지원합니다.
|
||||
# 일부 파서는 지원하지 않을 수 있습니다.
|
||||
# 예시
|
||||
? - 맨체스터 유나이티드
|
||||
- 레알 마드리드
|
||||
: [ 2001-01-01, 2002-02-02 ]
|
||||
: [2001-01-01, 2002-02-02]
|
||||
|
||||
# 리스트 혹은 배열에 대응되는 연속열은 다음과 같습니다.
|
||||
# (들여쓰기처럼 '-'를 세는 것에 주의하세요)
|
||||
연속열:
|
||||
- 하나
|
||||
- 둘
|
||||
- 0.5 # 연속열은 다른 형을 포함 가능
|
||||
- 넷
|
||||
- 키: 값
|
||||
다른_키: 다른_값
|
||||
-
|
||||
- 연속열 안의
|
||||
- 또 다른 연속열
|
||||
- 하나
|
||||
- 둘
|
||||
- 0.5 # 연속열은 다른 형을 포함 가능
|
||||
- 넷
|
||||
- 키: 값
|
||||
다른_키: 다른_값
|
||||
-
|
||||
- 연속열 안의
|
||||
- 또 다른 연속열
|
||||
- - - 중첩된 연속열 지시자
|
||||
- 접힘 가능
|
||||
|
||||
# YAML은 JSON의 수퍼셋이기 때문에, JSON식으로 맵과 연속열을 작성할 수도
|
||||
# 있습니다.
|
||||
@ -111,17 +121,19 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
|
||||
|
||||
# 앵커는 속성을 복제하거나 상속할 수 있습니다.
|
||||
기반: &기반
|
||||
이름: 모두 이름이 같다
|
||||
이름: 모두 이름이 같다
|
||||
|
||||
멍멍: &멍멍
|
||||
<<: *기반
|
||||
나이: 10
|
||||
# 정규식 << 는 병합 키 언어-비종속 타입으로 불립니다. 이는 하나
|
||||
# 이상 지정된 맵의 모든 키가 현재 맵 안으로 삽입됨을 나타냅니다.
|
||||
멍멍:
|
||||
<<: *기반
|
||||
나이: 10
|
||||
|
||||
야옹: &야옹
|
||||
<<: *기반
|
||||
나이: 20
|
||||
야옹:
|
||||
<<: *기반
|
||||
나이: 20
|
||||
|
||||
# 멍멍이와 야옹이는 같은 이름, '모두 이름이 같다'를 같습니다.
|
||||
# 멍멍이와 야옹이도 '이름: 모두 이름이 같다'를 갖습니다.
|
||||
|
||||
# 또한 YAML에는 명시적으로 형을 선언할 수 있는 태그가 있습니다.
|
||||
명시적_문자열: !!str 0.5
|
||||
@ -138,8 +150,7 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
|
||||
# 기타 YAML 형 #
|
||||
###############
|
||||
|
||||
# Strings and numbers aren't the only scalars that YAML can understand.
|
||||
# YAML이 이해할 수 있는 스칼라는 문자열과 수만 있는 것은 아닙니다.
|
||||
# YAML이 이해할 수 있는 스칼라가 문자열과 수만 있는 것은 아닙니다.
|
||||
# ISO 형식 날짜와 시간 리터럴 또한 해석됩니다.
|
||||
시간: 2001-12-15T02:59:43.1Z
|
||||
띄어쓰기_한_시간: 2001-12-14 21:59:43.10 -5
|
||||
@ -148,25 +159,27 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
|
||||
# !!binary 태그는 문자열이 실제로는 base64로 인코딩된
|
||||
# 이진수 객체(BLOB)라는 것을 나타냅니다.
|
||||
이미지_파일: !!binary |
|
||||
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
|
||||
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
|
||||
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
|
||||
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
|
||||
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
|
||||
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
|
||||
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
|
||||
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
|
||||
|
||||
# YAML에는 다음과 같은 집합도 있습니다.
|
||||
집합:
|
||||
? 하나
|
||||
? 둘
|
||||
? 셋
|
||||
? 하나
|
||||
? 둘
|
||||
? 셋
|
||||
|
||||
# 파이썬과 마찬가지로 집합은 단지 널 값을 갖는 맵입니다. 위는 다음과 같습니다.
|
||||
# 집합은 단지 널 값을 갖는 맵입니다. 위는 다음과 같습니다.
|
||||
집합2:
|
||||
하나: null
|
||||
둘: null
|
||||
셋: null
|
||||
하나: null
|
||||
둘: null
|
||||
셋: null
|
||||
|
||||
... # 문서 끝
|
||||
```
|
||||
|
||||
### 더 읽기
|
||||
|
||||
+ [(영어) YAML 공식 사이트](http://yaml.org/)
|
||||
+ [(영어) 온라인 YAML 검사기](http://codebeautify.org/yaml-validator)
|
||||
+ [(영어) YAML 공식 사이트](https://yaml.org/)
|
||||
+ [(영어) 온라인 YAML 검사기](http://www.yamllint.com/)
|
||||
|
@ -180,7 +180,7 @@ fun helloWorld(val name : String) {
|
||||
|
||||
// destructuring in "for" loop
|
||||
for ((a, b, c) in listOf(fooData)) {
|
||||
println("$a $b $c") // => 1 100 4
|
||||
println("$a $b $c") // => 1 2 4
|
||||
}
|
||||
|
||||
val mapData = mapOf("a" to 1, "b" to 2)
|
||||
@ -426,7 +426,7 @@ data class Counter(var value: Int) {
|
||||
operator fun invoke() = println("The value of the counter is $value")
|
||||
|
||||
}
|
||||
/* You can also overload operators through an extension methods */
|
||||
/* You can also overload operators through extension methods */
|
||||
// overload -Counter
|
||||
operator fun Counter.unaryMinus() = Counter(-this.value)
|
||||
|
||||
|
@ -131,7 +131,7 @@ 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`
|
||||
2. `λx.c = Kc` provided that `x` does not occur free in `c`
|
||||
3. `λx.(y z) = S (λx.y) (λx.z)`
|
||||
|
||||
Take the church number 2 for example:
|
||||
|
@ -2,7 +2,7 @@
|
||||
language: latex
|
||||
contributors:
|
||||
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
|
||||
- ["Colton Kohnke", "http://github.com/voltnor"]
|
||||
- ["Colton Kohnke", "https://github.com/voltnor"]
|
||||
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
|
||||
- ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
|
||||
- ["Svetlana Golubeva", "https://attillax.github.io/"]
|
||||
@ -95,8 +95,9 @@ to the source code.
|
||||
|
||||
Separate paragraphs by empty lines.
|
||||
|
||||
You need to add a backslash 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.
|
||||
You need to add a tilde after abbreviations (if not followed by a comma) for a
|
||||
non-breaking space, 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
|
||||
@ -140,8 +141,7 @@ about!
|
||||
Operators are essential parts of a mathematical document:
|
||||
trigonometric functions ($\sin$, $\cos$, $\tan$),
|
||||
logarithms and exponentials ($\log$, $\exp$),
|
||||
limits ($\lim$), etc.\
|
||||
have pre-defined LaTeX commands.
|
||||
limits ($\lim$), etc.~have pre-defined LaTeX commands.
|
||||
Let's write an equation to see how it's done:
|
||||
$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
|
||||
|
||||
@ -181,7 +181,9 @@ Summations and Integrals are written with sum and int commands:
|
||||
\section{Figures}
|
||||
|
||||
Let's insert a figure. Figure placement can get a little tricky.
|
||||
Basic options are [t] for top, [b] for bottom, [h] for here (approximately).
|
||||
I definitely have to lookup the placement options each time.
|
||||
% See https://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions for more details
|
||||
|
||||
\begin{figure}[H] % H here denoted the placement option.
|
||||
\centering % centers the figure on the page
|
||||
@ -198,16 +200,24 @@ We can also insert Tables in the same way as figures.
|
||||
\begin{table}[H]
|
||||
\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}
|
||||
Number & Last Name & First Name \\ % Column rows are separated by &
|
||||
% The basics are simple: one letter for each column, to control alignment:
|
||||
% basic options are: c, l, r and p for centered, left, right and paragraph
|
||||
% optionally, you can add a | for a vertical line
|
||||
% See https://en.wikibooks.org/wiki/LaTeX/Tables for more details
|
||||
\begin{tabular}{c|cc} % here it means "centered | vertical line, centered centered"
|
||||
Number & First Name & Last Name \\ % Column rows are separated by &
|
||||
\hline % a horizontal line
|
||||
1 & Biggus & Dickus \\
|
||||
2 & Monty & Python
|
||||
\end{tabular}
|
||||
% it will approximately be displayed like this
|
||||
% Number | First Name Last Name
|
||||
% -------|--------------------------- % because of \hline
|
||||
% 1 | Biggus Dickus
|
||||
% 2 | Monty Python
|
||||
\end{table}
|
||||
|
||||
\section{Getting \LaTeX{} to not compile something (i.e.\ Source Code)}
|
||||
\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
|
||||
@ -218,14 +228,15 @@ environment.
|
||||
\begin{verbatim}
|
||||
print("Hello World!")
|
||||
a%b; % look! We can use % signs in verbatim.
|
||||
random = 4; #decided by fair random dice roll
|
||||
random = 4; #decided by fair random dice roll, https://www.xkcd.com/221/
|
||||
See https://www.explainxkcd.com/wiki/index.php/221:_Random_Number
|
||||
\end{verbatim}
|
||||
|
||||
\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).
|
||||
(Yes, this document actually does compile).
|
||||
|
||||
Getting to the final document using \LaTeX{} consists of the following
|
||||
steps:
|
||||
@ -244,6 +255,7 @@ 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
|
||||
multiple times, to generate an intermediary *.aux file.}.
|
||||
% Also, this is how you add footnotes to your document!
|
||||
% with a simple \footnote{...} command. They are numbered ¹, ², ... by default.
|
||||
|
||||
You write all your formatting information in plain text in Step 1.
|
||||
The compilation part in Step 2 takes care of producing the document in the
|
||||
@ -262,9 +274,30 @@ There exists two main types of links: visible URL \\
|
||||
% You can not add extra-spaces or special symbols into shadowing text since it
|
||||
% will cause mistakes during the compilation
|
||||
|
||||
This package also produces list of thumbnails in the output pdf document and
|
||||
This package also produces list of thumbnails in the output PDF document and
|
||||
active links in the table of contents.
|
||||
|
||||
\section{Writing in ASCII or other encodings}
|
||||
|
||||
By default, historically LaTeX accepts inputs which are pure ASCII (128),
|
||||
but not extended ASCII, meaning without accents (à, è etc.) and non-Latin symbols.
|
||||
|
||||
It is easy to insert accents and basic Latin symbols, with backslash shortcuts
|
||||
Like \,c, \'e, \`A, \ae and \oe etc. % for ç, é, À, etc
|
||||
% See https://en.wikibooks.org/wiki/LaTeX/Special_Characters#Escaped_codes for more
|
||||
|
||||
To write directly in UTF-8, when compiling with pdflatex, use
|
||||
\begin{verbatim}
|
||||
\usepackage[utf8]{inputenc}
|
||||
\end{verbatim}
|
||||
The selected font has to support the glyphs used for your document, you have to add
|
||||
\begin{verbatim}
|
||||
\usepackage[T1]{fontenc}
|
||||
\end{verbatim}
|
||||
|
||||
Since LuaTeX and XeLaTeX were designed with built-in support for UTF-8, making
|
||||
life easier for writing in non-Latin alphabets.
|
||||
|
||||
\section{End}
|
||||
|
||||
That's all for now!
|
||||
@ -284,6 +317,6 @@ That's all for now!
|
||||
|
||||
## More on LaTeX
|
||||
|
||||
* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](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)
|
||||
|
@ -383,19 +383,26 @@ dofile('mod2.lua') --> Hi! (runs it again)
|
||||
-- loadfile loads a lua file but doesn't run it yet.
|
||||
f = loadfile('mod2.lua') -- Call f() to run it.
|
||||
|
||||
-- loadstring is loadfile for strings.
|
||||
g = loadstring('print(343)') -- Returns a function.
|
||||
-- load is loadfile for strings.
|
||||
-- (loadstring is deprecated, use load instead)
|
||||
g = load('print(343)') -- Returns a function.
|
||||
g() -- Prints out 343; nothing printed before now.
|
||||
|
||||
--]]
|
||||
|
||||
```
|
||||
|
||||
## Community
|
||||
|
||||
If you need support join the official Lua [mailing list](https://www.lua.org/lua-l.html), [irc channel](http://lua-users.org/wiki/IrcChannel), or [forum](https://luaforum.com).
|
||||
|
||||
|
||||
## References
|
||||
|
||||
I was excited to learn Lua so I could make games
|
||||
with the <a href="http://love2d.org/">Love 2D game engine</a>. That's the why.
|
||||
|
||||
I started with <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
|
||||
I started with <a href="https://ebens.me/post/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
|
||||
Next I read the official <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a> book.
|
||||
That's the how.
|
||||
|
||||
|
@ -3,12 +3,13 @@ language: markdown
|
||||
contributors:
|
||||
- ["Dan Turkel", "http://danturkel.com/"]
|
||||
- ["Jacob Ward", "http://github.com/JacobCWard/"]
|
||||
- ["Tomáš Hartman", "https://github.com/tomas-hartman"]
|
||||
filename: markdown.md
|
||||
---
|
||||
|
||||
|
||||
Markdown was created by John Gruber in 2004. It's meant to be an easy to read
|
||||
and write syntax which converts easily to HTML (and now many other formats as
|
||||
Markdown was created by John Gruber in 2004. It's meant to be an easy to read
|
||||
and write syntax which converts easily to HTML (and now many other formats as
|
||||
well).
|
||||
|
||||
Markdown also varies in implementation from one parser to a next. This
|
||||
@ -17,16 +18,25 @@ specific to a certain parser.
|
||||
|
||||
- [HTML Elements](#html-elements)
|
||||
- [Headings](#headings)
|
||||
- [Simple Text Styles](#simple-text-styles)
|
||||
- [Simple text styles](#simple-text-styles)
|
||||
- [Paragraphs](#paragraphs)
|
||||
- [Lists](#lists)
|
||||
- [Code blocks](#code-blocks)
|
||||
- [Horizontal rule](#horizontal-rule)
|
||||
- [Links](#links)
|
||||
- [Table of contents](#table-of-contents)
|
||||
- [Images](#images)
|
||||
- [Miscellany](#miscellany)
|
||||
- [Auto-links](#auto-links)
|
||||
- [Auto-links for emails](#auto-links-for-emails)
|
||||
- [Escaping characters](#escaping-characters)
|
||||
- [Keyboard keys](#keyboard-keys)
|
||||
- [Tables](#tables)
|
||||
- [Markdownlint](#markdownlint)
|
||||
- [Further reading](#further-reading)
|
||||
|
||||
## HTML Elements
|
||||
|
||||
Markdown is a superset of HTML, so any HTML file is valid Markdown.
|
||||
|
||||
```md
|
||||
@ -49,6 +59,7 @@ text you want to be in that element by a number of hashes (#).
|
||||
##### This is an <h5>
|
||||
###### This is an <h6>
|
||||
```
|
||||
|
||||
Markdown also provides us with two alternative ways of indicating h1 and h2.
|
||||
|
||||
```md
|
||||
@ -81,6 +92,7 @@ GitHub, we also have strikethrough:
|
||||
```md
|
||||
~~This text is rendered with strikethrough.~~
|
||||
```
|
||||
|
||||
## Paragraphs
|
||||
|
||||
Paragraphs are a one or multiple adjacent lines of text separated by one or
|
||||
@ -119,6 +131,7 @@ Block quotes are easy and done with the > character.
|
||||
```
|
||||
|
||||
## Lists
|
||||
|
||||
Unordered lists can be made using asterisks, pluses, or hyphens.
|
||||
|
||||
```md
|
||||
@ -155,6 +168,7 @@ render the numbers in order, but this may not be a good idea.
|
||||
1. Item two
|
||||
1. Item three
|
||||
```
|
||||
|
||||
(This renders the same as the above example)
|
||||
|
||||
You can also use sublists
|
||||
@ -217,7 +231,7 @@ highlighting of the language you specify after the \`\`\`
|
||||
|
||||
## Horizontal rule
|
||||
|
||||
Horizontal rules (`<hr/>`) are easily added with three or more asterisks or
|
||||
Horizontal rules (`<hr/>`) are easily added with three or more asterisks or
|
||||
hyphens, with or without spaces.
|
||||
|
||||
```md
|
||||
@ -235,11 +249,13 @@ the text to display in hard brackets [] followed by the url in parentheses ()
|
||||
```md
|
||||
[Click me!](http://test.com/)
|
||||
```
|
||||
|
||||
You can also add a link title using quotes inside the parentheses.
|
||||
|
||||
```md
|
||||
[Click me!](http://test.com/ "Link to Test.com")
|
||||
```
|
||||
|
||||
Relative paths work too.
|
||||
|
||||
```md
|
||||
@ -266,7 +282,27 @@ There is also "implicit naming" which lets you use the link text as the id.
|
||||
|
||||
But it's not that commonly used.
|
||||
|
||||
### Table of contents
|
||||
|
||||
Some Markdown flavors even make use of the combination of lists, links and
|
||||
headings in order to create tables of contents. In this case, heading titles in
|
||||
lowercase are prepended with hash (`#`) and are used as link ids. Should the
|
||||
heading have multiple words, they will be connected with a hyphen (`-`), that
|
||||
also replaces some special characters. (Some other special characters are
|
||||
omitted though.)
|
||||
|
||||
```md
|
||||
- [Heading](#heading)
|
||||
- [Another heading](#another-heading)
|
||||
- [Chapter](#chapter)
|
||||
- [Subchapter <h3 />](#subchapter-h3-)
|
||||
```
|
||||
|
||||
Nontheless, this is a feature that might not be working in all Markdown
|
||||
implementations the same way.
|
||||
|
||||
## Images
|
||||
|
||||
Images are done the same way as links but with an exclamation point in front!
|
||||
|
||||
```md
|
||||
@ -278,7 +314,9 @@ And reference style works as expected.
|
||||
<pre><code class="highlight">![<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>]
|
||||
|
||||
[<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"if you need a title, it's here"</span></code></pre>
|
||||
|
||||
## Miscellany
|
||||
|
||||
### Auto-links
|
||||
|
||||
```md
|
||||
@ -301,13 +339,14 @@ in italics, so I do this: \*this text surrounded by asterisks\*.
|
||||
|
||||
### Keyboard keys
|
||||
|
||||
In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard
|
||||
In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard
|
||||
keys.
|
||||
|
||||
```md
|
||||
Your computer crashed? Try sending a
|
||||
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
||||
```
|
||||
|
||||
### Tables
|
||||
|
||||
Tables are only available in GitHub Flavored Markdown and are slightly
|
||||
@ -319,6 +358,7 @@ cumbersome, but if you really want it:
|
||||
| Left-aligned | Centered | Right-aligned |
|
||||
| blah | blah | blah |
|
||||
```
|
||||
|
||||
or, for the same results
|
||||
|
||||
```md
|
||||
@ -327,5 +367,20 @@ Col 1 | Col2 | Col3
|
||||
Ugh this is so ugly | make it | stop
|
||||
```
|
||||
|
||||
## Markdownlint
|
||||
|
||||
In order to simplify work with Markdown and to unify its coding style,
|
||||
`Markdownlint` has been created. This tool is available also as a plugin for
|
||||
some IDEs and can be used as an utility to ensure validity and readability of
|
||||
Markdown.
|
||||
|
||||
---
|
||||
|
||||
## Further reading
|
||||
|
||||
For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
||||
|
||||
If you want to learn more on some major Markdown flavors' features, see:
|
||||
|
||||
- [GitHub flavored Markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
|
||||
- [GitLab flavored Markdown](https://docs.gitlab.com/ee/user/markdown.html)
|
||||
|
@ -28,7 +28,7 @@ this
|
||||
% Two percent signs denote the start of a new code section
|
||||
% Individual code sections can be run by moving the cursor to the section followed by
|
||||
% either clicking the "Run Section" button
|
||||
% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (OS X)
|
||||
% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (macOS)
|
||||
|
||||
%% This is the start of a code section
|
||||
% One way of using sections is to separate expensive but unchanging start-up code like loading data
|
||||
|
@ -193,7 +193,7 @@ gateways and routers.
|
||||
# Let $s0 = a, $s1 = b, $s2 = c, $v0 = return register
|
||||
ble $s0, $s1, a_LTE_b # if(a <= b) branch(a_LTE_b)
|
||||
ble $s0, $s2, max_C # if(a > b && a <=c) branch(max_C)
|
||||
move $v0, $s1 # else [a > b && a > c] max = a
|
||||
move $v0, $s0 # else [a > b && a > c] max = a
|
||||
j done # Jump to the end of the program
|
||||
|
||||
a_LTE_b: # Label for when a <= b
|
||||
@ -242,7 +242,7 @@ gateways and routers.
|
||||
## FUNCTIONS ##
|
||||
_functions:
|
||||
# Functions are callable procedures that can accept arguments and return
|
||||
values all denoted with labels, like above
|
||||
# values all denoted with labels, like above
|
||||
|
||||
main: # Programs begin with main func
|
||||
jal return_1 # jal will store the current PC in $ra
|
||||
@ -293,7 +293,7 @@ gateways and routers.
|
||||
|
||||
fact_done:
|
||||
lw $s0, ($sp)
|
||||
lw $ra, ($sp) # Restore the PC
|
||||
lw $ra, 4($sp) # Restore the PC
|
||||
addi $sp, $sp, 8
|
||||
|
||||
jr $ra
|
||||
@ -357,7 +357,7 @@ gateways and routers.
|
||||
li $t1, 5 # Length of the list
|
||||
|
||||
loop:
|
||||
bgt $t0, $t1, end_loop
|
||||
bge $t0, $t1, end_loop
|
||||
|
||||
lw $a0, ($s0)
|
||||
li $v0, 1
|
||||
|
405
mongodb.html.markdown
Normal file
@ -0,0 +1,405 @@
|
||||
---
|
||||
language: MongoDB
|
||||
filename: mongo.js
|
||||
contributors:
|
||||
- ["Raj Piskala", "https://www.rajpiskala.ml/"]
|
||||
---
|
||||
|
||||
MongoDB is a NoSQL document database for high volume data storage.
|
||||
|
||||
MongoDB uses collections and documents for its storage. Each document consists
|
||||
of key-value pairs using JSON-like syntax, similar to a dictionary or JavaScript
|
||||
object.
|
||||
|
||||
Likewise, as MongoDB is a NoSQL database, it uses its own query language, Mongo
|
||||
Query Language (MQL) which uses JSON for querying.
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Installation
|
||||
|
||||
MongoDB can either be installed locally following the instructions
|
||||
[here](https://docs.mongodb.com/manual/installation/) or you can create a
|
||||
remotely-hosted free 512 MB cluster
|
||||
[here](https://www.mongodb.com/cloud/atlas/register). Links to videos with
|
||||
instructions on setup are at the bottom.
|
||||
|
||||
This tutorial assumes that you have the MongoDB Shell from
|
||||
[here](https://www.mongodb.com/try/download/shell). You can also download the
|
||||
graphical tool, MongoDB Compass, down below from the same link.
|
||||
|
||||
### Components
|
||||
|
||||
After installing MongoDB, you will notice there are multiple command line tools.
|
||||
The three most important of which are:
|
||||
|
||||
- `mongod` - The database server which is responsible for managing data and
|
||||
handling queries
|
||||
- `mongos` - The sharding router, which is needed if data will be distributed
|
||||
across multiple machines
|
||||
- `mongo` - The database shell (using JavaScript) through which we can configure
|
||||
our database
|
||||
|
||||
Usually we start the `mongod` process and then use a separate terminal with
|
||||
`mongo` to access and modify our collections.
|
||||
|
||||
### JSON & BSON
|
||||
|
||||
While queries in MongoDB are made using a JSON-like\* format, MongoDB stores its
|
||||
documents internally in the Binary JSON (BSON format). BSON is not human
|
||||
readable like JSON as it's a binary encoding. However, this allows for end users
|
||||
to have access to more types than regular JSON, such as an integer or float
|
||||
type. Many other types, such as regular expressions, dates, or raw binary are
|
||||
supported too.
|
||||
|
||||
[Here](https://docs.mongodb.com/manual/reference/bson-types/) is the full list
|
||||
of all types that are supported.
|
||||
|
||||
- We refer JSON-like to mean JSON but with these extended types. For example,
|
||||
you can make queries directly with a regular expression or timestamp in
|
||||
MongoDB and you can receive data that has those types too.
|
||||
|
||||
```js
|
||||
/////////////////////////////////////////////////////////
|
||||
/////////////////// Getting Started /////////////////////
|
||||
/////////////////////////////////////////////////////////
|
||||
|
||||
// Start up the mongo database server
|
||||
// NOTE - You will need to do this in a separate terminal as the process will
|
||||
// take over the terminal. You may want to use the --fork option
|
||||
mongod // --fork
|
||||
|
||||
// Connecting to a remote Mongo server
|
||||
// mongo "mongodb+srv://host.ip.address/admin" --username your-username
|
||||
|
||||
// Mongoshell has a proper JavaScript interpreter built in
|
||||
3 + 2 // 5
|
||||
|
||||
// Show available databases
|
||||
// MongoDB comes with the following databases built-in: admin, config, local
|
||||
show dbs
|
||||
|
||||
// Switch to a new database (pre-existing or about to exist)
|
||||
// NOTE: There is no "create" command for a database in MongoDB.
|
||||
// The database is created upon data being inserted into a collection
|
||||
use employees
|
||||
|
||||
// Create a new collection
|
||||
// NOTE: Inserting a document will implicitly create a collection anyways,
|
||||
// so this is not required
|
||||
db.createCollection('engineers')
|
||||
db.createCollection('doctors')
|
||||
|
||||
// See what collections exist under employees
|
||||
show collections
|
||||
|
||||
/////////////////////////////////////////////////////////
|
||||
// Basic Create/Read/Update/Delete (CRUD) Operations: ///
|
||||
/////////////////////////////////////////////////////////
|
||||
|
||||
/////////////// Insert (Create) /////////////////////////
|
||||
|
||||
// Insert one employee into the database
|
||||
// Each insertion returns acknowledged true or false
|
||||
// Every document has a unique _id value assigned to it automatically
|
||||
db.engineers.insertOne({ name: "Jane Doe", age: 21, gender: 'Female' })
|
||||
|
||||
// Insert a list of employees into the `engineers` collection
|
||||
// Can insert as an array of objects
|
||||
db.engineers.insert([
|
||||
{ name: "Foo Bar", age: 25, gender: 'Male' },
|
||||
{ name: "Baz Qux", age: 27, gender: 'Other' },
|
||||
])
|
||||
|
||||
// MongoDB does not enforce a schema or structure for objects
|
||||
// Insert an empty object into the `engineers` collection
|
||||
db.engineers.insertOne({})
|
||||
|
||||
// Fields are optional and do not have to match rest of documents
|
||||
db.engineers.insertOne({ name: "Your Name", gender: "Male" })
|
||||
|
||||
// Types can vary and are preserved on insertion
|
||||
// This can require additional validation in some languages to prevent problems
|
||||
db.engineers.insert({ name: ['Foo', 'Bar'], age: 3.14, gender: true })
|
||||
|
||||
// Objects or arrays can be nested inside a document
|
||||
db.engineers.insertOne({
|
||||
name: "Your Name",
|
||||
gender: "Female",
|
||||
skilledIn: [
|
||||
"MongoDB",
|
||||
"NoSQL",
|
||||
],
|
||||
"date-of-birth": {
|
||||
"date": 1993-07-20T09:44:18.674Z,
|
||||
"age": 26
|
||||
},
|
||||
})
|
||||
|
||||
// We can override the _id field
|
||||
// Works fine
|
||||
db.engineers.insertOne({
|
||||
_id: 1,
|
||||
name: "An Engineer",
|
||||
age: 25,
|
||||
gender: "Female",
|
||||
})
|
||||
|
||||
// Be careful, as _id must ALWAYS be unique for the collection otherwise
|
||||
// the insertion will fail
|
||||
// Fails with a WriteError indicating _id is a duplicate value
|
||||
db.engineers.insertOne({
|
||||
_id: 1,
|
||||
name: "Another Engineer",
|
||||
age: 25,
|
||||
gender: "Male",
|
||||
})
|
||||
|
||||
// Works fine as this is a different collection
|
||||
db.doctors.insertOne({
|
||||
_id: 1,
|
||||
name: "Some Doctor",
|
||||
age: 26,
|
||||
gender: "Other",
|
||||
})
|
||||
|
||||
/////////////////// Find (Read) ////////////////////////
|
||||
// Queries are in the form of db.collectionName.find(<filter>)
|
||||
// Where <filter> is an object
|
||||
|
||||
// Show everything in our database so far, limited to a
|
||||
// maximum of 20 documents at a time
|
||||
// Press i to iterate this cursor to the next 20 documents
|
||||
db.engineers.find({})
|
||||
|
||||
// We can pretty print the result of any find() query
|
||||
db.engineers.find({}).pretty()
|
||||
|
||||
// MongoDB queries take in a JS object and search for documents with matching
|
||||
// key-value pairs
|
||||
// Returns the first document matching query
|
||||
// NOTE: Order of insertion is not preserved in the database, output can vary
|
||||
db.engineers.findOne({ name: 'Foo Bar' })
|
||||
|
||||
// Returns all documents with the matching key-value properties as a cursor
|
||||
// (which can be converted to an array)
|
||||
db.engineers.find({ age: 25 })
|
||||
|
||||
// Type matters when it comes to queries
|
||||
// Returns nothing as all ages above are integer type
|
||||
db.engineers.find({ age: '25' })
|
||||
|
||||
// find() supports nested objects and arrays just like create()
|
||||
db.engineers.find({
|
||||
name: "Your Name",
|
||||
gender: "Female",
|
||||
skilledIn: [
|
||||
"MongoDB",
|
||||
"NoSQL",
|
||||
],
|
||||
"date-of-birth": {
|
||||
"date": 1993-07-20T09:44:18.674Z,
|
||||
"age": 26
|
||||
},
|
||||
})
|
||||
|
||||
///////////////////////// Update ////////////////////////
|
||||
// Queries are in the form of db.collectionName.update(<filter>, <update>)
|
||||
// NOTE: <update> will always use the $set operator.
|
||||
// Several operators are covered later on in the tutorial.
|
||||
|
||||
// We can update a single object
|
||||
db.engineers.updateOne({ name: 'Foo Bar' }, { $set: { name: 'John Doe', age: 100 }})
|
||||
|
||||
// Or update many objects at the same time
|
||||
db.engineers.update({ age: 25 }, { $set: { age: 26 }})
|
||||
|
||||
// We can use { upsert: true } if we would like it to insert if the document doesn't already exist,
|
||||
// or to update if it does
|
||||
// Returns matched, upserted, modified count
|
||||
db.engineers.update({ name: 'Foo Baz' },
|
||||
{ $set:
|
||||
{
|
||||
age: 26,
|
||||
gender: 'Other'
|
||||
}
|
||||
},
|
||||
{ upsert: true }
|
||||
)
|
||||
|
||||
/////////////////////// Delete /////////////////////////
|
||||
// Queries are in the form of db.collectionName.find(<filter>)
|
||||
|
||||
// Delete first document matching query, always returns deletedCount
|
||||
db.engineers.deleteOne({ name: 'Foo Baz' })
|
||||
|
||||
// Delete many documents at once
|
||||
db.engineers.deleteMany({ gender: 'Male' })
|
||||
|
||||
// NOTE: There are two methods db.collection.removeOne(<filter>) and
|
||||
// db.collection.removeMany(<filter>) that also delete objects but have a
|
||||
// slightly different return value.
|
||||
// They are not included here as they have been deprecated in the NodeJS driver.
|
||||
|
||||
/////////////////////////////////////////////////////////
|
||||
//////////////////// Operators //////////////////////////
|
||||
/////////////////////////////////////////////////////////
|
||||
|
||||
// Operators in MongoDB have a $ prefix. For this tutorial, we are only looking
|
||||
// at comparison and logical operators, but there are many other types of
|
||||
// operators
|
||||
|
||||
//////////////// Comparison Operators ///////////////////
|
||||
|
||||
// Find all greater than or greater than equal to some condition
|
||||
db.engineers.find({ $gt: { age: 25 }})
|
||||
db.engineers.find({ $gte: { age: 25 }})
|
||||
|
||||
// Find all less than or less than equal to some condition
|
||||
db.engineers.find({ $lte: { age: 25 }})
|
||||
db.engineers.find({ $lte: { age: 25 }})
|
||||
|
||||
// Find all equal or not equal to
|
||||
// Note: the $eq operator is added implicitly in most queries
|
||||
db.engineers.find({ $eq: { age: 25 }})
|
||||
db.engineers.find({ $ne: { age: 25 }})
|
||||
|
||||
// Find all that match any element in the array
|
||||
db.engineers.find({ age: ${ in: [ 20, 23, 24, 25 ]}})
|
||||
|
||||
//////////////// Logical Operators ///////////////////
|
||||
|
||||
// Join two query clauses together
|
||||
// NOTE: MongoDB does this implicitly for most queries
|
||||
db.engineers.find({ $and: [
|
||||
gender: 'Female',
|
||||
age: {
|
||||
$gte: 18
|
||||
}
|
||||
]})
|
||||
|
||||
// Match either query condition
|
||||
db.engineers.find({ $or: [
|
||||
gender: 'Female',
|
||||
age: {
|
||||
$gte: 18
|
||||
}
|
||||
]})
|
||||
|
||||
// Negates the query
|
||||
db.engineers.find({ $not: {
|
||||
gender: 'Female'
|
||||
}})
|
||||
|
||||
// Must match none of the query conditions
|
||||
db.engineers.find({ $nor [
|
||||
gender: 'Female,
|
||||
age: {
|
||||
$gte: 18
|
||||
}
|
||||
]})
|
||||
|
||||
/////////////////////////////////////////////////////////
|
||||
//////////////// Database Operations: ///////////////////
|
||||
/////////////////////////////////////////////////////////
|
||||
|
||||
// Delete (drop) the employees database
|
||||
// THIS WILL DELETE ALL DOCUMENTS IN THE DATABASE!
|
||||
db.dropDatabase()
|
||||
|
||||
// Create a new database with some data
|
||||
use example
|
||||
db.test.insertOne({ name: "Testing data, please ignore!", type: "Test" })
|
||||
|
||||
// Quit Mongo shell
|
||||
exit
|
||||
|
||||
// Import/export database as BSON:
|
||||
|
||||
// Mongodump to export data as BSON for all databases
|
||||
// Exported data is found in under "MongoDB Database Tools/bin/dump"
|
||||
// NOTE: If the command is not found, navigate to "MongoDB Database Tools/bin"
|
||||
// and use the executable from there mongodump
|
||||
|
||||
// Mongorestore to restore data from BSON
|
||||
mongorestore dump
|
||||
|
||||
// Import/export database as JSON:
|
||||
// Mongoexport to export data as JSON for all databases
|
||||
mongoexport --collection=example
|
||||
|
||||
// Mongoimport to export data as JSON for all databases
|
||||
mongoimport --collection=example
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
|
||||
### Setup Videos
|
||||
|
||||
- [Install MongoDB - Windows 10](https://www.youtube.com/watch?v=85A6m1soKww)
|
||||
- [Install MongoDB - Mac](https://www.youtube.com/watch?v=DX15WbKidXY)
|
||||
- [Install MongoDB - Linux
|
||||
(Ubuntu)](https://www.youtube.com/watch?v=wD_2pojFWoE)
|
||||
|
||||
### Input Validation
|
||||
|
||||
From the examples above, if input validation or structure is a concern, I would
|
||||
take a look at the following ORMs:
|
||||
|
||||
- [Mongoose (Node.js)](https://mongoosejs.com/docs/) - Input validation through
|
||||
schemas that support types, required values, minimum and maximum values.
|
||||
- [MongoEngine (Python)](http://mongoengine.org/) - Similar to Mongoose, but I
|
||||
found it somewhat limited in my experience
|
||||
- [MongoKit (Python)](https://github.com/namlook/mongokit) - Another great
|
||||
alternative to MongoEngine that I find easier to use than MongoEngine
|
||||
|
||||
For statically strongly typed languages (e.g. Java, C++, Rust), input validation
|
||||
usually doesn't require a library as they define types and structure at compile
|
||||
time.
|
||||
|
||||
### Resources
|
||||
|
||||
If you have the time to spare, I would strongly recommend the courses on
|
||||
[MongoDB University](https://university.mongodb.com/). They're by MongoDB
|
||||
themselves and go into much more detail while still being concise. They're a mix
|
||||
of videos and quiz questions and this was how I gained my knowledge of MongoDB.
|
||||
|
||||
I would recommend the following video series for learning MongoDB:
|
||||
|
||||
- [MongoDB Crash Course - Traversy
|
||||
Media](https://www.youtube.com/watch?v=-56x56UppqQ)
|
||||
- [MongoDB Tutorial for Beginners -
|
||||
Amigoscode](https://www.youtube.com/watch?v=Www6cTUymCY)
|
||||
|
||||
Language-specific ones that I used before:
|
||||
|
||||
- [Build A REST API With Node.js, Express, & MongoDB - Web Dev
|
||||
Simplified](https://www.youtube.com/watch?v=fgTGADljAeg)
|
||||
- [MongoDB with Python Crash Course - Tutorial for Beginners -
|
||||
FreeCodeCamp](https://www.youtube.com/watch?v=E-1xI85Zog8)
|
||||
- [How to Use MongoDB with Java - Random
|
||||
Coder](https://www.youtube.com/watch?v=reYPUvu2Giw)
|
||||
- [An Introduction to Using MongoDB with Rust -
|
||||
MongoDB](https://www.youtube.com/watch?v=qFlftfLGwPM)
|
||||
|
||||
Most of the information above was cross-referenced with the [MongoDB
|
||||
docs](https://www.mongodb.com/). Here are the docs for each section:
|
||||
|
||||
- [MongoDB Types](https://docs.mongodb.com/manual/reference/bson-types/) - List
|
||||
of all types that MongoDB supports natively
|
||||
- [MongoDB Operators](https://docs.mongodb.com/manual/reference/operator/) -
|
||||
List of operators MongoDB supports natively
|
||||
- [MongoDB CRUD](https://docs.mongodb.com/manual/reference/command/nav-crud/) -
|
||||
Commands for create, read, update, delete
|
||||
|
||||
If you've been enjoying MongoDB so far and want to explore intermediate
|
||||
features, I would look at
|
||||
[aggregation](https://docs.mongodb.com/manual/reference/command/nav-aggregation/),
|
||||
[indexing](https://docs.mongodb.com/manual/indexes/), and
|
||||
[sharding](https://docs.mongodb.com/manual/sharding/).
|
||||
|
||||
- Aggregation - useful for creating advanced queries to be executed by the
|
||||
database
|
||||
- Idexing allows for caching, which allows for much faster execution of queries
|
||||
- Sharding allows for horizontal data scaling and distribution between multiple
|
||||
machines.
|
@ -17,7 +17,7 @@ translators:
|
||||
lang: ms-my
|
||||
---
|
||||
|
||||
Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan Mac OS X. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell.
|
||||
Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan macOS. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell.
|
||||
|
||||
[Baca lebih lanjut di sini.](http://www.gnu.org/software/bash/manual/bashref.html)
|
||||
|
||||
|
@ -373,5 +373,8 @@ with builtins; [
|
||||
* [James Fisher - Nix by example - Part 1: The Nix expression language]
|
||||
(https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55)
|
||||
|
||||
* [Susan Potter - Nix Cookbook - Nix By Example]
|
||||
(https://ops.functionalalgebra.com/nix-by-example/)
|
||||
|
||||
* [Rommel Martinez - A Gentle Introduction to the Nix Family]
|
||||
(https://ebzzry.io/en/nix/#nix)
|
||||
(https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
|
||||
|
@ -17,7 +17,7 @@ lang: nl-nl
|
||||
filename: LearnBash-nl.sh
|
||||
---
|
||||
|
||||
Bash is de naam van de unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en Mac OS X.
|
||||
Bash is de naam van de unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en macOS.
|
||||
Bijna alle voorbeelden hieronder kunnen deel uitmaken van een shell script of kunnen uitgevoerd worden in de shell.
|
||||
|
||||
[Lees er meer over hier.](http://www.gnu.org/software/bash/manual/bashref.html)
|
||||
|
@ -17,7 +17,7 @@ lang: no-nb
|
||||
---
|
||||
Bash er navnet på unix skallet, som også var distribuert som skallet for GNU
|
||||
operativsystemet og som standard skall på de fleste Linux distribusjoner og
|
||||
Mac OS X.
|
||||
macOS.
|
||||
|
||||
[Les mer her.](http://www.gnu.org/software/bash/manual/bashref.html)
|
||||
|
||||
|
@ -9,7 +9,7 @@ contributors:
|
||||
filename: LearnObjectiveC.m
|
||||
---
|
||||
|
||||
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
|
||||
Objective-C is the main programming language used by Apple for the macOS and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
|
||||
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
|
||||
|
||||
```objective-c
|
||||
|
@ -201,7 +201,7 @@ let (~/) x = 1.0 /. x ;;
|
||||
|
||||
(* Lists are enclosed in square brackets, items are separated by
|
||||
semicolons. *)
|
||||
let my_list = [1; 2; 3] ;;
|
||||
let my_list = [1; 2; 3] ;; (* Has type "int list". *)
|
||||
|
||||
(* Tuples are (optionally) enclosed in parentheses, items are separated
|
||||
by commas. *)
|
||||
|
@ -138,7 +138,6 @@ cv2.destroyAllWindows()
|
||||
* An up-to-date language reference can be found at [https://opencv.org](https://opencv.org)
|
||||
* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV](https://en.wikipedia.org/wiki/OpenCV)
|
||||
* Good OpenCv Tutorials
|
||||
* [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html)
|
||||
* [https://realpython.com/python-opencv-color-spaces](https://realpython.com/python-opencv-color-spaces)
|
||||
* [https://pyimagesearch.com](https://pyimagesearch.com)
|
||||
* [https://www.learnopencv.com](https://www.learnopencv.com)
|
||||
|
@ -12,7 +12,7 @@ source : [wikipedia](https://en.wikipedia.org/wiki/Pascal_(programming_language)
|
||||
|
||||
|
||||
|
||||
to compile and run a pascal program you could use a free pascal compiler. [Download Here](https://www.freepascal.org/)
|
||||
To compile and run a pascal program you could use a free pascal compiler. [Download Here](https://www.freepascal.org/)
|
||||
|
||||
```pascal
|
||||
//Anatomy of a Pascal Program
|
||||
@ -23,7 +23,7 @@ to compile and run a pascal program you could use a free pascal compiler. [Downl
|
||||
}
|
||||
|
||||
//name of the program
|
||||
program learn_pascal; //<-- dont forget a semicolon
|
||||
program learn_pascal; //<-- don't forget a semicolon
|
||||
|
||||
const
|
||||
{
|
||||
@ -31,7 +31,7 @@ const
|
||||
}
|
||||
type
|
||||
{
|
||||
this is where you should delcare a custom
|
||||
this is where you should declare custom
|
||||
data-types
|
||||
}
|
||||
var
|
||||
@ -44,11 +44,11 @@ begin
|
||||
{
|
||||
area to declare your instruction
|
||||
}
|
||||
end. // End of a main program area should required a "." symbol
|
||||
end. // End of a main program area should require a "." symbol
|
||||
```
|
||||
|
||||
```pascal
|
||||
//declaring variable
|
||||
//When declaring variables
|
||||
//you can do this
|
||||
var a:integer;
|
||||
var b:integer;
|
||||
@ -62,7 +62,7 @@ var a,b : integer;
|
||||
|
||||
```pascal
|
||||
program Learn_More;
|
||||
//Lets learn about data types and their operations
|
||||
//Let's learn about data types and their operations
|
||||
|
||||
const
|
||||
PI = 3.141592654;
|
||||
|
@ -217,6 +217,12 @@ open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
|
||||
my $line = <$in>;
|
||||
my @lines = <$in>;
|
||||
|
||||
# You can iterate through the lines in a file one at a time with a while loop:
|
||||
|
||||
while (my $line = <$in>) {
|
||||
print "Found apples\n" if $line =~ m/apples/;
|
||||
}
|
||||
|
||||
# You can write to an open filehandle using the standard "print"
|
||||
# function.
|
||||
|
||||
|
337
phel.html.markdown
Normal file
@ -0,0 +1,337 @@
|
||||
---
|
||||
language: phel
|
||||
filename: learnphel.phel
|
||||
contributors:
|
||||
- ["Chemaclass", "https://github.com/Chemaclass"]
|
||||
---
|
||||
|
||||
[Phel](https://phel-lang.org/) is a functional programming language that compiles to PHP.
|
||||
It is a dialect of Lisp inspired by Clojure and Janet.
|
||||
|
||||
## Features
|
||||
- Built on PHP's ecosystem
|
||||
- Good error reporting
|
||||
- Persistent Datastructures (Lists, Vectors, Maps and Sets)
|
||||
- Macros
|
||||
- Recursive functions
|
||||
- Powerful but simple Syntax
|
||||
- REPL
|
||||
|
||||
```newlisp
|
||||
# Comments begin with a # character and continue until the end of the line. There are no multi-line comments.
|
||||
|
||||
# Phel is written in "forms", which are just
|
||||
# lists of things inside parentheses, separated by whitespace.
|
||||
|
||||
# The first call in a file should be ns, to set the namespace
|
||||
(ns learn-phel)
|
||||
|
||||
# More basic examples:
|
||||
|
||||
# str will create a string out of all its arguments
|
||||
(str "Hello" " " "World") #=> "Hello World"
|
||||
|
||||
# Math is straightforward
|
||||
(+ 1 1) #=> 2
|
||||
(- 2 1) #=> 1
|
||||
(* 1 2) #=> 2
|
||||
(/ 2 1) #=> 2
|
||||
|
||||
# Equality is =
|
||||
(= 1 1) #=> true
|
||||
(= 2 1) #=> false
|
||||
|
||||
# You need not for logic, too
|
||||
(not true) #=> false
|
||||
|
||||
# Nesting forms works as you expect
|
||||
(+ 1 (- 3 2)) # = 1 + (3 - 2) => 2
|
||||
|
||||
# Phel inherits PHP under the hood, so it can use native PHP (functions and classes) without
|
||||
# any additional cost by using the `php/` prefix to all PHP native functions.
|
||||
|
||||
# Types
|
||||
#############
|
||||
|
||||
# Booleans are similar as the native PHP ones
|
||||
|
||||
nil
|
||||
true
|
||||
false
|
||||
|
||||
# Symbols are used to name functions and variables in Phel
|
||||
# For example: symbol, snake_case_symbol, my-module/my-function
|
||||
|
||||
# Keywords are like symbols that begin with a colon character. However, they are used as constants rather than a name for something.
|
||||
|
||||
:keyword
|
||||
:0x0x0x
|
||||
::
|
||||
|
||||
# Numbers in Phel are equivalent to numbers in PHP
|
||||
|
||||
1337 # integer
|
||||
+1337 # positive integer
|
||||
-1337 # negative integer
|
||||
|
||||
1.234 # float
|
||||
+1.234 # positive float
|
||||
-1.234 # negative float
|
||||
1.2e3 # float
|
||||
7E-10 # float
|
||||
|
||||
# Strings are surrounded by double quotes. They almost work the same as PHP double quoted strings.
|
||||
# A string can be written in multiple lines. The line break character is then ignored by the reader.
|
||||
|
||||
"hello world"
|
||||
|
||||
"this is\na\nstring"
|
||||
|
||||
"this
|
||||
is
|
||||
a
|
||||
string."
|
||||
|
||||
"use backslack to escape \" string"
|
||||
|
||||
"the dollar must not be escaped: $ or $abc just works"
|
||||
|
||||
|
||||
# Collections & Sequences
|
||||
#############
|
||||
|
||||
# Lists are linked-list data structures, while vectors are array-backed
|
||||
(type '(1 2 3)) #=> :list
|
||||
(type [1 2 3]) #=> :vector
|
||||
|
||||
# A list would be written as just (1 2 3), but we have to quote
|
||||
# it to stop the reader thinking it's a function.
|
||||
# Also, (list 1 2 3) is the same as '(1 2 3)
|
||||
|
||||
# You can produce a (non-lazy) sequence between a range.
|
||||
(range 1 10 2) #=> (range from to step)
|
||||
(take 4 (range 10))
|
||||
|
||||
# Use cons to add an item to the beginning of a list
|
||||
(cons 4 '(1 2 3)) #=> (4 1 2 3)
|
||||
|
||||
# Use push to add, and put to replace an item in a vector
|
||||
(push [1 2 3] 4) #=> (1 2 3 4)
|
||||
(put [1 2 3] 1 4) #=> (1 4 3)
|
||||
|
||||
# Use concat to add lists or vectors together
|
||||
(concat [1 2] '(3 4)) #=> [1 2 3 4]
|
||||
|
||||
# Use filter, map to interact with collections
|
||||
(map inc [1 2 3]) #=> [2 3 4]
|
||||
(filter even? [1 2 3]) #=> [2]
|
||||
|
||||
# Use reduce to reduce them. The initial-value is mandatory
|
||||
(reduce + 0 [1 2 3 4])
|
||||
#=> (+ (+ (+ 1 2) 3) 4)
|
||||
#=> 10
|
||||
|
||||
(reduce push [] '(3 2 1))
|
||||
#=> (push (push (push [] 3) 2) 1)
|
||||
#=> [3 2 1]
|
||||
|
||||
# Functions
|
||||
#############
|
||||
|
||||
# Use fn to create new functions
|
||||
# A function always returns its last statement
|
||||
(fn [] "Hello World") #=> <function>
|
||||
|
||||
# You need extra parens to call it
|
||||
((fn [] "Hello World")) #=> "Hello World"
|
||||
|
||||
# You can bind a value to a symbol using def for definition
|
||||
(def x 1)
|
||||
x #=> 1
|
||||
|
||||
# Variables provide a way to manage mutable state
|
||||
(def foo (var 10)) # Define a variable with value 10
|
||||
|
||||
# Assign a function to a definition
|
||||
(def hello-world (fn [] "Hello World"))
|
||||
(hello-world) #=> "Hello World"
|
||||
|
||||
# You can shorten this process by using defn
|
||||
(defn hello-world [] "Hello World")
|
||||
|
||||
# The [] is the list of arguments for the function
|
||||
(defn hello [name]
|
||||
(str "Hello " name))
|
||||
(hello "Jens") #=> "Hello Jens"
|
||||
|
||||
# You can also use this shorthand to create functions
|
||||
(def hello2 |(str "Hello " $1))
|
||||
(hello2 "Anna") #=> "Hello Anna"
|
||||
|
||||
# Functions can pack extra arguments up in a seq for you
|
||||
(defn count-args [& args]
|
||||
(str "You passed " (count args) " args: " args))
|
||||
(count-args 1 2 3) #=> "You passed 3 args: @[1 2 3]"
|
||||
|
||||
# You can mix regular and packed arguments
|
||||
(defn hello-count [name & args]
|
||||
(str "Hello " name ", you passed " (count args) " extra args"))
|
||||
(hello-count "Jesus" 1 2) #=> "Hello Jesus, you passed 2 extra args"
|
||||
|
||||
|
||||
# Maps
|
||||
#############
|
||||
|
||||
# Hash maps have faster lookups but don't retain key order
|
||||
(type {:a 1 :b 2 :c 3}) #=> :hash-map
|
||||
(type (hash-map :a 1 :b 2 :c 3)) #=> :hash-map
|
||||
|
||||
# Maps can use any hashable type as a key, but usually keywords are best
|
||||
# Keywords are like strings with some efficiency bonuses and they start with `:`
|
||||
(type :a) #=> :keyword
|
||||
|
||||
(def stringmap {"a" 1 "b" 2 "c" 3})
|
||||
stringmap #=> {"a" 1 "b" 2 "c" 3}
|
||||
|
||||
(def keymap {:a 1 :b 2 :c 3})
|
||||
keymap #=> {:a 1 :c 3 :b 2}
|
||||
|
||||
# Retrieve a value from a map by calling it as a function
|
||||
(stringmap "a") #=> 1
|
||||
(keymap :a) #=> 1
|
||||
|
||||
# Keywords can be used to retrieve their value from a map, too!
|
||||
(:b keymap) #=> 2
|
||||
|
||||
# Don't try this with strings
|
||||
# ("a" stringmap)
|
||||
# ...Exception: Call to undefined function a()
|
||||
|
||||
# Retrieving a non-present key returns nil
|
||||
(stringmap "d") #=> nil
|
||||
|
||||
# Use put to add new keys to hash-maps
|
||||
(def newkeymap (put keymap :d 4))
|
||||
newkeymap #=> {:a 1 :b 2 :c 3 :d 4}
|
||||
|
||||
# But remember, phel types are immutable!
|
||||
keymap #=> {:a 1 :b 2 :c 3}
|
||||
|
||||
# Use unset to remove keys
|
||||
(unset keymap :a) #=> {:b 2 :c 3}
|
||||
|
||||
# Sets
|
||||
#############
|
||||
|
||||
# A Set contains unique values in random order
|
||||
|
||||
(type (set 1 2 3)) #=> :set
|
||||
(set 1 2 3 1 2 3 3 2 1 3 2 1) #=> (set 1 2 3)
|
||||
|
||||
# Add a member with push
|
||||
(push (set 1 2 3) 4) #=> (set 1 2 3 4)
|
||||
|
||||
# Remove one with unset
|
||||
(unset (set 1 2 3) 1) #=> (set 2 3)
|
||||
|
||||
# Test for existence by using the set as a function
|
||||
((set 1 2 3) 1) #=> 1
|
||||
((set 1 2 3) 4) #=> nil
|
||||
|
||||
# There are more functions like: count, union, intersection, difference, etc
|
||||
|
||||
|
||||
# Useful forms
|
||||
#############
|
||||
|
||||
# `If` conditionals in phel are special forms
|
||||
(if false "a" "b") #=> "b"
|
||||
(if false "a") #=> nil
|
||||
|
||||
# Use let to create temporary bindings
|
||||
(let [a 1 b 2]
|
||||
(> a b)) #=> false
|
||||
|
||||
# Group statements together with do
|
||||
(do
|
||||
(print "Hello")
|
||||
"World") #=> "World" (prints "Hello")
|
||||
|
||||
# Functions have an implicit do
|
||||
(defn print-and-say-hello [name]
|
||||
(print "Saying hello to " name)
|
||||
(str "Hello " name))
|
||||
(print-and-say-hello "Jeff") #=> "Hello Jeff" (prints "Saying hello to Jeff")
|
||||
|
||||
# So does let
|
||||
(let [name "Urkel"]
|
||||
(print "Saying hello to " name)
|
||||
(str "Hello " name)) #=> "Hello Urkel" (prints "Saying hello to Urkel")
|
||||
|
||||
# Use the threading macros (-> and ->>) to express transformations of
|
||||
# data more clearly.
|
||||
|
||||
# The "Thread-first" macro (->) inserts into each form the result of
|
||||
# the previous, as the first argument (second item)
|
||||
(->
|
||||
{:a 1 :b 2}
|
||||
(put :c 3) #=> (put {:a 1 :b 2} :c 3)
|
||||
(unset :b)) #=> (unset (put {:a 1 :b 2} :c 3) :b)
|
||||
|
||||
|
||||
# The double arrow does the same thing, but inserts the result of
|
||||
# each line at the *end* of the form. This is useful for collection
|
||||
# operations in particular:
|
||||
(->>
|
||||
(range 10)
|
||||
(map inc) #=> (map inc (range 10))
|
||||
(filter odd?)) #=> (filter odd? (map inc (range 10)))
|
||||
# Result: [1 3 5 7 9]
|
||||
|
||||
|
||||
# When you are in a situation where you want more freedom as where to
|
||||
# put the result of previous data transformations in an
|
||||
# expression, you can use the as-> macro. With it, you can assign a
|
||||
# specific name to transformations' output and use it as a
|
||||
# placeholder in your chained expressions:
|
||||
|
||||
(as-> [1 2 3] input
|
||||
(map inc input) #=> You can use last transform's output at the last position
|
||||
(get input 2) #=> and at the second position, in the same expression
|
||||
(push [4 5 6] input 8 9 10)) #=> or in the middle !
|
||||
# Result: [4 5 6 4 8 9 10]
|
||||
|
||||
# PHP
|
||||
#################
|
||||
|
||||
# PHP has a huge and useful standard library, and you're able to use
|
||||
# all native functions with the prefix `php/`.
|
||||
(php/+ 1 2 3)
|
||||
|
||||
# With :use you can use different namespaces. Similar as `use` in PHP
|
||||
(ns my\module
|
||||
(:use \DateTimeImmutable))
|
||||
|
||||
# You can import functions from other phel files with :require
|
||||
(ns my\module
|
||||
(:require phel\test :refer [deftest is]))
|
||||
|
||||
# Use the class name with a "php/new" to make a new instance
|
||||
(php/new \DateTime) # <a date-time object>
|
||||
|
||||
# Use php/-> to call methods of an object
|
||||
(def d (php/new \DateTime))
|
||||
(php/-> d (getTimestamp)) # <a timestamp>
|
||||
|
||||
# you can do it in one line too
|
||||
(php/-> (php/new \DateTime) (getTimestamp))
|
||||
|
||||
# Use php/:: to call static methods
|
||||
(php/:: \DateTimeImmutable ATOM) # <a timestamp>
|
||||
```
|
||||
|
||||
### Further Reading
|
||||
|
||||
This is far from exhaustive, but hopefully it's enough to get you on your feet.
|
||||
|
||||
Read the full documentation in the website: [https://phel-lang.org/](https://phel-lang.org/documentation/getting-started/)
|
@ -591,6 +591,12 @@ echo $my_class->property; // => "public"
|
||||
echo $my_class->instanceProp; // => "An instance property"
|
||||
$my_class->myMethod(); // => "MyClass"
|
||||
|
||||
// Nullsafe operators since PHP 8
|
||||
// You can use this when you're unsure if the abstraction of $my_class contains has a property/method
|
||||
// it can be used in conjunction with the nullish coalesce operator to ensure proper value
|
||||
echo $my_class->invalid_property // An error is thrown
|
||||
echo $my_class?->invalid_property // => NULL
|
||||
echo $my_class?->invalid_property ?? "public" // => "public"
|
||||
|
||||
// Extend classes using "extends"
|
||||
class MyOtherClass extends MyClass
|
||||
|
@ -17,7 +17,7 @@ lang: pt-br
|
||||
Tutorial de shell em português
|
||||
|
||||
Bash é o nome do shell do Unix, que também é distribuído como shell do sistema
|
||||
operacional GNU e como shell padrão para Linux e Mac OS X. Praticamente todos
|
||||
operacional GNU e como shell padrão para Linux e macOS. Praticamente todos
|
||||
os exemplos abaixo podem fazer parte de um shell script e pode ser executados
|
||||
diretamente no shell.
|
||||
|
||||
|
@ -290,9 +290,9 @@ A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em t
|
||||
|
||||
## Leitura adicional
|
||||
|
||||
* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, eo Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
|
||||
* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, e o Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
|
||||
* [Selecionando elementos usando atributos](https://css-tricks.com/almanac/selectors/a/attribute/)
|
||||
* [QuirksMode CSS](http://www.quirksmode.org/css/)
|
||||
* [Z-Index - O empilhamento context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
|
||||
* [SASS](http://sass-lang.com/) e [menos](http://lesscss.org/) para CSS pré-processamento
|
||||
* [SASS](http://sass-lang.com/) e [Less](http://lesscss.org/) para CSS pré-processamento
|
||||
* [CSS-Tricks](https://css-tricks.com)
|
||||
|
786
pt-br/r-pt.html.markdown
Normal file
@ -0,0 +1,786 @@
|
||||
---
|
||||
language: R
|
||||
contributors:
|
||||
- ["e99n09", "http://github.com/e99n09"]
|
||||
- ["isomorphismes", "http://twitter.com/isomorphisms"]
|
||||
- ["kalinn", "http://github.com/kalinn"]
|
||||
translators:
|
||||
- ["Marcel Ribeiro-Dantas", "http://github.com/mribeirodantas"]
|
||||
lang: pt-br
|
||||
filename: learnr.r
|
||||
---
|
||||
|
||||
R é uma linguagem de programação estatística. Ela tem muitas bibliotecas para carregar e limpar conjuntos de dados, executar análises estatísticas e produzir gráficos. Você também pode executar comandos do `R` dentro de um documento LaTeX.
|
||||
|
||||
```r
|
||||
|
||||
# Comentários começam com o símbolo de Cerquilha, também conhecido como
|
||||
# jogo da velha
|
||||
|
||||
# Não existe um símbolo especial para comentários em várias linhas
|
||||
# mas você pode escrever várias linhas de comentários adicionando a
|
||||
# cerquilha (#) ao início de cada uma delas.
|
||||
|
||||
# No Windows e Linux, você pode usar CTRL-ENTER para executar uma linha.
|
||||
# No MacOS, o equivalente é COMMAND-ENTER
|
||||
|
||||
|
||||
|
||||
#############################################################################
|
||||
# Coisas que você pode fazer sem entender nada sobre programação
|
||||
#############################################################################
|
||||
|
||||
# Nesta seção, mostramos algumas das coisas legais que você pode fazer em
|
||||
# R sem entender nada de programação. Não se preocupe em entender tudo o
|
||||
# que o código faz. Apenas aproveite!
|
||||
|
||||
data() # navegue pelos conjuntos de dados pré-carregados
|
||||
data(rivers) # carregue este: "Comprimentos dos principais rios norte-americanos"
|
||||
ls() # observe que "rivers" apareceu na área de trabalho (workspace)
|
||||
head(rivers) # dê uma espiada no conjunto de dados
|
||||
# 735 320 325 392 524 450
|
||||
|
||||
length(rivers) # quantos rios foram medidos?
|
||||
# 141
|
||||
summary(rivers) # consulte um sumário de estatísticas básicas
|
||||
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
||||
# 135.0 310.0 425.0 591.2 680.0 3710.0
|
||||
|
||||
# faça um diagrama de ramos e folhas (uma visualização de dados semelhante a um histograma)
|
||||
stem(rivers)
|
||||
|
||||
# A vírgula está 2 dígito(s) à direita do símbolo |
|
||||
#
|
||||
# 0 | 4
|
||||
# 2 | 011223334555566667778888899900001111223333344455555666688888999
|
||||
# 4 | 111222333445566779001233344567
|
||||
# 6 | 000112233578012234468
|
||||
# 8 | 045790018
|
||||
# 10 | 04507
|
||||
# 12 | 1471
|
||||
# 14 | 56
|
||||
# 16 | 7
|
||||
# 18 | 9
|
||||
# 20 |
|
||||
# 22 | 25
|
||||
# 24 | 3
|
||||
# 26 |
|
||||
# 28 |
|
||||
# 30 |
|
||||
# 32 |
|
||||
# 34 |
|
||||
# 36 | 1
|
||||
|
||||
stem(log(rivers)) # Observe que os dados não são normais nem log-normais!
|
||||
# Tome isso, fundamentalistas da curva normal!
|
||||
|
||||
# O ponto decimal está 1 dígito(s) à esquerda do símbolo |
|
||||
#
|
||||
# 48 | 1
|
||||
# 50 |
|
||||
# 52 | 15578
|
||||
# 54 | 44571222466689
|
||||
# 56 | 023334677000124455789
|
||||
# 58 | 00122366666999933445777
|
||||
# 60 | 122445567800133459
|
||||
# 62 | 112666799035
|
||||
# 64 | 00011334581257889
|
||||
# 66 | 003683579
|
||||
# 68 | 0019156
|
||||
# 70 | 079357
|
||||
# 72 | 89
|
||||
# 74 | 84
|
||||
# 76 | 56
|
||||
# 78 | 4
|
||||
# 80 |
|
||||
# 82 | 2
|
||||
|
||||
# faça um histograma:
|
||||
hist(rivers, col="#333333", border="white", breaks=25) # brinque com estes parâmetros
|
||||
hist(log(rivers), col="#333333", border="white", breaks=25) # você fará mais gráficos mais tarde
|
||||
|
||||
# Aqui está outro conjunto de dados que vem pré-carregado. O R tem toneladas deles.
|
||||
data(discoveries)
|
||||
plot(discoveries, col="#333333", lwd=3, xlab="Ano",
|
||||
main="Número de descobertas importantes por ano")
|
||||
plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Ano",
|
||||
main="Número de descobertas importantes por ano")
|
||||
|
||||
# Em vez de deixar a ordenação padrão (por ano),
|
||||
# também podemos ordenar para ver o que é mais comum:
|
||||
sort(discoveries)
|
||||
# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
|
||||
# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3
|
||||
# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
|
||||
# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
|
||||
|
||||
stem(discoveries, scale=2)
|
||||
#
|
||||
# O ponto decimal está no símbolo |
|
||||
#
|
||||
# 0 | 000000000
|
||||
# 1 | 000000000000
|
||||
# 2 | 00000000000000000000000000
|
||||
# 3 | 00000000000000000000
|
||||
# 4 | 000000000000
|
||||
# 5 | 0000000
|
||||
# 6 | 000000
|
||||
# 7 | 0000
|
||||
# 8 | 0
|
||||
# 9 | 0
|
||||
# 10 | 0
|
||||
# 11 |
|
||||
# 12 | 0
|
||||
|
||||
max(discoveries)
|
||||
# 12
|
||||
summary(discoveries)
|
||||
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
||||
# 0.0 2.0 3.0 3.1 4.0 12.0
|
||||
|
||||
# Role um dado algumas vezes
|
||||
round(runif(7, min=.5, max=6.5))
|
||||
# 1 4 6 1 4 6 4
|
||||
# Seus números serão diferentes dos meus, a menos que definamos a mesma semente aleatória com o set.seed
|
||||
|
||||
# Obtenha 9 números de forma aleatória a partir de uma distribuição normal
|
||||
rnorm(9)
|
||||
# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271
|
||||
# [7] -0.59975593 0.57629164 1.08455362
|
||||
|
||||
|
||||
|
||||
##################################################
|
||||
# Tipos de dados e aritmética básica
|
||||
##################################################
|
||||
|
||||
# Agora para a parte orientada a programação do tutorial.
|
||||
# Nesta seção você conhecerá os tipos de dados importantes do R:
|
||||
# integers, numerics, characters, logicals, e factors.
|
||||
# Existem outros, mas estes são o mínimo que você precisa para
|
||||
# iniciar.
|
||||
|
||||
# INTEGERS
|
||||
# Os inteiros de armazenamento longo são escritos com L
|
||||
5L # 5
|
||||
class(5L) # "integer"
|
||||
# (Experimente ?class para obter mais informações sobre a função class().)
|
||||
# Em R, todo e qualquer valor, como 5L, é considerado um vetor de comprimento 1
|
||||
length(5L) # 1
|
||||
# Você pode ter um vetor inteiro com comprimento > 1 também:
|
||||
c(4L, 5L, 8L, 3L) # 4 5 8 3
|
||||
length(c(4L, 5L, 8L, 3L)) # 4
|
||||
class(c(4L, 5L, 8L, 3L)) # "integer"
|
||||
|
||||
# NUMERICS
|
||||
# Um "numeric" é um número de ponto flutuante de precisão dupla
|
||||
5 # 5
|
||||
class(5) # "numeric"
|
||||
# De novo, tudo em R é um vetor;
|
||||
# você pode fazer um vetor numérico com mais de um elemento
|
||||
c(3,3,3,2,2,1) # 3 3 3 2 2 1
|
||||
# Você também pode usar a notação científica
|
||||
5e4 # 50000
|
||||
6.02e23 # Número de Avogadro
|
||||
1.6e-35 # Comprimento de Planck
|
||||
# Você também pode ter números infinitamente grandes ou pequenos
|
||||
class(Inf) # "numeric"
|
||||
class(-Inf) # "numeric"
|
||||
# Você pode usar "Inf", por exemplo, em integrate(dnorm, 3, Inf)
|
||||
# isso evita as tabelas de escores-Z.
|
||||
|
||||
# ARITMÉTICA BÁSICA
|
||||
# Você pode fazer aritmética com números
|
||||
# Fazer aritmética com uma mistura de números inteiros (integers) e com
|
||||
# ponto flutuante (numeric) resulta em um numeric
|
||||
10L + 66L # 76 # integer mais integer resulta em integer
|
||||
53.2 - 4 # 49.2 # numeric menos numeric resulta em numeric
|
||||
2.0 * 2L # 4 # numeric vezes integer resulta em numeric
|
||||
3L / 4 # 0.75 # integer dividido por numeric resulta em numeric
|
||||
3 %% 2 # 1 # o resto de dois numeric é um outro numeric
|
||||
# Aritmética ilegal produz um "não-é-um-número" (do inglês Not-a-Number):
|
||||
0 / 0 # NaN
|
||||
class(NaN) # "numeric"
|
||||
# Você pode fazer aritmética em dois vetores com comprimento maior que 1,
|
||||
# desde que o comprimento do vetor maior seja um múltiplo inteiro do menor
|
||||
c(1,2,3) + c(1,2,3) # 2 4 6
|
||||
# Como um único número é um vetor de comprimento um, escalares são aplicados
|
||||
# elemento a elemento com relação a vetores
|
||||
(4 * c(1,2,3) - 2) / 2 # 1 3 5
|
||||
# Exceto para escalares, tenha cuidado ao realizar aritmética em vetores com
|
||||
# comprimentos diferentes. Embora possa ser feito,
|
||||
c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
|
||||
# ter comprimentos iguais é uma prática melhor e mais fácil de ler
|
||||
c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
|
||||
|
||||
# CHARACTERS
|
||||
# Não há diferença entre strings e caracteres em R
|
||||
"Horatio" # "Horatio"
|
||||
class("Horatio") # "character"
|
||||
class('H') # "character"
|
||||
# São ambos vetores de caracteres de comprimento 1
|
||||
# Aqui está um mais longo:
|
||||
c('alef', 'bet', 'gimmel', 'dalet', 'he')
|
||||
# "alef" "bet" "gimmel" "dalet" "he"
|
||||
length(c("Call","me","Ishmael")) # 3
|
||||
# Você pode utilizar expressões regulares (regex) em vetores de caracteres:
|
||||
substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
|
||||
gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
|
||||
# R tem vários vetores de caracteres embutidos:
|
||||
letters
|
||||
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
|
||||
# [20] "t" "u" "v" "w" "x" "y" "z"
|
||||
month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
|
||||
|
||||
# LOGICALS
|
||||
# Em R, um "logical" é um booleano
|
||||
class(TRUE) # "logical"
|
||||
class(FALSE) # "logical"
|
||||
# O comportamento deles é normal
|
||||
TRUE == TRUE # TRUE
|
||||
TRUE == FALSE # FALSE
|
||||
FALSE != FALSE # FALSE
|
||||
FALSE != TRUE # TRUE
|
||||
# Dados ausentes (NA) são logical, também
|
||||
class(NA) # "logical"
|
||||
# Use | e & para operações lógicas.
|
||||
# OR
|
||||
TRUE | FALSE # TRUE
|
||||
# AND
|
||||
TRUE & FALSE # FALSE
|
||||
# Aplicar | e & a vetores retorna operações lógicas elemento a elemento
|
||||
c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
|
||||
c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
|
||||
# Você pode testar se x é TRUE
|
||||
isTRUE(TRUE) # TRUE
|
||||
# Aqui obtemos um vetor logical com muitos elementos:
|
||||
c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
|
||||
c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
|
||||
|
||||
# FACTORS
|
||||
# A classe factor é para dados categóricos
|
||||
# Os fatores podem ser ordenados (como as avaliações de crianças) ou
|
||||
# não ordenados (como as cores)
|
||||
factor(c("azul", "azul", "verde", NA, "azul"))
|
||||
# azul azul verde <NA> azul
|
||||
# Levels: azul verde
|
||||
# Os "levels" são os valores que os dados categóricos podem assumir
|
||||
# Observe que os dados ausentes não entram nos levels
|
||||
levels(factor(c("verde", "verde", "azul", NA, "azul"))) # "azul" "verde"
|
||||
# Se um vetor de factor tem comprimento 1, seus levels também terão comprimento 1
|
||||
length(factor("green")) # 1
|
||||
length(levels(factor("green"))) # 1
|
||||
# Os fatores são comumente vistos em data frames, uma estrutura de dados que abordaremos
|
||||
# mais tarde
|
||||
data(infert) # "Infertilidade após aborto espontâneo e induzido"
|
||||
levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
|
||||
|
||||
# NULL
|
||||
# "NULL" é um valor estranho; use-o para "apagar" um vetor
|
||||
class(NULL) # NULL
|
||||
parakeet = c("bico", "penas", "asas", "olhos")
|
||||
parakeet
|
||||
# [1] "bico" "penas" "asas" "olhos"
|
||||
parakeet <- NULL
|
||||
parakeet
|
||||
# NULL
|
||||
|
||||
# COERÇÃO DE TIPO
|
||||
# Coerção de tipo é quando você força um valor a assumir um tipo diferente
|
||||
as.character(c(6, 8)) # "6" "8"
|
||||
as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
|
||||
# Se você colocar elementos de diferentes tipos em um vetor, coerções estranhas acontecem:
|
||||
c(TRUE, 4) # 1 4
|
||||
c("cachorro", TRUE, 4) # "cachorro" "TRUE" "4"
|
||||
as.numeric("Bilbo")
|
||||
# [1] NA
|
||||
# Warning message:
|
||||
# NAs introduced by coercion
|
||||
|
||||
# Observe também: esses são apenas os tipos de dados básicos
|
||||
# Existem muitos outros tipos de dados, como datas, séries temporais, etc.
|
||||
|
||||
|
||||
|
||||
##################################################
|
||||
# Variáveis, laços, expressões condicionais
|
||||
##################################################
|
||||
|
||||
# Uma variável é como uma caixa na qual você armazena um valor para uso posterior.
|
||||
# Chamamos isso de "atribuir" o valor à variável.
|
||||
# Ter variáveis nos permite escrever laços, funções e instruções com condição
|
||||
|
||||
# VARIÁVEIS
|
||||
# Existem muitas maneiras de atribuir valores:
|
||||
x = 5 # é possível fazer assim
|
||||
y <- "1" # mas é preferível fazer assim
|
||||
TRUE -> z # isso funciona, mas é estranho
|
||||
|
||||
# LAÇOS
|
||||
# Nós temos laços com for
|
||||
for (i in 1:4) {
|
||||
print(i)
|
||||
}
|
||||
# [1] 1
|
||||
# [1] 2
|
||||
# [1] 3
|
||||
# [1] 4
|
||||
# Nós temos laços com while
|
||||
a <- 10
|
||||
while (a > 4) {
|
||||
cat(a, "...", sep = "")
|
||||
a <- a - 1
|
||||
}
|
||||
# 10...9...8...7...6...5...
|
||||
# Tenha em mente que os laços for e while são executados lentamente em R
|
||||
# Operações em vetores inteiros (por exemplo, uma linha inteira, uma coluna inteira)
|
||||
# ou funções do tipo apply() (discutiremos mais tarde) são mais indicadas
|
||||
|
||||
# IF/ELSE
|
||||
# Novamente, bastante padrão
|
||||
if (4 > 3) {
|
||||
print("4 é maior que 3")
|
||||
} else {
|
||||
print("4 não é maior que 3")
|
||||
}
|
||||
# [1] "4 é maior que 3"
|
||||
|
||||
# FUNÇÕES
|
||||
# Definidas assim:
|
||||
jiggle <- function(x) {
|
||||
x = x + rnorm(1, sd=.1) # adicione um pouco de ruído (controlado)
|
||||
return(x)
|
||||
}
|
||||
# Chamada como qualquer outra função R:
|
||||
jiggle(5) # 5±ε. Após set.seed(2716057), jiggle(5)==5.005043
|
||||
|
||||
|
||||
|
||||
###########################################################################
|
||||
# Estruturas de dados: Vetores, matrizes, data frames e arranjos (arrays)
|
||||
###########################################################################
|
||||
|
||||
# UNIDIMENSIONAL
|
||||
|
||||
# Vamos começar do início, e com algo que você já sabe: vetores.
|
||||
vec <- c(8, 9, 10, 11)
|
||||
vec # 8 9 10 11
|
||||
# Consultamos elementos específicos utilizando colchetes
|
||||
# (Observe que R começa a contar a partir de 1)
|
||||
vec[1] # 8
|
||||
letters[18] # "r"
|
||||
LETTERS[13] # "M"
|
||||
month.name[9] # "September"
|
||||
c(6, 8, 7, 5, 3, 0, 9)[3] # 7
|
||||
# Também podemos pesquisar os índices de componentes específicos,
|
||||
which(vec %% 2 == 0) # 1 3
|
||||
# pegue apenas as primeiras ou últimas entradas no vetor,
|
||||
head(vec, 1) # 8
|
||||
tail(vec, 2) # 10 11
|
||||
# ou descubra se um determinado valor está no vetor
|
||||
any(vec == 10) # TRUE
|
||||
# Se um índice for além do comprimento de um vetor, você obterá NA:
|
||||
vec[6] # NA
|
||||
# Você pode encontrar o comprimento do seu vetor com length()
|
||||
length(vec) # 4
|
||||
# Você pode realizar operações em vetores inteiros ou subconjuntos de vetores
|
||||
vec * 4 # 32 36 40 44
|
||||
vec[2:3] * 5 # 45 50
|
||||
any(vec[2:3] == 8) # FALSE
|
||||
# e R tem muitas funções internas para sumarizar vetores
|
||||
mean(vec) # 9.5
|
||||
var(vec) # 1.666667
|
||||
sd(vec) # 1.290994
|
||||
max(vec) # 11
|
||||
min(vec) # 8
|
||||
sum(vec) # 38
|
||||
# Mais alguns recursos embutidos:
|
||||
5:15 # 5 6 7 8 9 10 11 12 13 14 15
|
||||
seq(from=0, to=31337, by=1337)
|
||||
# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
|
||||
# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
|
||||
|
||||
# BIDIMENSIONAL (ELEMENTOS DA MESMA CLASSE)
|
||||
|
||||
# Você pode fazer uma matriz com entradas do mesmo tipo assim:
|
||||
mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
|
||||
mat
|
||||
# [,1] [,2]
|
||||
# [1,] 1 4
|
||||
# [2,] 2 5
|
||||
# [3,] 3 6
|
||||
# Ao contrário de um vetor, a classe de uma matriz é "matrix" independente do que ela contém
|
||||
class(mat) # "matrix"
|
||||
# Consulte a primeira linha
|
||||
mat[1,] # 1 4
|
||||
# Execute uma operação na primeira coluna
|
||||
3 * mat[,1] # 3 6 9
|
||||
# Consulte uma célula específica
|
||||
mat[3,2] # 6
|
||||
|
||||
# Transponha toda a matriz
|
||||
t(mat)
|
||||
# [,1] [,2] [,3]
|
||||
# [1,] 1 2 3
|
||||
# [2,] 4 5 6
|
||||
|
||||
# Multiplicação de matrizes
|
||||
mat %*% t(mat)
|
||||
# [,1] [,2] [,3]
|
||||
# [1,] 17 22 27
|
||||
# [2,] 22 29 36
|
||||
# [3,] 27 36 45
|
||||
|
||||
# cbind() une vetores em colunas para formar uma matriz
|
||||
mat2 <- cbind(1:4, c("cachorro", "gato", "passaro", "cachorro"))
|
||||
mat2
|
||||
# [,1] [,2]
|
||||
# [1,] "1" "cachorro"
|
||||
# [2,] "2" "gato"
|
||||
# [3,] "3" "passaro"
|
||||
# [4,] "4" "cachorro"
|
||||
class(mat2) # matrix
|
||||
# Mais uma vez, observe o que aconteceu!
|
||||
# Como as matrizes devem conter todas as entradas da mesma classe,
|
||||
# tudo foi convertido para a classe character
|
||||
c(class(mat2[,1]), class(mat2[,2]))
|
||||
|
||||
# rbind() une vetores linha a linha para fazer uma matriz
|
||||
mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
|
||||
mat3
|
||||
# [,1] [,2] [,3] [,4]
|
||||
# [1,] 1 2 4 5
|
||||
# [2,] 6 7 0 4
|
||||
# Ah, tudo da mesma classe. Sem coerções. Muito melhor.
|
||||
|
||||
# BIDIMENSIONAL (CLASSES DIFERENTES)
|
||||
|
||||
# Para colunas de tipos diferentes, use um data frame
|
||||
# Esta estrutura de dados é tão útil para programação estatística,
|
||||
# que uma versão dela foi adicionada ao Python através do pacote "pandas".
|
||||
|
||||
estudantes <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
|
||||
c(3,2,2,1,0,-1),
|
||||
c("H", "G", "G", "R", "S", "G"))
|
||||
names(estudantes) <- c("nome", "ano", "casa") # nomeie as colunas
|
||||
class(estudantes) # "data.frame"
|
||||
estudantes
|
||||
# nome ano casa
|
||||
# 1 Cedric 3 H
|
||||
# 2 Fred 2 G
|
||||
# 3 George 2 G
|
||||
# 4 Cho 1 R
|
||||
# 5 Draco 0 S
|
||||
# 6 Ginny -1 G
|
||||
class(estudantes$ano) # "numeric"
|
||||
class(estudantes[,3]) # "factor"
|
||||
# encontre as dimensões
|
||||
nrow(estudantes) # 6
|
||||
ncol(estudantes) # 3
|
||||
dim(estudantes) # 6 3
|
||||
# A função data.frame() converte vetores de caracteres em vetores de fator
|
||||
# por padrão; desligue isso definindo stringsAsFactors = FALSE quando
|
||||
# você criar um data frame
|
||||
?data.frame
|
||||
|
||||
# Existem muitas maneiras particulares de consultar partes de um data frame,
|
||||
# todas sutilmente diferentes
|
||||
estudantes$ano # 3 2 2 1 0 -1
|
||||
estudantes[,2] # 3 2 2 1 0 -1
|
||||
estudantes[,"ano"] # 3 2 2 1 0 -1
|
||||
|
||||
# Uma versão extendida da estrutura data.frame é a data.table
|
||||
# Se você estiver trabalhando com dados enormes ou em painel, ou precisar mesclar
|
||||
# alguns conjuntos de dados, data.table pode ser uma boa escolha. Aqui está um tour
|
||||
# relâmpago:
|
||||
install.packages("data.table") # baixe o pacote a partir do CRAN
|
||||
require(data.table) # carregue ele
|
||||
estudantes <- as.data.table(estudantes)
|
||||
estudantes # observe a saída ligeiramente diferente
|
||||
# nome ano casa
|
||||
# 1: Cedric 3 H
|
||||
# 2: Fred 2 G
|
||||
# 3: George 2 G
|
||||
# 4: Cho 1 R
|
||||
# 5: Draco 0 S
|
||||
# 6: Ginny -1 G
|
||||
estudantes[nome=="Ginny"] # Consulte estudantes com o nome == "Ginny"
|
||||
# nome ano casa
|
||||
# 1: Ginny -1 G
|
||||
estudantes[ano==2] # Consulte estudantes com o ano == 2
|
||||
# nome ano casa
|
||||
# 1: Fred 2 G
|
||||
# 2: George 2 G
|
||||
# data.table facilita a fusão de dois conjuntos de dados
|
||||
# vamos fazer outro data.table para mesclar com os alunos
|
||||
fundadores <- data.table(casa=c("G","H","R","S"),
|
||||
fundador=c("Godric","Helga","Rowena","Salazar"))
|
||||
fundadores
|
||||
# casa fundador
|
||||
# 1: G Godric
|
||||
# 2: H Helga
|
||||
# 3: R Rowena
|
||||
# 4: S Salazar
|
||||
setkey(estudantes, casa)
|
||||
setkey(fundadores, casa)
|
||||
estudantes <- fundadores[estudantes] # mescle os dois conjuntos de dados com base na "casa"
|
||||
setnames(estudantes, c("casa","nomeFundadorCasa","nomeEstudante","ano"))
|
||||
estudantes[,order(c("nome","ano","casa","nomeFundadorCasa")), with=F]
|
||||
# nomeEstudante ano casa nomeFundadorCasa
|
||||
# 1: Fred 2 G Godric
|
||||
# 2: George 2 G Godric
|
||||
# 3: Ginny -1 G Godric
|
||||
# 4: Cedric 3 H Helga
|
||||
# 5: Cho 1 R Rowena
|
||||
# 6: Draco 0 S Salazar
|
||||
|
||||
# O data.table torna as tabelas de sumário fáceis
|
||||
estudantes[,sum(ano),by=casa]
|
||||
# casa V1
|
||||
# 1: G 3
|
||||
# 2: H 3
|
||||
# 3: R 1
|
||||
# 4: S 0
|
||||
|
||||
# Para remover uma coluna de um data.frame ou data.table,
|
||||
# atribua a ela o valor NULL
|
||||
estudantes$nomeFundadorCasa <- NULL
|
||||
estudantes
|
||||
# nomeEstudante ano casa
|
||||
# 1: Fred 2 G
|
||||
# 2: George 2 G
|
||||
# 3: Ginny -1 G
|
||||
# 4: Cedric 3 H
|
||||
# 5: Cho 1 R
|
||||
# 6: Draco 0 S
|
||||
|
||||
# Remova uma linha consultando parte dos dados
|
||||
# Usando data.table:
|
||||
estudantes[nomeEstudante != "Draco"]
|
||||
# casa estudanteNome ano
|
||||
# 1: G Fred 2
|
||||
# 2: G George 2
|
||||
# 3: G Ginny -1
|
||||
# 4: H Cedric 3
|
||||
# 5: R Cho 1
|
||||
# Usando data.frame:
|
||||
estudantes <- as.data.frame(estudantes)
|
||||
estudantes[estudantes$casa != "G",]
|
||||
# casa nomeFundadorCasa nomeEstudante ano
|
||||
# 4 H Helga Cedric 3
|
||||
# 5 R Rowena Cho 1
|
||||
# 6 S Salazar Draco 0
|
||||
|
||||
# MULTIDIMENSIONAL (TODOS OS ELEMENTOS DE UM TIPO)
|
||||
|
||||
# Arranjos (arrays) criam tabelas n-dimensionais
|
||||
# Todos os elementos devem ser do mesmo tipo
|
||||
# Você pode fazer uma tabela bidimensional (como uma matriz)
|
||||
array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
|
||||
# [,1] [,2] [,3] [,4]
|
||||
# [1,] 1 4 8 3
|
||||
# [2,] 2 5 9 6
|
||||
# Você pode usar array para fazer matrizes tridimensionais também
|
||||
array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
|
||||
# , , 1
|
||||
#
|
||||
# [,1] [,2]
|
||||
# [1,] 2 8
|
||||
# [2,] 300 9
|
||||
# [3,] 4 0
|
||||
#
|
||||
# , , 2
|
||||
#
|
||||
# [,1] [,2]
|
||||
# [1,] 5 66
|
||||
# [2,] 60 7
|
||||
# [3,] 0 847
|
||||
|
||||
# LISTAS (MULTIDIMENSIONAIS, POSSIVELMENTE IMPERFEITAS, DE DIFERENTES TIPOS)
|
||||
|
||||
# Finalmente, R tem listas (de vetores)
|
||||
lista1 <- list(tempo = 1:40)
|
||||
lista1$preco = c(rnorm(40,.5*lista1$tempo,4)) # aleatória
|
||||
lista1
|
||||
# Você pode obter itens na lista assim
|
||||
lista1$tempo # um modo
|
||||
lista1[["tempo"]] # um outro modo
|
||||
lista1[[1]] # e ainda um outro modo
|
||||
# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
||||
# [34] 34 35 36 37 38 39 40
|
||||
# Você pode obter itens de uma lista como qualquer outro vetor
|
||||
lista1$preco[4]
|
||||
|
||||
# Listas não são a estrutura de dados mais eficiente para se trabalhar em R;
|
||||
# a menos que você tenha um bom motivo, você deve se ater a data.frames
|
||||
# As listas geralmente são retornadas por funções que realizam regressões lineares
|
||||
|
||||
##################################################
|
||||
# A família de funções apply()
|
||||
##################################################
|
||||
|
||||
# Lembra de mat?
|
||||
mat
|
||||
# [,1] [,2]
|
||||
# [1,] 1 4
|
||||
# [2,] 2 5
|
||||
# [3,] 3 6
|
||||
# Use apply(X, MARGIN, FUN) para aplicar a função FUN a uma matriz X
|
||||
# sobre linhas (MARGIN = 1) ou colunas (MARGIN = 2)
|
||||
# Ou seja, R faz FUN para cada linha (ou coluna) de X, muito mais rápido que um
|
||||
# laço for ou while faria
|
||||
apply(mat, MAR = 2, jiggle)
|
||||
# [,1] [,2]
|
||||
# [1,] 3 15
|
||||
# [2,] 7 19
|
||||
# [3,] 11 23
|
||||
# Outras funções: ?lappy, ?sapply
|
||||
|
||||
# Não as deixe te intimidar; todos concordam que essas funções são bem confusas
|
||||
|
||||
# O pacote plyr visa substituir (e melhorar!) a família *apply().
|
||||
install.packages("plyr")
|
||||
require(plyr)
|
||||
?plyr
|
||||
|
||||
|
||||
|
||||
#########################
|
||||
# Carregando dados
|
||||
#########################
|
||||
|
||||
# "pets.csv" é um arquivo hospedado na internet
|
||||
# (mas também poderia tranquilamente ser um arquivo no seu computador)
|
||||
require(RCurl)
|
||||
pets <- read.csv(textConnection(getURL("https://learnxinyminutes.com/docs/pets.csv")))
|
||||
pets
|
||||
head(pets, 2) # primeiras duas linhas
|
||||
tail(pets, 1) # última linha
|
||||
|
||||
# Para salvar um data frame ou matriz como um arquivo .csv:
|
||||
write.csv(pets, "pets2.csv") # para criar um novo arquivo .csv
|
||||
# Define o diretório de trabalho com setwd(), confirme em qual você está com getwd()
|
||||
|
||||
# Experimente ?read.csv e ?write.csv para obter mais informações
|
||||
|
||||
|
||||
|
||||
#########################
|
||||
# Análise estatística
|
||||
#########################
|
||||
|
||||
# Regressão linear!
|
||||
modeloLinear <- lm(preco ~ tempo, data = lista1)
|
||||
modeloLinear # imprime na tela o resultado da regressão
|
||||
# Call:
|
||||
# lm(formula = preco ~ tempo, data = lista1)
|
||||
#
|
||||
# Coefficients:
|
||||
# (Intercept) tempo
|
||||
# 0.1453 0.4943
|
||||
summary(modeloLinear) # saída mais detalhada da regressão
|
||||
# Call:
|
||||
# lm(formula = preco ~ tempo, data = lista1)
|
||||
#
|
||||
# Residuals:
|
||||
# Min 1Q Median 3Q Max
|
||||
# -8.3134 -3.0131 -0.3606 2.8016 10.3992
|
||||
#
|
||||
# Coefficients:
|
||||
# Estimate Std. Error t value Pr(>|t|)
|
||||
# (Intercept) 0.14527 1.50084 0.097 0.923
|
||||
# tempo 0.49435 0.06379 7.749 2.44e-09 ***
|
||||
# ---
|
||||
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
|
||||
#
|
||||
# Residual standard error: 4.657 on 38 degrees of freedom
|
||||
# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022
|
||||
# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09
|
||||
coef(modeloLinear) # extrai os parâmetros estimados
|
||||
# (Intercept) tempo
|
||||
# 0.1452662 0.4943490
|
||||
summary(modeloLinear)$coefficients # um outro meio de extrair os resultados
|
||||
# Estimate Std. Error t value Pr(>|t|)
|
||||
# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
|
||||
# tempo 0.4943490 0.06379348 7.74920901 2.440008e-09
|
||||
summary(modeloLinear)$coefficients[,4] # the p-values
|
||||
# (Intercept) tempo
|
||||
# 9.234021e-01 2.440008e-09
|
||||
|
||||
# MODELOS LINEARES GERAIS
|
||||
# Regressão logística
|
||||
set.seed(1)
|
||||
lista1$sucesso = rbinom(length(lista1$tempo), 1, .5) # binário aleatório
|
||||
modeloLg <- glm(sucesso ~ tempo, data = lista1,
|
||||
family=binomial(link="logit"))
|
||||
modeloLg # imprime na tela o resultado da regressão logística
|
||||
# Call: glm(formula = sucesso ~ tempo,
|
||||
# family = binomial(link = "logit"), data = lista1)
|
||||
#
|
||||
# Coefficients:
|
||||
# (Intercept) tempo
|
||||
# 0.17018 -0.01321
|
||||
#
|
||||
# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual
|
||||
# Null Deviance: 55.35
|
||||
# Residual Deviance: 55.12 AIC: 59.12
|
||||
summary(modeloLg) # saída mais detalhada da regressão
|
||||
# Call:
|
||||
# glm(formula = sucesso ~ tempo,
|
||||
# family = binomial(link = "logit"), data = lista1)
|
||||
|
||||
# Deviance Residuals:
|
||||
# Min 1Q Median 3Q Max
|
||||
# -1.245 -1.118 -1.035 1.202 1.327
|
||||
#
|
||||
# Coefficients:
|
||||
# Estimate Std. Error z value Pr(>|z|)
|
||||
# (Intercept) 0.17018 0.64621 0.263 0.792
|
||||
# tempo -0.01321 0.02757 -0.479 0.632
|
||||
#
|
||||
# (Dispersion parameter for binomial family taken to be 1)
|
||||
#
|
||||
# Null deviance: 55.352 on 39 degrees of freedom
|
||||
# Residual deviance: 55.121 on 38 degrees of freedom
|
||||
# AIC: 59.121
|
||||
#
|
||||
# Number of Fisher Scoring iterations: 3
|
||||
|
||||
|
||||
#########################
|
||||
# Gráficos
|
||||
#########################
|
||||
|
||||
# FUNÇÕES DE PLOTAGEM INTEGRADAS
|
||||
# Gráficos de dispersão!
|
||||
plot(lista1$tempo, lista1$preco, main = "dados falsos")
|
||||
# Trace a linha de regressão em um gráfico existente!
|
||||
abline(modeloLinear, col = "red")
|
||||
# Obtenha uma variedade de diagnósticos legais
|
||||
plot(modeloLinear)
|
||||
# Histogramas!
|
||||
hist(rpois(n = 10000, lambda = 5), col = "thistle")
|
||||
# Gráficos de barras!
|
||||
barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
|
||||
|
||||
# GGPLOT2
|
||||
# Mas estes não são nem os mais bonitos dos gráficos no R
|
||||
# Experimente o pacote ggplot2 para gráficos diferentes e mais bonitos
|
||||
install.packages("ggplot2")
|
||||
require(ggplot2)
|
||||
?ggplot2
|
||||
pp <- ggplot(estudantes, aes(x=casa))
|
||||
pp + geom_bar()
|
||||
ll <- as.data.table(lista1)
|
||||
pp <- ggplot(ll, aes(x=tempo,preco))
|
||||
pp + geom_point()
|
||||
# ggplot2 tem uma excelente documentação (disponível em http://docs.ggplot2.org/current/)
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
## Como faço para obter R?
|
||||
|
||||
* Obtenha o R e uma interface gráfica para o R em [http://www.r-project.org/](http://www.r-project.org/)
|
||||
* [RStudio](http://www.rstudio.com/ide/) é uma outra interface gráfica
|
@ -234,7 +234,7 @@ fn main() {
|
||||
|
||||
// `for` laços de repetição/iteração
|
||||
let array = [1, 2, 3];
|
||||
for i in array.iter() {
|
||||
for i in array {
|
||||
println!("{}", i);
|
||||
}
|
||||
|
||||
@ -329,4 +329,3 @@ mais na página oficial [Rust website](http://rust-lang.org).
|
||||
|
||||
No Brasil acompanhe os encontros do [Meetup Rust São Paulo]
|
||||
(http://www.meetup.com/pt-BR/Rust-Sao-Paulo-Meetup/).
|
||||
|
||||
|
@ -259,7 +259,7 @@ nomes.length; // pega o tamanho
|
||||
nomes.length = 1; // tamanhos pode ser alterados (para arrays dinâmicos)
|
||||
|
||||
// arrays multidimensionais
|
||||
uint x[][5]; // array com 5 arrays dinâmicos como elementos (ordem da maioria
|
||||
uint[][5] x; // array com 5 arrays dinâmicos como elementos (ordem da maioria
|
||||
// das linguagens)
|
||||
|
||||
// Dicionários (qualquer tipo para qualquer tipo)
|
||||
|
@ -10,7 +10,7 @@ lang: pt-br
|
||||
|
||||
---
|
||||
|
||||
Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e OS X criada pela Apple. Criada para
|
||||
Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e macOS criada pela Apple. Criada para
|
||||
coexistir com Objective-C e para ser mais resiliente a código com erros, Swift foi apresentada em 2014 na Apple's
|
||||
developer conference WWDC. Foi construída com o compilador LLVM já incluído no Xcode 6 beta.
|
||||
|
||||
|
@ -12,7 +12,7 @@ Typescript é uma linguagem que visa facilitar o desenvolvimento de aplicações
|
||||
Typescript acrescenta conceitos comuns como classes, módulos, interfaces, genéricos e (opcional) tipagem estática para JavaScript.
|
||||
É um super conjunto de JavaScript: todo o código JavaScript é TypeScript válido então ele pode ser adicionado diretamente a qualquer projeto. O compilador emite TypeScript JavaScript.
|
||||
|
||||
Este artigo irá se concentrar apenas na sintaxe extra do TypeScript, ao contrário de [JavaScript](javascript-pt.html.markdown).
|
||||
Este artigo irá se concentrar apenas na sintaxe extra do TypeScript, ao contrário de [JavaScript](../javascript-pt/).
|
||||
|
||||
Para testar o compilador TypeScript, vá para o [Playground](http://www.typescriptlang.org/Playground), onde você vai ser capaz de escrever código, ter auto conclusão e ver diretamente o JavaScript emitido.
|
||||
|
||||
|