From b6e9ad3b8d5b0c742f4362f48c1e9988f6a8e87e Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sun, 19 Apr 2015 11:18:51 +0800 Subject: Create a copy of the English version. --- zh-cn/tmux-cn.html.markdown | 251 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 251 insertions(+) create mode 100644 zh-cn/tmux-cn.html.markdown diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown new file mode 100644 index 00000000..c11da5fc --- /dev/null +++ b/zh-cn/tmux-cn.html.markdown @@ -0,0 +1,251 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +filename: LearnTmux.txt +--- + + +[tmux](http://tmux.sourceforge.net) +is a terminal multiplexer: it enables a number of terminals +to be created, accessed, and controlled from a single screen. tmux +may be detached from a screen and continue running in the background +then later reattached. + + +``` + + tmux [command] # Run a command + # 'tmux' with no commands will create a new session + + new # Create a new session + -s "Session" # Create named session + -n "Window" # Create named Window + -c "/dir" # Start in target directory + + attach # Attach last/available session + -t "#" # Attach target session + -d # Detach the session from other instances + + ls # List open sessions + -a # List all open sessions + + lsw # List windows + -a # List all windows + -s # List all windows in session + + lsp # List panes + -a # List all panes + -s # List all panes in session + -t # List app panes in target + + kill-window # Kill current window + -t "#" # Kill target window + -a # Kill all windows + -a -t "#" # Kill all windows but the target + + kill-session # Kill current session + -t "#" # Kill target session + -a # Kill all sessions + -a -t "#" # Kill all sessions but the target + +``` + + +### Key Bindings + +The method of controlling an attached tmux session is via key +combinations called 'Prefix' keys. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # 'Prefix' combination required to use keybinds + + (M-1) = Meta + 1 -or- Alt + 1 +---------------------------------------------------------------------- + + ? # List all key bindings + : # Enter the tmux command prompt + r # Force redraw of the attached client + c # Create a new window + + ! # Break the current pane out of the window. + % # Split the current pane into two, left and right + " # Split the current pane into two, top and bottom + + n # Change to the next window + p # Change to the previous window + { # Swap the current pane with the previous pane + } # Swap the current pane with the next pane + + s # Select a new session for the attached client + interactively + w # Choose the current window interactively + 0 to 9 # Select windows 0 to 9 + + d # Detach the current client + D # Choose a client to detach + + & # Kill the current window + x # Kill the current pane + + Up, Down # Change to the pane above, below, left, or right + Left, Right + + M-1 to M-5 # Arrange panes: + # 1) even-horizontal + # 2) even-vertical + # 3) main-horizontal + # 4) main-vertical + # 5) tiled + + C-Up, C-Down # Resize the current pane in steps of one cell + C-Left, C-Right + + M-Up, M-Down # Resize the current pane in steps of five cells + M-Left, M-Right + +``` + + +### Configuring ~/.tmux.conf + +tmux.conf can be used to set options automatically on start up, much +like how .vimrc or init.el are used. + +``` +# Example tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Enable UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Scrollback/History limit +set -g history-limit 2048 + +# Index Start +set -g base-index 1 + +# Mouse +set-option -g mouse-select-pane on + +# Force reload of config file +unbind r +bind r source-file ~/.tmux.conf + + +### Keybinds +########################################################################### + +# Unbind C-b as the default prefix +unbind C-b + +# Set new default prefix +set-option -g prefix ` + +# Return to previous window when prefix is pressed twice +bind C-a last-window +bind ` last-window + +# Allow swapping C-a and ` using F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Keybind preference +setw -g mode-keys vi +set-option -g status-keys vi + +# Moving between panes with vim movement keys +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Window Cycle/Swap +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# Easy split pane commands +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Activate inner-most session (when nesting tmux) to send commands +bind a send-prefix + + +### Theme +########################################################################### + +# Statusbar Color Palatte +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Pane Border Color Palette +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Message Color Palette +set-option -g message-fg black +set-option -g message-bg green + +# Window Status Color Palette +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notification +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Automatically set window titles +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Statusbar Adjustments +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Show performance counters in statusbar +# Requires https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### References + +[Tmux | Home](http://tmux.sourceforge.net) + +[Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -- cgit v1.2.3 From da12b4d6f592aaf7bce4de6d78c75877cdcc968c Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sun, 19 Apr 2015 11:42:22 +0800 Subject: Translate the majority into Chinese. --- zh-cn/tmux-cn.html.markdown | 184 ++++++++++++++++++++++---------------------- 1 file changed, 92 insertions(+), 92 deletions(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index c11da5fc..184daca1 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -1,9 +1,12 @@ --- category: tool tool: tmux +filename: LearnTmux-cn.txt contributors: - ["mdln", "https://github.com/mdln"] -filename: LearnTmux.txt +translators: + - ["Arnie97", "https://github.com/Arnie97"] +lang: zh-cn --- @@ -16,194 +19,191 @@ then later reattached. ``` - tmux [command] # Run a command - # 'tmux' with no commands will create a new session + tmux [command] # 运行一条命令 + # 如果忽略 'tmux' 之后的命令,将会建立一个新的会话 - new # Create a new session - -s "Session" # Create named session - -n "Window" # Create named Window - -c "/dir" # Start in target directory + new # 创建一个新的会话 + -s "Session" # 创建一个named会话 + -n "Window" # 创建一个named窗口 + -c "/dir" # 在指定的工作目录中启动会话 - attach # Attach last/available session - -t "#" # Attach target session - -d # Detach the session from other instances + attach # 连接到上一次的会话(如果可用) + -t "#" # 连接到指定的会话 + -d # 断开其他客户端的会话 - ls # List open sessions - -a # List all open sessions + ls # 列出打开的会话 + -a # 列出所有打开的会话 - lsw # List windows - -a # List all windows - -s # List all windows in session + lsw # 列出窗口 + -a # 列出所有窗口 + -s # 列出会话中的所有窗口 - lsp # List panes - -a # List all panes - -s # List all panes in session + lsp # 列出窗格 + -a # 列出所有窗格 + -s # 列出会话中的所有窗格 -t # List app panes in target - kill-window # Kill current window - -t "#" # Kill target window - -a # Kill all windows - -a -t "#" # Kill all windows but the target + kill-window # 关闭当前窗口 + -t "#" # 关闭指定的窗口 + -a # 关闭所有窗口 + -a -t "#" # 关闭除指定窗口以外的所有窗口 - kill-session # Kill current session - -t "#" # Kill target session - -a # Kill all sessions - -a -t "#" # Kill all sessions but the target + kill-session # 关闭当前会话 + -t "#" # 关闭指定的会话 + -a # 关闭所有会话 + -a -t "#" # 关闭除指定会话以外的所有会话 ``` -### Key Bindings +## 快捷键 -The method of controlling an attached tmux session is via key -combinations called 'Prefix' keys. +# 通过“前缀”快捷键,可以控制一个已经连入的tmux会话。 ``` ---------------------------------------------------------------------- - (C-b) = Ctrl + b # 'Prefix' combination required to use keybinds + (C-b) = Ctrl + b # 在使用下列快捷键之前,需要按这个“前缀”快捷键 - (M-1) = Meta + 1 -or- Alt + 1 + (M-1) = Meta + 1 或 Alt + 1 ---------------------------------------------------------------------- - ? # List all key bindings - : # Enter the tmux command prompt - r # Force redraw of the attached client - c # Create a new window + ? # 列出所有快捷键 + : # 进入tmux的命令提示符 + r # 强制重绘 the attached client + c # 创建一个新窗口 ! # Break the current pane out of the window. - % # Split the current pane into two, left and right - " # Split the current pane into two, top and bottom + % # 将当前窗格分为左右两半 + " # 将当前窗格分为上下两半 - n # Change to the next window - p # Change to the previous window - { # Swap the current pane with the previous pane - } # Swap the current pane with the next pane + n # 切换到下一个窗口 + p # 切换到上一个窗口 + { # 将当前窗格与上一个窗格交换 + } # 将当前窗格与下一个窗格交换 - s # Select a new session for the attached client - interactively - w # Choose the current window interactively - 0 to 9 # Select windows 0 to 9 + s # 在交互式界面中,选择并连接至另一个会话 + w # 在交互式界面中,选择并激活一个窗口 + 0 至 9 # 选择 0 到 9 号窗口 - d # Detach the current client - D # Choose a client to detach + d # 断开当前客户端 + D # 选择并断开一个客户端 - & # Kill the current window - x # Kill the current pane + & # 关闭当前窗口 + x # 关闭当前窗格 - Up, Down # Change to the pane above, below, left, or right + Up, Down # 将焦点移动至相邻的窗格 Left, Right - M-1 to M-5 # Arrange panes: + M-1 到 M-5 # 排列窗格: # 1) even-horizontal # 2) even-vertical # 3) main-horizontal # 4) main-vertical # 5) tiled - C-Up, C-Down # Resize the current pane in steps of one cell + C-Up, C-Down # 改变当前窗格的大小,每按一次增减一个单位 C-Left, C-Right - M-Up, M-Down # Resize the current pane in steps of five cells + M-Up, M-Down # 改变当前窗格的大小,每按一次增减五个单位 M-Left, M-Right ``` -### Configuring ~/.tmux.conf +### 配置 ~/.tmux.conf -tmux.conf can be used to set options automatically on start up, much -like how .vimrc or init.el are used. +tmux.conf 可以在 tmux 启动时自动设置选项,类似于 .vimrc 或 init.el 的用法。 ``` -# Example tmux.conf +# tmux.conf 示例 # 2014.10 -### General +### 通用设置 ########################################################################### -# Enable UTF-8 +# 启用 UTF-8 编码 setw -g utf8 on set-option -g status-utf8 on -# Scrollback/History limit +# 命令回滚/历史数量限制 set -g history-limit 2048 # Index Start set -g base-index 1 -# Mouse +# 启用鼠标 set-option -g mouse-select-pane on -# Force reload of config file +# 重新加载配置文件 unbind r bind r source-file ~/.tmux.conf -### Keybinds +### 快捷键设置 ########################################################################### -# Unbind C-b as the default prefix +# 取消默认的前缀键 C-b unbind C-b -# Set new default prefix +# 设置新的前缀键 set-option -g prefix ` -# Return to previous window when prefix is pressed twice +# 再次按下前缀键时,回到之前的窗口 bind C-a last-window bind ` last-window -# Allow swapping C-a and ` using F11/F12 +# 按下F11/F12,可以选择不同的前缀键 bind F11 set-option -g prefix C-a bind F12 set-option -g prefix ` -# Keybind preference +# Vim 风格的快捷键绑定 setw -g mode-keys vi set-option -g status-keys vi -# Moving between panes with vim movement keys +# 使用 vim 风格的按键在窗格间移动 bind h select-pane -L bind j select-pane -D bind k select-pane -U bind l select-pane -R -# Window Cycle/Swap +# 循环切换不同的窗口 bind e previous-window bind f next-window bind E swap-window -t -1 bind F swap-window -t +1 -# Easy split pane commands +# 较易于使用的窗格分割快捷键 bind = split-window -h bind - split-window -v unbind '"' unbind % -# Activate inner-most session (when nesting tmux) to send commands +# 在嵌套使用 tmux 的情况下,激活最内层的会话,以便向其发送命令 bind a send-prefix -### Theme +### 外观主题 ########################################################################### -# Statusbar Color Palatte +# 状态栏颜色 set-option -g status-justify left set-option -g status-bg black set-option -g status-fg white set-option -g status-left-length 40 set-option -g status-right-length 80 -# Pane Border Color Palette -set-option -g pane-active-border-fg green -set-option -g pane-active-border-bg black -set-option -g pane-border-fg white -set-option -g pane-border-bg black +# 窗格边框颜色 +set-option -g 窗格-active-border-fg green +set-option -g 窗格-active-border-bg black +set-option -g 窗格-border-fg white +set-option -g 窗格-border-bg black -# Message Color Palette +# 消息框颜色 set-option -g message-fg black set-option -g message-bg green -# Window Status Color Palette +# 窗口状态栏颜色 setw -g window-status-bg black setw -g window-status-current-fg green setw -g window-status-bell-attr default @@ -214,38 +214,38 @@ setw -g window-status-activity-attr default setw -g window-status-activity-fg yellow -### UI +### 用户界面 ########################################################################### -# Notification +# 通知方式 setw -g monitor-activity on set -g visual-activity on set-option -g bell-action any set-option -g visual-bell off -# Automatically set window titles +# 自动设置窗口标题 set-option -g set-titles on -set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # 窗口编号,程序名称,是否活动 -# Statusbar Adjustments +# 调整状态栏 set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" -# Show performance counters in statusbar -# Requires https://github.com/thewtex/tmux-mem-cpu-load/ +# 在状态栏中显示性能计数器 +# 需要用到 https://github.com/thewtex/tmux-mem-cpu-load set -g status-interval 4 set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" ``` -### References +### 参考资料 -[Tmux | Home](http://tmux.sourceforge.net) +[Tmux 主页](http://tmux.sourceforge.net) -[Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) +[Tmux 手册](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) [Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) -[Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) +[如何在 tmux 状态栏中显示 CPU / 内存占用百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -- cgit v1.2.3 From 8aa98bd572bf4a0e1e52ead5a5ee192fc2101df6 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Thu, 28 May 2015 15:54:49 +0800 Subject: Minor improvements. --- zh-cn/tmux-cn.html.markdown | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 184daca1..00bf35f3 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -10,21 +10,19 @@ lang: zh-cn --- -[tmux](http://tmux.sourceforge.net) -is a terminal multiplexer: it enables a number of terminals -to be created, accessed, and controlled from a single screen. tmux -may be detached from a screen and continue running in the background -then later reattached. - +[tmux](http://tmux.sourceforge.net)是一款终端复用工具。 +在它的帮助下,你可以在同一个控制台上建立、访问并控制多个终端。 +你可以断开与一个tmux终端的连接,此时程序将在后台运行, +当你需要时,可以随时重新连接到这个终端。 ``` tmux [command] # 运行一条命令 - # 如果忽略 'tmux' 之后的命令,将会建立一个新的会话 + # 如果单独使用 'tmux' 而不指定某个命令,将会建立一个新的会话 new # 创建一个新的会话 - -s "Session" # 创建一个named会话 - -n "Window" # 创建一个named窗口 + -s "Session" # 创建一个会话,并命名为“Session” + -n "Window" # 创建一个窗口,并命名为“Window” -c "/dir" # 在指定的工作目录中启动会话 attach # 连接到上一次的会话(如果可用) @@ -56,9 +54,9 @@ then later reattached. ``` -## 快捷键 +### 快捷键 -# 通过“前缀”快捷键,可以控制一个已经连入的tmux会话。 +通过“前缀”快捷键,可以控制一个已经连入的tmux会话。 ``` ---------------------------------------------------------------------- @@ -69,7 +67,7 @@ then later reattached. ? # 列出所有快捷键 : # 进入tmux的命令提示符 - r # 强制重绘 the attached client + r # 强制重绘当前客户端 c # 创建一个新窗口 ! # Break the current pane out of the window. @@ -194,10 +192,10 @@ set-option -g status-left-length 40 set-option -g status-right-length 80 # 窗格边框颜色 -set-option -g 窗格-active-border-fg green -set-option -g 窗格-active-border-bg black -set-option -g 窗格-border-fg white -set-option -g 窗格-border-bg black +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black # 消息框颜色 set-option -g message-fg black -- cgit v1.2.3 From 4b0f53d964cc219c491765bfa9c8635cf6d38863 Mon Sep 17 00:00:00 2001 From: Tomasz Janiszewski Date: Thu, 1 Oct 2015 09:56:31 +0200 Subject: Add Polish translations for XML --- pl-pl/xml-pl.html.markdown | 137 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 pl-pl/xml-pl.html.markdown diff --git a/pl-pl/xml-pl.html.markdown b/pl-pl/xml-pl.html.markdown new file mode 100644 index 00000000..7cce138f --- /dev/null +++ b/pl-pl/xml-pl.html.markdown @@ -0,0 +1,137 @@ +--- +language: xml +filename: learnxml-pl.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Tomasz Janiszewski", "https://github.com/janisz"] +lang: pl-pl +--- + +XML (_Extensible Markup Language_) to rozszerzalny język znaczników, stworzony +do przechowywania i transportu danych. + +W przeciwieństwie do HTML, XML nie specyfikuje w jaki sposób wyświetlić dane, a +tylko je przechowuje. + +* Składnia XML + +```xml + + + + + + Codzienny Włoski + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Nauka XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + +komputer.gif + + +``` + +* Dobrze sformatowany dokument i walidacja + +Dokument XML jest dobrze sformatowany gdy jest syntaktycznie poprawny. +Jednakże możliwe jest wstrzykiwanie większej liczby ograniczeń w dokumencie, +używając definicji takich jak DTD i XML Schema. + +Dokument XML, który jest zgodny ze swoją definicją jest poprawny. + + +Korzystając z tych narzędzi możesz sprawdzić dane zawarte w dokumencie poza +logiką aplikacji. + +```xml + + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` -- cgit v1.2.3 From 05559e8620d478b891c47d541dea978f661a8f3a Mon Sep 17 00:00:00 2001 From: Ale46 Date: Fri, 2 Oct 2015 18:41:55 +0200 Subject: [python/it] Translated python to Italian --- it-it/python-it.html.markdown | 647 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 647 insertions(+) create mode 100644 it-it/python-it.html.markdown diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown new file mode 100644 index 00000000..49bbab08 --- /dev/null +++ b/it-it/python-it.html.markdown @@ -0,0 +1,647 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] +filename: learnpython.py +translators: + - ["Ale46", "http://github.com/Ale46/"] +lang: it-it +--- +Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari +linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente +pseudocodice eseguibile. + +Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] + +Nota: Questo articolo è valido solamente per Python 2.7, ma dovrebbe andar bene anche per +Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). + +```python + +# I commenti su una sola linea iniziano con un cancelletto + +""" Più stringhe possono essere scritte + usando tre ", e sono spesso usate + come commenti +""" + +#################################################### +## 1. Tipi di dati primitivi ed Operatori +#################################################### + +# Hai i numeri +3 # => 3 + +# La matematica è quello che vi aspettereste +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# La divisione è un po' complicata. E' una divisione fra interi in cui viene +# restituito in automatico il risultato intero. +5 / 2 # => 2 + +# Per le divisioni con la virgbola abbiamo bisogno di parlare delle variabili floats. +2.0 # Questo è un float +11.0 / 4.0 # => 2.75 ahhh...molto meglio + +# Il risultato di una divisione fra interi troncati positivi e negativi +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funziona anche per i floats +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Operazione Modulo +7 % 3 # => 1 + +# Elevamento a potenza (x alla y-esima potenza) +2**4 # => 16 + +# Forzare le precedenze con le parentesi +(1 + 3) * 2 # => 8 + +# Operatori Booleani +# Nota "and" e "or" sono case-sensitive +True and False #=> False +False or True #=> True + +# Note sull'uso di operatori Bool con interi +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# nega con not +not True # => False +not False # => True + +# Uguaglianza è == +1 == 1 # => True +2 == 1 # => False + +# Disuguaglianza è != +1 != 1 # => False +2 != 1 # => True + +# Altri confronti +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# I confronti possono essere concatenati! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Le stringhe sono create con " o ' +"Questa è una stringa." +'Anche questa è una stringa.' + +# Anche le stringhe possono essere sommate! +"Ciao " + "mondo!" # => Ciao mondo!" +# Le stringhe possono essere sommate anche senza '+' +"Ciao " "mondo!" # => Ciao mondo!" + +# ... oppure moltiplicate +"Hello" * 3 # => "HelloHelloHello" + +# Una stringa può essere considerata come una lista di caratteri +"Questa è una stringa"[0] # => 'Q' + +# % può essere usato per formattare le stringhe, in questo modo: +"%s possono essere %s" % ("le stringhe", "interpolate") + +# Un nuovo modo per fomattare le stringhe è il metodo format. +# Questo metodo è quello consigliato +"{0} possono essere {1}".format("le stringhe", "formattate") +# Puoi usare della parole chiave se non vuoi contare +"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna") + +# None è un oggetto +None # => None + +# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None +# Usa "is" invece +"etc" is None # => False +None is None # => True + +# L'operatore 'is' testa l'identità di un oggetto. Questo non è +# molto utile quando non hai a che fare con valori primitivi, ma lo è +# quando hai a che fare con oggetti. + +# None, 0, e stringhe/liste vuote sono tutte considerate a False. +# Tutti gli altri valori sono True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Variabili e Collections +#################################################### + +# Python ha una funzione di stampa +print "Sono Python. Piacere di conoscerti!" + +# Non c'è bisogno di dichiarare una variabile per assegnarle un valore +una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores +una_variabile # => 5 + +# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. +# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni. +un_altra_variabile # Genera un errore di nome + +# if può essere usato come un'espressione +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Liste immagazzinano sequenze +li = [] +# Puoi partire con una lista pre-riempita +altra_li = [4, 5, 6] + +# Aggiungi cose alla fine di una lista con append +li.append(1) # li ora è [1] +li.append(2) # li ora è [1, 2] +li.append(4) # li ora è [1, 2, 4] +li.append(3) # li ora è [1, 2, 4, 3] +# Rimuovi dalla fine della lista con pop +li.pop() # => 3 e li ora è [1, 2, 4] +# Rimettiamolo a posto +li.append(3) # li ora è [1, 2, 4, 3] di nuovo. + +# Accedi ad una lista come faresti con un array +li[0] # => 1 +# Assegna nuovo valore agli indici che sono già stati inizializzati con = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Nota: è resettato al valore iniziale +# Guarda l'ultimo elemento +li[-1] # => 3 + +# Guardare al di fuori dei limiti è un IndexError +li[4] # Genera IndexError + +# Puoi guardare gli intervalli con la sintassi slice (a fetta). +# (E' un intervallo chiuso/aperto per voi tipi matematici.) +li[1:3] # => [2, 4] +# Ometti l'inizio +li[2:] # => [4, 3] +# Ometti la fine +li[:3] # => [1, 2, 4] +# Seleziona ogni seconda voce +li[::2] # =>[1, 4] +# Copia al contrario della lista +li[::-1] # => [3, 4, 2, 1] +# Usa combinazioni per fare slices avanzate +# li[inizio:fine:passo] + +# Rimuovi arbitrariamente elementi da una lista con "del" +del li[2] # li è ora [1, 2, 3] +# Puoi sommare le liste +li + altra_li # => [1, 2, 3, 4, 5, 6] +# Nota: i valori per li ed _altri_li non sono modificati. + +# Concatena liste con "extend()" +li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6] + +# Controlla l'esistenza di un valore in una lista con "in" +1 in li # => True + +# Esamina la lunghezza con "len()" +len(li) # => 6 + + +# Tuple sono come le liste ma immutabili. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Genera un TypeError + +# Puoi fare tutte queste cose da lista anche sulle tuple +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Puoi scompattare le tuple (o liste) in variabili +a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3 +# Le tuple sono create di default se non usi le parentesi +d, e, f = 4, 5, 6 +# Guarda come è facile scambiare due valori +e, d = d, e # d è ora 5 ed e è ora 4 + + +# Dizionari immagazzinano mappature +empty_dict = {} +# Questo è un dizionario pre-riempito +filled_dict = {"uno": 1, "due": 2, "tre": 3} + +# Accedi ai valori con [] +filled_dict["uno"] # => 1 + +# Ottieni tutte le chiavi come una lista con "keys()" +filled_dict.keys() # => ["tre", "due", "uno"] +# Nota - Nei dizionari l'ordine delle chiavi non è garantito. +# Il tuo risultato potrebbe non essere uguale a questo. + +# Ottieni tutt i valori come una lista con "values()" +filled_dict.values() # => [3, 2, 1] +# Nota - Come sopra riguardo l'ordinamento delle chiavi. + +# Controlla l'esistenza delle chiavi in un dizionario con "in" +"uno" in filled_dict # => True +1 in filled_dict # => False + +# Cercando una chiave non esistente è un KeyError +filled_dict["quattro"] # KeyError + +# Usa il metodo "get()" per evitare KeyError +filled_dict.get("uno") # => 1 +filled_dict.get("quattro") # => None +# Il metodo get supporta un argomento di default quando il valore è mancante +filled_dict.get("uno", 4) # => 1 +filled_dict.get("quattro", 4) # => 4 +# nota che filled_dict.get("quattro") è ancora => None +# (get non imposta il valore nel dizionario) + +# imposta il valore di una chiave con una sintassi simile alle liste +filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4 + +# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente +filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5 + + +# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni) +empty_set = set() +# Inizializza un "set()" con un po' di valori +some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4]) + +# l'ordine non è garantito, anche se a volta può sembrare ordinato +another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4]) + +# Da Python 2.7, {} può essere usato per dichiarare un set +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Aggiungere elementi ad un set +filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5} + +# Fai interazioni su un set con & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Fai unioni su set con | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Fai differenze su set con - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Controlla l'esistenza in un set con in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Control Flow +#################################################### + +# Dichiariamo una variabile +some_var = 5 + +# Questo è un controllo if. L'indentazione è molto importante in python! +# stampa "some_var è più piccola di 10" +if some_var > 10: + print "some_var è decisamente più grande di 10." +elif some_var < 10: # Questa clausola elif è opzionale. + print "some_var è più piccola di 10." +else: # Anche questo è opzionale. + print "some_var è precisamente 10." + + +""" +I cicli for iterano sulle liste +stampa: + cane è un mammifero + gatto è un mammifero + topo è un mammifero +""" +for animale in ["cane", "gatto", "topo"]: + # Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.) + print "{0} è un mammifero".format(animale) + +""" +"range(numero)" restituisce una lista di numeri +da zero al numero dato +stampa: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" restituisce una lista di numeri +dal più piccolo (lower) al più grande (upper) +stampa: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +I cicli while vengono eseguiti finchè una condizione viene a mancare +stampa: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Forma compatta per x = x + 1 + +# Gestisci le eccezioni con un blocco try/except + +# Funziona da Python 2.6 in su: +try: + # Usa "raise" per generare un errore + raise IndexError("Questo è un errore di indice") +except IndexError as e: + pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero. +except (TypeError, NameError): + pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. +else: # Optional clause to the try/except block. Must follow all except blocks + print "All good!" # Viene eseguita solo se il codice dentro try non genera eccezioni +finally: # Eseguito sempre + print "Possiamo liberare risorse qui" + +# Invece di try/finally per liberare risorse puoi usare il metodo with +with open("myfile.txt") as f: + for line in f: + print line + +#################################################### +## 4. Funzioni +#################################################### + +# Usa "def" per creare nuove funzioni +def aggiungi(x, y): + print "x è {0} e y è {1}".format(x, y) + return x + y # Restituisce valori con il metodo return + +# Chiamare funzioni con parametri +aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11 + +# Un altro modo per chiamare funzioni è con parole chiave come argomenti +aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine. + + +# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali +# che verranno interpretati come come tuple se non usi il * +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Puoi definire funzioni che accettano un numero variabile di parole chiave +# come argomento, che saranno interpretati come un dizionario se non usi ** +def keyword_args(**kwargs): + return kwargs + +# Chiamiamola per vedere cosa succede +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Puoi farle entrambi in una volta, se ti va +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) stampa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! +# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs +# sviluppandoli, rispettivamente, con * e ** +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Funzioni Scope +x = 5 + +def setX(num): + # La variabile locale x non è uguale alla variabile globale x + x = num # => 43 + print x # => 43 + +def setGlobalX(num): + global x + print x # => 5 + x = num # la variabile globable x è ora 6 + print x # => 6 + +setX(43) +setGlobalX(6) + +# Python ha funzioni di prima classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Ci sono anche funzioni anonime +(lambda x: x > 2)(3) # => True + +# Esse sono incluse in funzioni di alto livello +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Possiamo usare la comprensione delle liste per mappe e filtri +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + + +#################################################### +## 5. Classi +#################################################### + +# Usiamo una sottoclasse da un oggetto per avere una classe. +class Human(object): + + # Un attributo della classe. E' condiviso da tutte le istanze delle classe + species = "H. sapiens" + + # Costruttore base, richiamato quando la classe viene inizializzata. + # Si noti che il doppio leading e l'underscore finali denotano oggetti + # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato + # dall'utente. Non dovresti usare nomi di questo genere. + def __init__(self, name): + # Assegna l'argomento all'attributo name dell'istanza + self.name = name + + # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # Un metodo della classe è condiviso fra tutte le istanze + # Sono chiamate con la classe chiamante come primo argomento + @classmethod + def get_species(cls): + return cls.species + + # Un metodo statico è chiamato senza una classe od una istanza di riferimento + @staticmethod + def grunt(): + return "*grunt*" + + +# Instanziare una classe +i = Human(name="Ian") +print i.say("hi") # stampa "Ian: hi" + +j = Human("Joel") +print j.say("hello") # stampa "Joel: hello" + +# Chiamare metodi della classe +i.get_species() # => "H. sapiens" + +# Cambiare l'attributo condiviso +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Chiamare il metodo condiviso +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduli +#################################################### + +# Puoi importare moduli +import math +print math.sqrt(16) # => 4 + +# Puoi ottenere specifiche funzione da un modulo +from math import ceil, floor +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# Puoi importare tutte le funzioni da un modulo +# Attenzione: questo non è raccomandato +from math import * + +# Puoi abbreviare i nomi dei moduli +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# puoi anche verificare che le funzioni sono equivalenti +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# I moduli di Python sono normali file python. Ne puoi +# scrivere di tuoi ed importarli. Il nome del modulo +# è lo stesso del nome del file. + +# Potete scoprire quali funzioni e attributi +# definiscono un modulo +import math +dir(math) + + +#################################################### +## 7. Avanzate +#################################################### + +# Generators help you make lazy code +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Un generatore crea valori al volo. +# Invece di generare e ritornare tutti i valori in una volta ne crea uno in ciascuna +# iterazione. Ciò significa che i valori più grandi di 15 non saranno considerati in +# double_numbers. +# Nota xrange è un generatore che fa la stessa cosa di range. +# Creare una lista 1-900000000 occuperebbe molto tempo e spazio. +# xrange crea un oggetto generatore xrange invece di creare l'intera lista +# come fa range. +# Usiamo un underscore finale nel nome delle variabile quando vogliamo usare un nome +# che normalmente colliderebbe con una parola chiave di python +xrange_ = xrange(1, 900000000) + +# raddoppierà tutti i numeri fino a che result >=30 non sarà trovato +for i in double_numbers(xrange_): + print i + if i >= 30: + break + + +# Decoratori +# in questo esempio beg include say +# Beg chiamerà say. Se say_please è True allora cambierà il messaggio +# ritornato +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From c3387b8a611b6fbb00ac8d54102b772d44d3eca2 Mon Sep 17 00:00:00 2001 From: Andrew Backes Date: Sun, 18 Oct 2015 22:32:14 -0500 Subject: [typescript/en] Template Strings --- typescript.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/typescript.html.markdown b/typescript.html.markdown index e9135510..101bb5dc 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -159,6 +159,10 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); // Including references to a definition file: /// +// Template Strings +var name = 'Tyrone'; +var greeting = `Hi ${name}, how are you?` + ``` ## Further Reading -- cgit v1.2.3 From 525b6106a57baa570734e29b43f861cd8cc5de3a Mon Sep 17 00:00:00 2001 From: Andrew Backes Date: Sun, 18 Oct 2015 22:38:56 -0500 Subject: [typescript/en] Multiline Strings Multiline Strings via Template Strings --- typescript.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 101bb5dc..61b0fdb8 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -159,9 +159,13 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); // Including references to a definition file: /// -// Template Strings +// Template Strings (strings that use backtics) +// String Intepolation with Template Strings var name = 'Tyrone'; var greeting = `Hi ${name}, how are you?` +// Multiline Strings with Template Strings +var multiline = `This is an example +of a multiline string`; ``` -- cgit v1.2.3 From 998e76c310422e0946431b036eb7de03a9384e74 Mon Sep 17 00:00:00 2001 From: Andrew Backes Date: Mon, 19 Oct 2015 08:09:58 -0500 Subject: [typescript/en] Typo fixed in 'backticks' --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 61b0fdb8..17c56e7a 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -159,7 +159,7 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); // Including references to a definition file: /// -// Template Strings (strings that use backtics) +// Template Strings (strings that use backticks) // String Intepolation with Template Strings var name = 'Tyrone'; var greeting = `Hi ${name}, how are you?` -- cgit v1.2.3 From 5ca38bf934801c9e85e25e19842a6f84ebe6efa0 Mon Sep 17 00:00:00 2001 From: Andrew Backes Date: Mon, 19 Oct 2015 10:40:57 -0500 Subject: [typescript/en] Fixing typo in 'Interpolation' --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 17c56e7a..20974304 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -160,7 +160,7 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); /// // Template Strings (strings that use backticks) -// String Intepolation with Template Strings +// String Interpolation with Template Strings var name = 'Tyrone'; var greeting = `Hi ${name}, how are you?` // Multiline Strings with Template Strings -- cgit v1.2.3 From 7c15eaefcdfe21809ebab893f6d8d6321188abf1 Mon Sep 17 00:00:00 2001 From: Chaitya Shah Date: Tue, 20 Oct 2015 11:45:58 -0400 Subject: Fix Spacing Inconsistency Fix spacing inconsistency in PennyFarthing Constructor --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 38c9e490..a78aa9fc 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -519,7 +519,7 @@ class PennyFarthing extends Bicycle { // (Penny Farthings are those bicycles with the big front wheel. // They have no gears.) - public PennyFarthing(int startCadence, int startSpeed){ + public PennyFarthing(int startCadence, int startSpeed) { // Call the parent constructor with super super(startCadence, startSpeed, 0, "PennyFarthing"); } -- cgit v1.2.3 From 3dec2d03a7c327dcf5049ef087d1dd395b04ffd8 Mon Sep 17 00:00:00 2001 From: Jean Matheus Souto Date: Sat, 24 Oct 2015 20:51:42 -0200 Subject: Add more resources, add me to contributors --- pt-br/ruby-pt.html.markdown | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 89a051d4..668cd25f 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -4,6 +4,7 @@ lang: pt-br filename: learnruby-pt.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] + - ["Jean Matheus Souto", "http://jeanmatheussouto.github.io"] translators: - ["Katyanna Moura", "https://twitter.com/amelie_kn"] --- @@ -161,9 +162,6 @@ hash['numero'] #=> 5 hash['nada aqui'] #=> nil # Interar sobre hashes com o método #each: -hash.each do |k, v| - puts "#{k} is #{v}" -end hash.each do |k, v| puts "#{k} é #{v}" @@ -385,3 +383,11 @@ Humano.bar # 0 Doutor.bar # nil ``` + +## Mais sobre Ruby + +- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/) +- [Aprenda Ruby com desafios](http://www.learneroo.com/modules/61/nodes/338) - Uma coleção de desafios para testar a linguagem. +- [Ruby a partir de outras linguagens](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/)- Um mais antigo [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) e tambem uma versão online disponível. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Uma versão colaborativa de um *style-guide* -- cgit v1.2.3 From 4b0dda63b31873fad1b038c1db4745aaa20756cf Mon Sep 17 00:00:00 2001 From: Zane Sterling Date: Sun, 25 Oct 2015 12:55:50 -0400 Subject: Fix typo in README.md --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 94afbcbe..092785f8 100644 --- a/README.markdown +++ b/README.markdown @@ -51,7 +51,7 @@ Long version: ### Header configuration The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least -the custom scripts underpinning the site, required that some key information be defined in the header. +the custom scripts underpinning the site, requires that some key information be defined in the header. The following fields are necessary for English articles about programming languages: -- cgit v1.2.3 From e60a7d73e846e683bd4345cff4d1a514beab5b91 Mon Sep 17 00:00:00 2001 From: jxu093 Date: Sun, 25 Oct 2015 22:19:40 -0400 Subject: Added Python Resource --- python.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/python.html.markdown b/python.html.markdown index 42a52bcf..254235ab 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -712,6 +712,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [Fullstack Python](https://www.fullstackpython.com/) ### Dead Tree -- cgit v1.2.3 From 5acb0c1a604d468af2cd651229866c48ed7c4e24 Mon Sep 17 00:00:00 2001 From: Bruno Volcov Date: Mon, 26 Oct 2015 17:23:27 -0200 Subject: add a cool reference for learn Ruby =) --- ruby.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index c10255d8..b3ef2a4d 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -13,6 +13,7 @@ contributors: - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gabriel Halley", https://github.com/ghalley] + - ["Bruno Volcov", https://github.com/volcov] --- @@ -285,7 +286,7 @@ end #=> iteration 4 #=> iteration 5 -# There are a bunch of other helpful looping functions in Ruby, +# There are a bunch of other helpful looping functions in Ruby, # for example "map", "reduce", "inject", the list goes on. Map, # for instance, takes the array it's looping over, does something # to it as defined in your block, and returns an entirely new array. @@ -576,3 +577,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/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser. -- cgit v1.2.3 From 69efce9e8340216164b8aeae3af72994fae64582 Mon Sep 17 00:00:00 2001 From: Juuso Mikkonen Date: Mon, 26 Oct 2015 22:33:53 +0200 Subject: [scala/eng] Added Java import to misc --- scala.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..166285f2 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -606,6 +606,9 @@ import scala.collection.immutable.{List => ImmutableList} // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} +// Java classes can also be imported. Scala syntax can be used +import java.swing.{JFrame, JWindow} + // Your programs entry point is defined in an scala file using an object, with a // single method, main: object Application { -- cgit v1.2.3 From 35a1cd4eeb96557c70de57b972b0000c94245f13 Mon Sep 17 00:00:00 2001 From: ditam Date: Wed, 28 Oct 2015 23:31:15 +0100 Subject: add Hungarian translation --- hu-hu/yaml-hu.html.markdown | 146 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 hu-hu/yaml-hu.html.markdown diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown new file mode 100644 index 00000000..eeafbfb3 --- /dev/null +++ b/hu-hu/yaml-hu.html.markdown @@ -0,0 +1,146 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +--- + +A YAML egy adat sorosító nyelv amit úgy terveztek, hogy közvetlenül is +olvasható és írható legyen emberi szemmel. + +A JSON formátum egy szigorú befoglaló halmazát alkotja, kiegészítve azt +szintaktikai jelentéssel bíró sortörésekkel és indentációval, +a Python-hoz hasonlóan. A Python-nal ellentétben azonban a YAML nem engedélyezi +a közvetlen tab karakterek jelenlétét. + +Megjegyzés: UTF-8 ékezetes betűk használhatóak, ha a fájl kódlása megfelelő, +a kódolást a tartalomban explicit nem kell (és nem is lehet) feltüntetni. + +```yaml +# A kommentek YAML-ban így néznek ki. + +################## +# Skalár típusok # +################## + +# A gyökér objektumunk (az egész dokumentumra értve) egy map, +# ami a más nyelvekből ismert dictionary, hash vagy object típusokkal egyenértékű. +kulcs: érték +masik_kulcs: Másik érték jön ide. +egy_szam: 100 +tudomanyos_jelolessel: 1e+12 +boolean: true +null_value: null +kulcs benne szóközökkel: érték +# Látható, hogy a sztringeket nem szükséges idézőjelek közé zárni, bár szabad. +Továbbá: "Idézőjelekkel megadott sztring." +"A kulcs is lehet idézőjeles.": "Hasznos lehet, ha ':'-ot akarsz a kulcsban." + +# Többsoros sztringek írhatóak 'literal block'-ként ('|' jelet használva) +# vagy 'folded block'-ként is ('>' jelet használva). +literal_block: | + Ez az egész szöveg-blokk lesz az értéke a literal_block kulcsnak, + a sortöréseket megtartva. + + Az ilyen sztringet az indentáció visszahúzása zárja le, a behúzás pedig + eltávolításra kerül. + + A 'még jobban' behúzott részek megtartják a behúzásukat - + ezeknek a soroknak 4 szóköz behúzása lesz. +folded_style: > + Az az egész szöveg-blokk lesz az értéke a 'folded_style' kulcsnak, de + ezúttal minden sortörés egy szóközre lesz cserélve. + + Az üres sorok, mint a fenti, új sor karakterre cserélődnek. + + A 'még jobban' behúzott sorok megtartják a sortöréseiket, - + ez a szöveg két sorban jelenik meg. + +###################### +# Gyűjtemény típusok # +###################### + +# Egymásba ágyazás a behúzás változtatásával érhető el. +beagyazott_map: + key: value + another_key: Another Value + masik_beagyazott_map: + hello: hello + +# A mapeknek nem csak sztring kulcsaik lehetnek. +0.25: lebegőpontos kulcs + +# A kulcsok lehetnek többsoros objektumok is, ? jellel jelezve a kulcs kezdetét +? | + Ez itt egy + többsoros kulcs +: és ez az értéke + +# Szintén engedélyezett a kollekció típusok használata kulcsként, de egyéb +# nyelvekben ez gyakran problémákat fog okozni. + +# Szekvenciák (listákkal vagy tömbökkel egyenértékűek) így néznek ki: +egy_szekvencia: + - Item 1 + - Item 2 + - 0.5 # Többféle típust is tartalmazhat + - Item 4 + - key: value + another_key: another_value + - + - Ez egy szekvencia + - egy másik szekvenciába ágyazva + +# Mivel a YAML a JSON befoglaló halmazát alkotja, JSON szintaxisú +# mapek és szekvenciák is használhatóak: +json_map: {"key": "value"} +json_seq: [3, 2, 1, "takeoff"] + +######################### +# EXTRA YAML KÉPESSÉGEK # +######################### + +# A YAML-ben ún. 'anchor'-ök segítségével könnyen lehet duplikálni +# tartalmakat a dokumentumon belül. A következő kulcsok azonos értékkel bírnak: +anchored_tartalom: &anchor_neve Ez a sztring két kulcs értéke is lesz. +másik_anchor: *anchor_neve + +# Vannak a YAML-ben tagek is, amivel explicit lehet típusokat jelölni. +explicit_string: !!str 0.5 +# Bizonyos implementációk nyelv-specifikus tageket tartalmaznak, mint +# például ez a Python komplex szám típusának jelölésére: +python_complex_number: !!python/complex 1+2j + +###################### +# EXTRA YAML TÍPUSOK # +###################### + +# Nem a sztringek és a számok az egyedüli skalár típusok YAML-ben. +# ISO-formátumú dátumok és dátumot jelölő literal kifejezések is értelmezettek. +datetime: 2001-12-15T02:59:43.1Z +datetime_with_spaces: 2001-12-14 21:59:43.10 -5 +date: 2002-12-14 + +# A !!binary tag jelöli, hogy egy sztring valójában base64-kódolású +# reprezentációja egy bináris blob-nak +gif_file: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# Létezik a YAML-ban egy halmaz típus (set) is, ami így néz ki: +set: + ? elem1 + ? elem2 + ? elem3 + +# Mint Pythonban, a halmazok null értékekkel feltöltött mapek, vagyis a fenti +# halmaz egyenértékű a következővel: +set2: + item1: null + item2: null + item3: null +``` \ No newline at end of file -- cgit v1.2.3 From 78dee8ef7505e8ebc34bb8bf3d6be124231ee1a7 Mon Sep 17 00:00:00 2001 From: ditam Date: Wed, 28 Oct 2015 23:36:48 +0100 Subject: fix small typos and grammar. --- hu-hu/yaml-hu.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown index eeafbfb3..757b8417 100644 --- a/hu-hu/yaml-hu.html.markdown +++ b/hu-hu/yaml-hu.html.markdown @@ -7,12 +7,12 @@ translators: - ["Tamás Diószegi", "https://github.com/ditam"] --- -A YAML egy adat sorosító nyelv amit úgy terveztek, hogy közvetlenül is +A YAML egy adat sorosító nyelv, amit úgy terveztek, hogy közvetlenül is olvasható és írható legyen emberi szemmel. A JSON formátum egy szigorú befoglaló halmazát alkotja, kiegészítve azt szintaktikai jelentéssel bíró sortörésekkel és indentációval, -a Python-hoz hasonlóan. A Python-nal ellentétben azonban a YAML nem engedélyezi +a Pythonhoz hasonlóan. A Pythonnal ellentétben azonban a YAML nem engedélyezi a közvetlen tab karakterek jelenlétét. Megjegyzés: UTF-8 ékezetes betűk használhatóak, ha a fájl kódlása megfelelő, @@ -140,7 +140,7 @@ set: # Mint Pythonban, a halmazok null értékekkel feltöltött mapek, vagyis a fenti # halmaz egyenértékű a következővel: set2: - item1: null - item2: null - item3: null + elem1: null + elem2: null + elem3: null ``` \ No newline at end of file -- cgit v1.2.3 From 3b1940b9cc9c0e46a9275b2ae64e4c5996d7de75 Mon Sep 17 00:00:00 2001 From: Alex Luehm Date: Wed, 28 Oct 2015 17:45:31 -0500 Subject: [C/en] Added tidbit about fall-though in switch statements. Another pitfall, as not all languages have fall-through in switches. --- c.html.markdown | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 3d632eab..2a5e460f 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -76,7 +76,7 @@ int main (int argc, char** argv) /////////////////////////////////////// // Types /////////////////////////////////////// - + // All variables MUST be declared at the top of the current block scope // we declare them dynamically along the code for the sake of the tutorial @@ -318,6 +318,12 @@ int main (int argc, char** argv) case 1: printf("Huh, 'a' equals 1!\n"); break; + // Be careful - without a "break", execution continues until the + // next "break" is reached. + case 3: + case 4: + printf("Look at that.. 'a' is either 3, or 4\n"); + break; default: // if `some_integral_expression` didn't match any of the labels fputs("error!\n", stderr); @@ -345,8 +351,8 @@ int main (int argc, char** argv) https://ideone.com/GuPhd6 this will print out "Error occured at i = 52 & j = 99." */ - - + + /////////////////////////////////////// // Typecasting /////////////////////////////////////// @@ -445,7 +451,7 @@ int main (int argc, char** argv) for (xx = 0; xx < 20; xx++) { *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) - + // Note that there is no standard way to get the length of a // dynamically allocated array in C. Because of this, if your arrays are // going to be passed around your program a lot, you need another variable @@ -721,13 +727,13 @@ typedef void (*my_fnp_type)(char *); /******************************* Header Files ********************************** -Header files are an important part of c as they allow for the connection of c -source files and can simplify code and definitions by seperating them into +Header files are an important part of c as they allow for the connection of c +source files and can simplify code and definitions by seperating them into seperate files. -Header files are syntaxtically similar to c source files but reside in ".h" -files. They can be included in your c source file by using the precompiler -command #include "example.h", given that example.h exists in the same directory +Header files are syntaxtically similar to c source files but reside in ".h" +files. They can be included in your c source file by using the precompiler +command #include "example.h", given that example.h exists in the same directory as the c file. */ -- cgit v1.2.3 From d0ab5fc7729062d24b8f3aac1d8578e914a5955a Mon Sep 17 00:00:00 2001 From: ditam Date: Wed, 28 Oct 2015 23:47:41 +0100 Subject: add language suffix to filename --- hu-hu/yaml-hu.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown index 757b8417..aca6cd37 100644 --- a/hu-hu/yaml-hu.html.markdown +++ b/hu-hu/yaml-hu.html.markdown @@ -1,6 +1,6 @@ --- language: yaml -filename: learnyaml.yaml +filename: learnyaml-hu.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: -- cgit v1.2.3 From 54c67dfb38d1bb2a9dc004b3244d2ae3102107f3 Mon Sep 17 00:00:00 2001 From: bk2dcradle Date: Thu, 29 Oct 2015 22:13:24 +0530 Subject: [c++] Added Lambda Expressions and Range for --- c++.html.markdown | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index d03092e5..6033ca06 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -801,6 +801,106 @@ void doSomethingWithAFile(const std::string& filename) // all automatically destroy their contents when they fall out of scope. // - Mutexes using lock_guard and unique_lock +/////////////////////////////////////// +// Lambda Expressions (C++11 and above) +/////////////////////////////////////// + +// lambdas are a convenient way of defining an anonymous function +// object right at the location where it is invoked or passed as +// an argument to a function. + +// Example consider sorting a vector of pairs using the second +// value of the pair + +vector > tester; +tester.push_back(make_pair(3, 6)); +tester.push_back(make_pair(1, 9)); +tester.push_back(make_pair(5, 0)); + +// Pass a lambda expression as third argument to the sort function +// sort is from the header + +sort(tester.begin(), tester.end(), [](const pair &lhs, const pair &rhs) { + return lhs.second < rhs.second; + }); + +// Notice the syntax of the lambda expression, +// [] in the lambda is used to "capture" variables. +// For Example: + +vector dog_ids; +// number_of_dogs = 3; +for(int i = 0; i < 3; i++){ + dog_ids.push_back(i); +} + +int weight[3]; +weight[0] = 30, weight[1] = 50, weight[2] = 10; + +// Say you want to sort dog_ids according to the dogs' weights +// So dog_ids should in the end become: [2, 0, 1] + +// Here's where lambda expressions come in handy + +sort(dog_ids.begin(), dog_ids.end(), [weight](const int &lhs, const int &rhs) { + return weight[lhs] < weight[rhs]; + }); +// Note we captured "weight" in the above example. + +// lambda are really useful for the case of structs +// You can use lambda expressions instead of overloading +// the "<" operator + +struct dog{ + int weight, age; +}dogs[3]; + +dogs[0].weight = 30, dogs[0].age = 4; +dogs[1].weight = 40, dogs[1].age = 10; +dogs[2].weight = 20, dogs[2].age = 9; + +// Say I want to sort the dogs array by the dogs' weights + +sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { + return lhs.weight < rhs.weight; + }); +// dogs is now sorted according to their weight + +// Do something with the dogs + +// Now I want to sort the dogs by in descending order of their age + +sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { + return lhs.age > rhs.age; + }); +// dogs is now sorted in descending order of their age + + +/////////////////////////////// +// Range For (C++11 and above) +/////////////////////////////// + +// You can use a range for loop to iterate over a container +int arr[] = {1, 10, 3}; + +for(int elem: arr){ + cout< Date: Thu, 29 Oct 2015 19:44:21 +0100 Subject: [go/de] More infos, reformulation and typo fixes for Go. --- de-de/go-de.html.markdown | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index d3a192fe..099927b6 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -4,17 +4,16 @@ filename: learngo-de.go contributors: - ["Joseph Adams", "https://github.com/jcla1"] - ["Dennis Keller", "https://github.com/denniskeller"] + - ["Jerome Meinke", "https://github.com/jmeinke"] lang: de-de --- -Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in -der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in -der realen Welt zu lösen. - -Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung -und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu -verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern -Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große -Programmierprojekte. +Die Sprache Go (auch golang) wurde von Google entwickelt und wird seit 2007 +benutzt. Go ähnelt in der Syntax der Sprache C, bietet darüber hinaus aber viele +Vorteile. Einerseits verzichtet Gp auf Speicherarithmetik und +benutzt einen Garbabe Collector. Andererseits enthält Go native Sprachelemente +für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen +Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten +erleichtert. Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine aktive Community. @@ -24,7 +23,7 @@ aktive Community. /* Mehr- zeiliger Kommentar */ -// Eine jede Quelldatei beginnt mit einer Paket-Klausel. +// Wie bei Java gehört jede Quelldatei einem Paket an (Modularisierung). // "main" ist ein besonderer Paketname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. @@ -40,7 +39,7 @@ import ( // Es folgt die Definition einer Funktion, in diesem Fall von "main". Auch hier // ist der Name wieder besonders. "main" markiert den Eintrittspunkt des -// Programms. Vergessen Sie nicht die geschweiften Klammern! +// Programms. func main() { // Println gibt eine Zeile zu stdout aus. // Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt. @@ -50,8 +49,8 @@ func main() { beyondHello() } -// Funktionen können Parameter akzeptieren, diese werden in Klammern deklariert, -// die aber auch bei keinen Parametern erforderlich sind. +// Funktionen können Parameter akzeptieren. Siese werden in Klammern deklariert, +// die aber auch ohne Parameter erforderlich sind. func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. @@ -306,14 +305,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ``` ## Weitere Resourcen -Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/). -Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel -Dokumentation lesen. +Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/). +Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor +allem aber Dokumentation zur Sprache und den Paketen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr -kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen -ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/). -Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil -verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen +kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen +ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/) +einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil +verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). - -- cgit v1.2.3 From e5a02057227506b95630658971caabb30b64f705 Mon Sep 17 00:00:00 2001 From: meinkej Date: Thu, 29 Oct 2015 19:50:17 +0100 Subject: Fix a typo introduced in the previous commit. Reformatted some lines. --- de-de/go-de.html.markdown | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 099927b6..94f48e65 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -49,7 +49,7 @@ func main() { beyondHello() } -// Funktionen können Parameter akzeptieren. Siese werden in Klammern deklariert, +// Funktionen können Parameter akzeptieren. Diese werden in Klammern deklariert, // die aber auch ohne Parameter erforderlich sind. func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. @@ -98,7 +98,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre // Vorzüge, aber slices werden viel häufiger verwendet s3 := []int{4, 5, 9} // Vergleichen Sie mit a3, hier: keine Ellipse - s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Initialwert 0 + s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Wert 0 var d2 [][]float64 // Nur eine Deklaration, keine Speicherzuweisung bs := []byte("eine slice") // Umwandlungs-Syntax @@ -200,7 +200,8 @@ type pair struct { x, y int } -// Definiere eine Methode von "pair". Dieser Typ erfüllt jetzt das Stringer interface. +// Definiere eine Methode von "pair". +// Dieser Typ erfüllt jetzt das Stringer interface. func (p pair) String() string { // p ist der Empfänger // Sprintf ist eine weitere öffentliche Funktion von fmt. // Der Syntax mit Punkt greift auf die Felder zu. @@ -254,8 +255,9 @@ func learnConcurrency() { // Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für // maps, slices und Kanäle. c := make(chan int) - // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently) - // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal. + // Starte drei parallele "Goroutines". + // Die Zahlen werden parallel (concurrently) erhöht. + // Alle drei senden ihr Ergebnis in den gleichen Kanal. go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine go inc(10, c) go inc(-805, c) -- cgit v1.2.3 From db632ee03ca837fcdc4ca45e428ad7efb9c8135f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20P=C3=A9rez?= Date: Sat, 31 Oct 2015 11:27:29 +0100 Subject: Create file for PHP translation es-ES --- es-es/php-es.html.markdown | 823 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 823 insertions(+) create mode 100644 es-es/php-es.html.markdown diff --git a/es-es/php-es.html.markdown b/es-es/php-es.html.markdown new file mode 100644 index 00000000..a8276e53 --- /dev/null +++ b/es-es/php-es.html.markdown @@ -0,0 +1,823 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Mario Pérez", "https://github.com/MarioPerezEsteso"] +lang: es-es +filename: learnphp-es.php +--- + +This document describes PHP 5+. + +```php + +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (a leading 0 denotes an octal number) +$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) + +// Floats (aka doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Delete variable +unset($int1); + +// Arithmetic +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// Shorthand arithmetic +$number = 0; +$number += 1; // Increment $number by 1 +echo $number++; // Prints 1 (increments after evaluation) +echo ++$number; // Prints 3 (increments before evaluation) +$number /= $float; // Divide and assign the quotient to $number + +// Strings should be enclosed in single quotes; +$sgl_quotes = '$String'; // => '$String' + +// Avoid using double quotes except to embed other variables +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Special characters are only escaped in double quotes +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// Enclose a variable in curly braces if needed +$money = "I have $${number} in the bank."; + +// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs will do string interpolation +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 introduced a new syntax +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // prints 1 + +// List literals implicitly assign integer keys +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// Add an element to the end of an array +$array[] = 'Four'; +// or +array_push($array, 'Five'); + +// Remove element from array +unset($array[3]); + +/******************************** + * Output + */ + +echo('Hello World!'); +// Prints Hello World! to stdout. +// Stdout is the web page if running in a browser. + +print('Hello World!'); // The same as echo + +// echo and print are language constructs too, so you can drop the parentheses +echo 'Hello World!'; +print 'Hello World!'; + +$paragraph = 'paragraph'; + +echo 100; // Echo scalar variables directly +echo $paragraph; // or variables + +// If short open tags are configured, or your PHP version is +// 5.4.0 or greater, you can use the short echo syntax +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Dumps type and value of variable to stdout +var_dump($z); // prints int(0) + +// Prints variable to stdout in human-readable format +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * Logic + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert throws a warning if its argument is not true + +// These comparisons will always be true, even if the types aren't the same. +assert($a == $b); // equality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// The following will only be true if the values match and are the same type. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// 'Spaceship' operator (since PHP 7) +// Returns 0 if values on either side are equal +// Returns 1 if value on the left is greater +// Returns -1 if the value on the right is greater + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 since they are equal +echo $a <=> $b; // -1 since $a < $b +echo $b <=> $a; // 1 since $b > $a + +// Variables can be converted between types, depending on their usage. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (strings are coerced to integers) + +$string = 'one'; +echo $string + $string; // => 0 +// Outputs 0 because the + operator cannot cast the string 'one' to a number + +// Type casting can be used to treat a variable as another type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// There are also dedicated functions for casting most types +$integer = 5; +$string = strval($integer); + +$var = null; // Null value + + +/******************************** + * Control Structures + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// ternary operator +print (false ? 'Does not get printed' : 'Does'); + +// ternary shortcut operator since PHP 5.3 +// equivalent of "$x ? $x : 'Does'"" +$x = false; +print($x ?: 'Does'); + +// null coalesce operator since php 7 +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// This alternative syntax is useful for templates: +?> + + +This is displayed if the test is truthy. + +This is displayed otherwise. + + + 2, 'car' => 4]; + +// Foreach loops can iterate over arrays +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Prints "24" + +echo "\n"; + +// You can iterate over the keys as well as the values +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Exit out of the while loop + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Skip this iteration of the loop + } + echo $i; +} // Prints "0124" + + +/******************************** + * Functions + */ + +// Define a function with "function": +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// A valid function name starts with a letter or underscore, followed by any +// number of letters, numbers, or underscores. + +function add ($x, $y = 1) { // $y is optional and defaults to 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result is not accessible outside the function +// print $result; // Gives a warning. + +// Since PHP 5.3 you can declare anonymous functions; +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Functions can return functions +function bar ($x, $y) { + // Use 'use' to bring in outside variables + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Prints "A - B - C" + +// You can call named functions using strings +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Useful for programatically determining which function to run. +// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + + +// You can get the all the parameters passed to a function +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + +// Since PHP 5.6 you can get a variable number of arguments +function variable($word, ...$list) { + echo $word . " || "; + foreach ($list as $item) { + echo $item . ' | '; + } +} + +variable("Separate", "Hello", "World") // Separate || Hello | World | + +/******************************** + * Includes + */ + +instanceProp = $instanceProp; + } + + // Methods are declared as functions inside a class + public function myMethod() + { + print 'MyClass'; + } + + //final keyword would make a function unoverridable + final function youCannotOverrideMe() + { + } + +/* + * Declaring class properties or methods as static makes them accessible without + * needing an instantiation of the class. A property declared as static can not + * be accessed with an instantiated class object (though a static method can). + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// Class constants can always be accessed statically +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs 'I am static'; + +// Instantiate classes using new +$my_class = new MyClass('An instance property'); +// The parentheses are optional if not passing in an argument. + +// Access class members using -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Sat, 31 Oct 2015 14:37:12 +0300 Subject: Add binary number example. --- php.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 7b0cf61c..d03b89fe 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -54,6 +54,8 @@ $int1 = 12; // => 12 $int2 = -12; // => -12 $int3 = 012; // => 10 (a leading 0 denotes an octal number) $int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) +// Binary integer literals are available since PHP 5.4.0. +$int5 = 0b11111111; // 255 (a leading 0b denotes a binary number) // Floats (aka doubles) $float = 1.234; @@ -117,11 +119,11 @@ echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid' // a valid constant name starts with a letter or underscore, // followed by any number of letters, numbers, or underscores. -define("FOO", "something"); +define("FOO", "something"); // access to a constant is possible by calling the choosen name without a $ echo FOO; // Returns 'something' -echo 'This outputs '.FOO; // Returns 'This ouputs something' +echo 'This outputs ' . FOO; // Returns 'This ouputs something' -- cgit v1.2.3 From 608615360c7f49cb33c9e7eb3957e031b9b8a89c Mon Sep 17 00:00:00 2001 From: Niko Weh Date: Sat, 31 Oct 2015 22:37:13 +1000 Subject: [haskell/en] Extended section on GHCi - Added the :i command, as i feel that it is as useful as :t. - Added another example for :t, hopefully showcasing it's flexibility - For consistency, changed the name of (.) from function to operator (as is already the case with ($)), and added a short remark in the GHCi section that (most) operators are also functions. --- haskell.html.markdown | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 936744a0..940cf4c7 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -193,7 +193,7 @@ foo = (+10) foo 5 -- 15 -- function composition --- the (.) function chains functions together. +-- the operator `.` chains functions together. -- For example, here foo is a function that takes a value. It adds 10 to it, -- multiplies the result of that by 4, and then returns the final value. foo = (*4) . (+10) @@ -401,11 +401,26 @@ main'' = do let foo = 5 --- You can see the type of any value with `:t`: +-- You can see the type of any value or expression with `:t`: ->:t foo +> :t foo foo :: Integer +-- Operators, such as `+`, `:` and `$`, are functions. +-- Their type can be inspected by putting the operator in parentheses: + +> :t (:) +(:) :: a -> [a] -> [a] + +-- You can get additional information on any `name` using `:i`: + +> :i (+) +class Num a where + (+) :: a -> a -> a + ... + -- Defined in ‘GHC.Num’ +infixl 6 + + -- You can also run any action of type `IO ()` > sayHello -- cgit v1.2.3 From b336e810865a1a2ce54c53b467bcd1545455a679 Mon Sep 17 00:00:00 2001 From: Pavel Kazlou Date: Sat, 31 Oct 2015 16:12:18 +0300 Subject: removed controversial performance info, fixed recursion info and typos --- scala.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..13e8d9d8 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -231,7 +231,7 @@ r foreach println (5 to 1 by -1) foreach (println) -// A while loops +// A while loop var i = 0 while (i < 10) { println("i " + i); i += 1 } @@ -239,17 +239,18 @@ while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why i // Show the value of i. Note that while is a loop in the classical sense - // it executes sequentially while changing the loop variable. while is very - // fast, faster that Java loops, but using the combinators and - // comprehensions above is easier to understand and parallelize + // fast, but using the combinators and comprehensions above is easier + // to understand and parallelize -// A do while loop +// A do-while loop i = 0 do { println("i is still less than 10") i += 1 } while (i < 10) -// Tail recursion is an idiomatic way of doing recurring things in Scala. +// Recursion is the idiomatic way of repeating an action in Scala (as in most +// other functional languages). // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. def showNumbersInRange(a: Int, b: Int): Unit = { @@ -267,7 +268,7 @@ val x = 10 if (x == 1) println("yeah") if (x == 10) println("yeah") if (x == 11) println("yeah") -if (x == 11) println ("yeah") else println("nay") +if (x == 11) println("yeah") else println("nay") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -- cgit v1.2.3 From 3dbcf1c2c6092b0287bae150eec2271446f95927 Mon Sep 17 00:00:00 2001 From: Pavel Kazlou Date: Sat, 31 Oct 2015 16:22:59 +0300 Subject: added docs for multi-variable tuple assignment --- scala.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..4ba9a31b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -321,9 +321,15 @@ divideInts(10, 3) // (Int, Int) = (3,1) val d = divideInts(10, 3) // (Int, Int) = (3,1) d._1 // Int = 3 - d._2 // Int = 1 +// Alternatively you can do multiple-variable assignment to tuple, which is more +// convenient and readable in many cases +val (div, mod) = divideInts(10, 3) + +div // Int = 3 +mod // Int = 1 + ///////////////////////////////////////////////// // 5. Object Oriented Programming -- cgit v1.2.3 From d47f06345b37cecf4072523c1c79f63f37846d8c Mon Sep 17 00:00:00 2001 From: Pavel Kazlou Date: Sat, 31 Oct 2015 16:50:40 +0300 Subject: added docs for default case in pattern matching --- scala.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..131bd71c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -454,6 +454,9 @@ def matchEverything(obj: Any): String = obj match { // You can nest patterns: case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" + + // Match any case (default) if all previous haven't matched + case _ => "Got unknown object" } // In fact, you can pattern match any object with an "unapply" method. This -- cgit v1.2.3 From a11e01b82162ad43db9b4f751ead0fdd09ad3fb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20P=C3=A9rez?= Date: Sat, 31 Oct 2015 15:32:24 +0100 Subject: Translate learn PHP to es-es --- es-es/php-es.html.markdown | 714 +++++++++++++++++++++++---------------------- 1 file changed, 358 insertions(+), 356 deletions(-) diff --git a/es-es/php-es.html.markdown b/es-es/php-es.html.markdown index a8276e53..fa52353c 100644 --- a/es-es/php-es.html.markdown +++ b/es-es/php-es.html.markdown @@ -9,121 +9,121 @@ lang: es-es filename: learnphp-es.php --- -This document describes PHP 5+. +Este documento explica el funcionamiento de PHP 5+. ```php - -Hello World Again! +¡Hola Mundo de nuevo! 12 $int2 = -12; // => -12 -$int3 = 012; // => 10 (a leading 0 denotes an octal number) -$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) +$int3 = 012; // => 10 (un 0 al comienzo declara un número octal) +$int4 = 0x0F; // => 15 (un 0x al comienzo declara un hexadecimal) -// Floats (aka doubles) +// Floats (también conocidos como doubles) $float = 1.234; $float = 1.2e3; $float = 7E-10; -// Delete variable +// Eliminar variable unset($int1); -// Arithmetic -$sum = 1 + 1; // 2 -$difference = 2 - 1; // 1 -$product = 2 * 2; // 4 -$quotient = 2 / 1; // 2 +// Operaciones aritméticas +$suma = 1 + 1; // 2 +$diferencia = 2 - 1; // 1 +$producto = 2 * 2; // 4 +$cociente = 2 / 1; // 2 -// Shorthand arithmetic -$number = 0; -$number += 1; // Increment $number by 1 -echo $number++; // Prints 1 (increments after evaluation) -echo ++$number; // Prints 3 (increments before evaluation) -$number /= $float; // Divide and assign the quotient to $number +// Operaciones aritméticas de escritura rápida +$numero = 0; +$numero += 1; // Incrementa $numero en 1 +echo $numero++; // Imprime 1 (incremento después la evaluación) +echo ++$numero; // Imprime 3 (incremento antes de la evaluación) +$numero /= $float; // Divide y asigna el cociente a $numero -// Strings should be enclosed in single quotes; +// Las cadenas de caracteres deben declararse entre comillas simples $sgl_quotes = '$String'; // => '$String' -// Avoid using double quotes except to embed other variables +// Evita utilizar comillas dobles excepto para embeber otras variables $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' -// Special characters are only escaped in double quotes -$escaped = "This contains a \t tab character."; -$unescaped = 'This just contains a slash and a t: \t'; +// Los caracteres especiales solo son válidos entre comillas dobles +$escaped = "Esto contiene \t un caracter tabulador."; +$unescaped = 'Esto solo contiene una barra y una t: \t'; -// Enclose a variable in curly braces if needed -$money = "I have $${number} in the bank."; +// Rodea una variable entre corchetes si es necesario +$dinero = "Tengo $${numero} en el banco."; -// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +// Desde PHP 5.3, los nowdocs pueden ser utilizados para multilíneas no interpoladas $nowdoc = <<<'END' Multi line string END; -// Heredocs will do string interpolation +// Heredocs interpola cadenas de caracteres $heredoc = << 1, 'Two' => 2, 'Three' => 3); +// Funciona con todas las versiones de php +$asociativo = array('Uno' => 1, 'Dos' => 2, 'Tres' => 3); -// PHP 5.4 introduced a new syntax -$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; +// PHP 5.4 introdujo una nueva sintaxis +$asociativo = ['Uno' => 1, 'Dos' => 2, 'Tres' => 3]; -echo $associative['One']; // prints 1 +echo $asociativo['Uno']; // imprime 1 -// List literals implicitly assign integer keys -$array = ['One', 'Two', 'Three']; -echo $array[0]; // => "One" +// Lista literales implícitamente asignados con claves enteras +$array = ['Uno', 'Dos', 'Tres']; +echo $array[0]; // => "Uno" -// Add an element to the end of an array -$array[] = 'Four'; -// or -array_push($array, 'Five'); +// Añadir un elemento al final de un array +$array[] = 'Cuatro'; +// o +array_push($array, 'Cinco'); -// Remove element from array +// Eliminar un elemento de un array unset($array[3]); /******************************** - * Output + * Salidas por pantalla */ -echo('Hello World!'); -// Prints Hello World! to stdout. -// Stdout is the web page if running in a browser. +echo('¡Hola Mundo!'); +// Imprime ¡Hola Mundo! en stdout. +// Stdout es la página web si se está ejecutando en un navegador. -print('Hello World!'); // The same as echo +print('!Hola Mundo!'); // Es lo mismo que echo -// echo and print are language constructs too, so you can drop the parentheses -echo 'Hello World!'; -print 'Hello World!'; +// No es necesario el paréntesis en echo y print +echo '¡Hola Mundo!'; +print '¡Hola Mundo!'; -$paragraph = 'paragraph'; +$parrafo = 'parrafo'; -echo 100; // Echo scalar variables directly -echo $paragraph; // or variables +echo 100; // Haz echo de escalares directamente +echo $parrafo; // o de variables -// If short open tags are configured, or your PHP version is -// 5.4.0 or greater, you can use the short echo syntax +// Si las etiquetas cortas estás configuradas y tu versión de PHP es +// la 5.4.0 o superior, puede utilizar la sintaxis abreviada de echo ?> -

+

2 echo $z; // => 2 @@ -194,179 +194,178 @@ $y = 0; echo $x; // => 2 echo $z; // => 0 -// Dumps type and value of variable to stdout -var_dump($z); // prints int(0) +// Dump muestra el tipo y valor de una variable en stdout +var_dump($z); // imprime int(0) -// Prints variable to stdout in human-readable format -print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) +// Para mostrar el valor de una variable en un formato legible para humanos +print_r($array); // imprime: Array ( [0] => Uno [1] => Dos [2] => Tres ) /******************************** - * Logic + * Lógica */ $a = 0; $b = '0'; $c = '1'; $d = '1'; -// assert throws a warning if its argument is not true +// assert lanza una advertencia si su argumento no es verdadero -// These comparisons will always be true, even if the types aren't the same. -assert($a == $b); // equality -assert($c != $a); // inequality -assert($c <> $a); // alternative inequality +// Estas comparaciones siempre serán verdaderas, incluso si los tipos no son los mismos. +assert($a == $b); // igualdad +assert($c != $a); // desigualdad +assert($c <> $a); // desigualdad alternativa assert($a < $c); assert($c > $b); assert($a <= $b); assert($c >= $d); -// The following will only be true if the values match and are the same type. +// Los siguiente solo será verdadero si los valores coinciden y son del mismo tipo. assert($c === $d); assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); -// 'Spaceship' operator (since PHP 7) -// Returns 0 if values on either side are equal -// Returns 1 if value on the left is greater -// Returns -1 if the value on the right is greater +// Operador 'Spaceship' (desde PHP 7) +// Devuelve 0 si ambos valores son iguales +// Devuelve 1 si el valor de la izquierda es mayor +// Devuelve -1 si el valor de la derecha es mayor $a = 100; $b = 1000; -echo $a <=> $a; // 0 since they are equal -echo $a <=> $b; // -1 since $a < $b -echo $b <=> $a; // 1 since $b > $a +echo $a <=> $a; // 0 porque son iguales +echo $a <=> $b; // -1 porque $a < $b +echo $b <=> $a; // 1 porque $b > $a -// Variables can be converted between types, depending on their usage. +// Las variables pueden ser convertidas entre tipos, dependiendo de su uso. -$integer = 1; -echo $integer + $integer; // => 2 +$entero = 1; +echo $entero + $entero; // => 2 $string = '1'; -echo $string + $string; // => 2 (strings are coerced to integers) +echo $string + $string; // => 2 (los strings son convertidos a enteros) -$string = 'one'; +$string = 'uno'; echo $string + $string; // => 0 -// Outputs 0 because the + operator cannot cast the string 'one' to a number +// Muestra un 0 porque el operador + no puede convertir la cadena de caracteres 'uno' a un número -// Type casting can be used to treat a variable as another type +// La conversión de tipos puede ser utilizada para tratar a una variable como otro tipo $boolean = (boolean) 1; // => true -$zero = 0; -$boolean = (boolean) $zero; // => false +$cero = 0; +$boolean = (boolean) $cero; // => false -// There are also dedicated functions for casting most types -$integer = 5; -$string = strval($integer); +// También hay funciones dedicadas a la conversión de tipos +$entero = 5; +$string = strval($entero); -$var = null; // Null value +$var = null; // Valor nulo /******************************** - * Control Structures + * Estructuras de control */ if (true) { - print 'I get printed'; + print 'He sido imprimido'; } if (false) { - print 'I don\'t'; + print 'Yo no'; } else { - print 'I get printed'; + print 'He sido imprimido'; } if (false) { - print 'Does not get printed'; + print 'No se imprime'; } elseif(true) { - print 'Does'; + print 'Sí se imprime'; } -// ternary operator -print (false ? 'Does not get printed' : 'Does'); +// operador ternario +print (false ? 'No se imprime' : 'Sí se imprime'); -// ternary shortcut operator since PHP 5.3 -// equivalent of "$x ? $x : 'Does'"" +// atajo para el operador ternario desde PHP 5.3 +// equivalente de "$x ? $x : 'Sí'"" $x = false; -print($x ?: 'Does'); +print($x ?: 'Sí'); -// null coalesce operator since php 7 +// operador 'no definido' desde php 7 $a = null; -$b = 'Does print'; -echo $a ?? 'a is not set'; // prints 'a is not set' -echo $b ?? 'b is not set'; // prints 'Does print' +$b = 'Imprime'; +echo $a ?? 'a no está definido'; // imprime 'a no está definido' +echo $b ?? 'b no está definido'; // imprime 'Imprime' $x = 0; if ($x === '0') { - print 'Does not print'; + print 'No imprime'; } elseif($x == '1') { - print 'Does not print'; + print 'No imprime'; } else { - print 'Does print'; + print 'Imprime'; } -// This alternative syntax is useful for templates: +// Esta sintaxis alternativa se utiliza para plantillas: ?> -This is displayed if the test is truthy. +Esto se muestra si la evaluación es verdadera. -This is displayed otherwise. +En otro caso, se muestra esto. 2, 'car' => 4]; +$ruedas = ['bicicleta' => 2, 'coche' => 4]; -// Foreach loops can iterate over arrays -foreach ($wheels as $wheel_count) { - echo $wheel_count; -} // Prints "24" +// Los bucles foreach pueden iterar por arrays +foreach ($ruedas as $numero_ruedas) { + echo $numero_ruedas; +} // Imprime "24" echo "\n"; -// You can iterate over the keys as well as the values -foreach ($wheels as $vehicle => $wheel_count) { - echo "A $vehicle has $wheel_count wheels"; +// También se puede iterar sobre las claves, así como sobre los valores +foreach ($ruedas as $vehiculo => $numero_ruedas) { + echo "Un $vehiculo tiene $numero_ruedas ruedas"; } echo "\n"; @@ -374,45 +373,45 @@ echo "\n"; $i = 0; while ($i < 5) { if ($i === 3) { - break; // Exit out of the while loop + break; // Sale fuera del bucle while } echo $i++; -} // Prints "012" +} // Imprime "012" for ($i = 0; $i < 5; $i++) { if ($i === 3) { - continue; // Skip this iteration of the loop + continue; // Se salta esta iteración del bucle } echo $i; -} // Prints "0124" +} // Imprime "0124" /******************************** - * Functions + * Funciones */ -// Define a function with "function": -function my_function () { - return 'Hello'; +// Define una función con "function": +function mi_funcion () { + return 'Hola'; } -echo my_function(); // => "Hello" +echo mi_funcion(); // => "Hola" -// A valid function name starts with a letter or underscore, followed by any -// number of letters, numbers, or underscores. +// Un nombre válido de función comienza con una letra o guión bajo, seguido de cualquier +// número de letras, números o guiones bajos. -function add ($x, $y = 1) { // $y is optional and defaults to 1 - $result = $x + $y; - return $result; +function anadir ($x, $y = 1) { // $y es opcional y por defecto es 1 + $resultado = $x + $y; + return $resultado; } -echo add(4); // => 5 -echo add(4, 2); // => 6 +echo anadir(4); // => 5 +echo anadir(4, 2); // => 6 -// $result is not accessible outside the function -// print $result; // Gives a warning. +// $resultado no es accesible fuera de la función +// print $resultado; // Devuelve una advertencia. -// Since PHP 5.3 you can declare anonymous functions; +// Desde PHP 5.3 se pueden declarar funciones anónimas $inc = function ($x) { return $x + 1; }; @@ -423,28 +422,28 @@ function foo ($x, $y, $z) { echo "$x - $y - $z"; } -// Functions can return functions +// Las funciones pueden devolver funciones function bar ($x, $y) { - // Use 'use' to bring in outside variables + // Utiliza 'use' para meter variables de fuera de la función return function ($z) use ($x, $y) { foo($x, $y, $z); }; } $bar = bar('A', 'B'); -$bar('C'); // Prints "A - B - C" +$bar('C'); // Imprime "A - B - C" -// You can call named functions using strings -$function_name = 'add'; -echo $function_name(1, 2); // => 3 -// Useful for programatically determining which function to run. -// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); +// Puedes llamar a funciones utilizando cadenas de caracteres +$nombre_funcion = 'add'; +echo $nombre_funcion(1, 2); // => 3 +// Es útil para determinarl qué función ejecutar. +// O, utiliza call_user_func(callable $callback [, $parameter [, ... ]]); -// You can get the all the parameters passed to a function -function parameters() { - $numargs = func_num_args(); - if ($numargs > 0) { +// Puedes obtener todos los parámetros pasados a una función +function parametros() { + $numero_argumentos = func_num_args(); + if ($numero_argumentos > 0) { echo func_get_arg(0) . ' | '; } $args_array = func_get_args(); @@ -453,151 +452,153 @@ function parameters() { } } -parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | +parametros('Hola', 'Mundo'); // Hola | 0 - Hola | 1 - Mundo | -// Since PHP 5.6 you can get a variable number of arguments -function variable($word, ...$list) { - echo $word . " || "; - foreach ($list as $item) { +// Desde PHP 5.6 se puede obtener un número variable de argumentos +function variable($palabra, ...$lista) { + echo $palabra . " || "; + foreach ($lista as $item) { echo $item . ' | '; } } -variable("Separate", "Hello", "World") // Separate || Hello | World | +variable("Separa", "Hola", "Mundo") // Separa || Hola | Mundo | /******************************** * Includes */ instanceProp = $instanceProp; } - // Methods are declared as functions inside a class - public function myMethod() + // Los métodos son declarados como funciones dentro de una clase + public function miMetodo() { - print 'MyClass'; + print 'MiClase'; } - //final keyword would make a function unoverridable - final function youCannotOverrideMe() + // la palabra clave final hará una función no sobreescribible + final function noMePuedesSobreEscribir() { } /* - * Declaring class properties or methods as static makes them accessible without - * needing an instantiation of the class. A property declared as static can not - * be accessed with an instantiated class object (though a static method can). + * Declarar propiedades de clase o métodos como estáticos los hace accesibles sin + * necesidad de instanciar la clase. Una propiedad declarada como estática no + * puede ser accedida mediante una instancia de la clase, pero sí mediante un + * método estático. */ - public static function myStaticMethod() + public static function miMetodoEstatico() { - print 'I am static'; + print 'Soy estático'; } } -// Class constants can always be accessed statically -echo MyClass::MY_CONST; // Outputs 'value'; +// Las constantes de una clase siempre pueden ser accedidas estáticamente +echo MiClase::MI_CONSTANTE; // Muestra 'valor'; -echo MyClass::$staticVar; // Outputs 'static'; -MyClass::myStaticMethod(); // Outputs 'I am static'; +echo MiClase::$staticVar; // Muestra 'static'; +MiClase::miMetodoEstatico(); // Muestra 'Soy estático'; -// Instantiate classes using new -$my_class = new MyClass('An instance property'); -// The parentheses are optional if not passing in an argument. +// Instancia una clase usando new +$mi_clase = new MiClase('Una instancia'); +// Los paréntesis son opcionales si no se pasa ningún argumento. -// Access class members using -> -echo $my_class->property; // => "public" -echo $my_class->instanceProp; // => "An instance property" -$my_class->myMethod(); // => "MyClass" +// Accede a los miembros de una clase utilizando -> +echo $mi_clase->propiedad; // => "public" +echo $mi_clase->instanceProp; // => "Una instancia" +$mi_clase->miMetodo(); // => "MiClase" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Extender clases utilizando "extends" +class MiOtraClase extends MiClase { - function printProtectedProperty() + function imprimePropiedadProtegida() { echo $this->prot; } - // Override a method - function myMethod() + // Sobreescribe un método + function miMetodo() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::miMetodo(); + print ' > MiOtraClase'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$mi_otra_clase = new MiOtraClase('Propiedad de instancia'); +$mi_otra_clase->imprimePropiedadProtegida(); // => Imprime "protected" +$mi_otra_clase->miMetodo(); // Imprime "MiClase > MiOtraClase" -final class YouCannotExtendMe +final class NoMePuedesExtender { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Puedes utilizar "métodos mágicos" para crear los getters y setters +class MiClaseMapeada { - private $property; + private $propiedad; public function __get($key) { @@ -610,60 +611,60 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new MiClaseMapeada(); +echo $x->propiedad; // Utilizará el método __get() +$x->propiedad = 'Algo'; // Utilizará el método __set() -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Las clases pueden ser abstractas (utilizando la palabra clave abstract) o +// implementando interfaces (utilizando la palabra clave implements). +// Una interfaz puede ser declarada con la palabra clave interface. -interface InterfaceOne +interface InterfazUno { - public function doSomething(); + public function hazAlgo(); } -interface InterfaceTwo +interface InterfazDos { - public function doSomethingElse(); + public function hazOtraCosa(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// las interfaces pueden ser extendidas +interface InterfazTres extends InterfazDos { - public function doAnotherContract(); + public function hazCualquierOtraCosa(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class MiClaseAbstracta implements InterfazUno { - public $x = 'doSomething'; + public $x = 'hazAlgo'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class MiOtraClase extends MiClaseAbstracta implements InterfazDos { - public function doSomething() + public function hazAlgo() { echo $x; } - public function doSomethingElse() + public function hazOtraCosa() { - echo 'doSomethingElse'; + echo 'hazOtraCosa'; } } -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Las clases pueden implementar más de una interfaz +class CualquierOtraClase implements InterfazUno, InterfazDos { - public function doSomething() + public function hazAlgo() { - echo 'doSomething'; + echo 'hazAlgo'; } - public function doSomethingElse() + public function hazOtraCosa() { - echo 'doSomethingElse'; + echo 'hazOtraCosa'; } } @@ -672,65 +673,65 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo * Traits */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Los traits están disponibles desde PHP 5.4.0 y son declarados utilizando "trait" -trait MyTrait +trait MiTrait { - public function myTraitMethod() + public function miMetodoTrait() { - print 'I have MyTrait'; + print 'Tengo trait'; } } -class MyTraitfulClass +class MiClaseTrait { - use MyTrait; + use MiTrait; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$cls = new MiClaseTrait(); +$cls->miMetodoTrait(); // Imprime "Tengo trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Esta sección está separada porque una declaración de namespace debe +// ser la primera sentencia en un archivo. Vamos a suponer que no es el caso Date: Sat, 31 Oct 2015 15:39:50 +0100 Subject: Improvements to the german LaTeX document. Fix a sentence, added a command to be able to define multiline comment blocks. Additionally, make use of the \LaTeX command to correctly show the LaTeX logo. --- de-de/latex-de.html.markdown | 91 +++++++++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 40 deletions(-) diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown index 2c18b8fd..ee9c6e3e 100644 --- a/de-de/latex-de.html.markdown +++ b/de-de/latex-de.html.markdown @@ -6,19 +6,19 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] translators: - ["Moritz Kammerer", "https://github.com/phxql"] + - ["Jerome Meinke", "https://github.com/jmeinke"] lang: de-de filename: latex-de.tex --- ``` -% Alle Kommentare starten fangen mit % an -% Es gibt keine Kommentare über mehrere Zeilen +% Alle Kommentare starten mit einem Prozentzeichen % -% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. +% LaTeX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. % MS Word oder OpenOffice Writer -% Jedes LateX-Kommando startet mit einem Backslash (\) +% Jedes LaTeX-Kommando startet mit einem Backslash (\) -% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen +% LaTeX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen % Weitere Dokumententypen sind z.B. book, report, presentations, etc. % Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall % wollen wir einen 12 Punkte-Font verwenden. @@ -26,7 +26,7 @@ filename: latex-de.tex % Als nächstes definieren wir die Pakete, die wir verwenden wollen. % Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest, -% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern. +% musst du die Fähigkeiten von LaTeX durch Hinzufügen von Paketen erweitern. % Wir verwenden die Pakete float und caption für Bilder. \usepackage{caption} \usepackage{float} @@ -34,30 +34,41 @@ filename: latex-de.tex % Mit diesem Paket können leichter Umlaute getippt werden \usepackage[utf8]{inputenc} +% Es gibt eigentlich keine Kommentare über mehrere Zeilen, solche kann man +% aber selbst durch die Angabe eigener Kommandos definieren. +% Dieses Kommando kann man später benutzen. +\newcommand{\comment}[1]{} + % Es können durchaus noch weitere Optione für das Dokument gesetzt werden! \author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} \date{\today} -\title{Learn LaTeX in Y Minutes!} +\title{Learn \LaTeX\ in Y Minutes!} % Nun kann's losgehen mit unserem Dokument. % Alles vor dieser Zeile wird die Preamble genannt. -\begin{document} +\begin{document} + +\comment{ + Dies ist unser selbst-definierter Befehl + für mehrzeilige Kommentare. +} + % Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann -% LateX für uns eine Titelseite generieren +% LaTeX für uns eine Titelseite generieren \maketitle -% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an. +% Die meisten Paper haben ein Abstract. LaTeX bietet dafür einen vorgefertigen Befehl an. % Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem % Inhalt erscheinen. % Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. \begin{abstract} - LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee! + \LaTeX -Documentation geschrieben in \LaTeX ! Wie ungewöhnlich und garantiert nicht meine Idee! \end{abstract} % Section Befehle sind intuitiv. % Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen. \section{Einleitung} -Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen! +Hi, mein Name ist Moritz und zusammen werden wir \LaTeX\ erforschen! \section{Noch eine section} Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection. @@ -71,16 +82,16 @@ So ist's schon viel besser. % Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung. % Das funktioniert auch bei anderen Befehlen. -\section*{Das ist eine unnummerierte section} -Es müssen nicht alle sections nummeriert sein! +\section*{Das ist eine unnummerierte section} +Es müssen nicht alle Sections nummeriert sein! \section{Ein paar Notizen} -LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. +\LaTeX\ ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge \textbackslash\textbackslash in den Code ein.\\ \section{Listen} -Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen, +Listen sind eine der einfachsten Dinge in \LaTeX. Ich muss morgen einkaufen gehen, also lass uns eine Einkaufsliste schreiben: \begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung. % \item bringt enumerate dazu, eins weiterzuzählen. @@ -96,7 +107,7 @@ also lass uns eine Einkaufsliste schreiben: \section{Mathe} -Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen +Einer der Haupteinsatzzwecke von \LaTeX\ ist das Schreiben von akademischen Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle Symbole zu unserem Paper hinzuzufügen! \\ @@ -106,18 +117,18 @@ Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstabe um nur ein paar zu nennen.\\ Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen -Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ +Papern. So schreibt man in \LaTeX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ -% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben, +% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LaTeX schreiben, % geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings % nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und % ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden. Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$. -Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt! +Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den \LaTeX nicht kennt! Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten: -Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), +Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), Logarithmus und Exponenten ($\log$, $\exp$), Grenzwerte ($\lim$), etc. haben vordefinierte Befehle. Lass uns eine Gleichung schreiben: \\ @@ -127,7 +138,7 @@ $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\ Brüche (Zähler / Nenner) können so geschrieben werden: % 10 / 7 -$^{10}/_{7}$ +$^{10}/_{7}$ % Komplexere Brüche können so geschrieben werden: % \frac{Zähler}{Nenner} @@ -142,19 +153,19 @@ Wir können Gleichungen auch in einer equation Umgebung verwenden. \end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen Wir können nun unsere Gleichung referenzieren! -Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in +Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden: Grafiken, Gleichungen, Sections, etc. Summen und Integrale können mit den sum und int Befehlen dargestellt werden: -% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen -\begin{equation} +% Manche LaTeX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen +\begin{equation} \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} +\end{equation} +\begin{equation} \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} +\end{equation} \section{Grafiken} @@ -164,7 +175,7 @@ Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt. \begin{figure}[H] % H ist die Platzierungsoption \centering % Zentriert die Grafik auf der Seite % Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} + %\includegraphics[width=0.8\linewidth]{right-triangle.png} % Auskommentiert, damit es nicht im Dokument auftaucht. \caption{Dreieck mit den Seiten $a$, $b$, $c$} \label{fig:right-triangle} @@ -177,7 +188,7 @@ Wir können Tabellen genauso wie Grafiken einfügen. \caption{Überschrift der Tabelle.} % Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll. % Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal. - \begin{tabular}{c|cc} + \begin{tabular}{c|cc} Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt \hline % Eine horizontale Linie 1 & Biggus & Dickus \\ @@ -187,36 +198,36 @@ Wir können Tabellen genauso wie Grafiken einfügen. % \section{Links} % Kommen bald! -\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)} -Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll -in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren, +\section{Verhindern, dass \LaTeX\ etwas kompiliert (z.B. Quelltext)} +Angenommen, wir wollen Quelltext in unserem \LaTeX-Dokument. \LaTeX\ soll +in diesem Fall nicht den Quelltext als \LaTeX-Kommandos interpretieren, sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden wir eine verbatim Umgebung. % Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.) % aber verbatim ist das simpelste. -\begin{verbatim} +\begin{verbatim} print("Hello World!") a%b; % Schau dir das an! Wir können % im verbatim verwenden! random = 4; #decided by fair random dice roll \end{verbatim} -\section{Kompilieren} +\section{Kompilieren} Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\ Dafür musst du folgende Schritte durchführen: \begin{enumerate} - \item Schreibe das Dokument. (den LateX-Quelltext). - \item Kompiliere den Quelltext in ein PDF. + \item Schreibe das Dokument. (den \LaTeX -Quelltext). + \item Kompiliere den Quelltext in ein PDF. Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\ - \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf \end{verbatim} \end{enumerate} -Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt +Manche \LaTeX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt 2 wird unsichtbar im Hintergrund ausgeführt. Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet -- cgit v1.2.3 From c0b2ccdb43ab8b49cfdab277c8cc266abf532bd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20P=C3=A9rez?= Date: Sat, 31 Oct 2015 15:45:36 +0100 Subject: Create latex es-es file --- es-es/latex-es.html.markdown | 239 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 es-es/latex-es.html.markdown diff --git a/es-es/latex-es.html.markdown b/es-es/latex-es.html.markdown new file mode 100644 index 00000000..11bac4fc --- /dev/null +++ b/es-es/latex-es.html.markdown @@ -0,0 +1,239 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Mario Pérez", "https://github.com/MarioPerezEsteso"] +filename: learn-latex-es.tex +--- + +```tex +% All comment lines start with % +% There are no multi-line comments + +% LaTeX is NOT a "What You See Is What You Get" word processing software like +% MS Word, or OpenOffice Writer + +% Every LaTeX command starts with a backslash (\) + +% LaTeX documents start with a defining the type of document it's compiling +% Other document types include book, report, presentations, etc. +% The options for the document appear in the [] brackets. In this case +% it specifies we want to use 12pt font. +\documentclass[12pt]{article} + +% Next we define the packages the document uses. +% If you want to include graphics, colored text, or +% source code from another language file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. +% I'm going to include the float and caption packages for figures. +\usepackage{caption} +\usepackage{float} + +% We can define some other document properties too! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Now we're ready to begin the document +% Everything before this line is called "The Preamble" +\begin{document} +% if we set the author, date, title fields, we can have LaTeX +% create a title page for us. +\maketitle + +% Most research papers have abstract, you can use the predefined commands for this. +% This should appear in its logical order, therefore, after the top matter, +% but before the main sections of the body. +% This command is available in the document classes article and report. +\begin{abstract} + LaTeX documentation written as LaTeX! How novel and totally not my idea! +\end{abstract} + +% Section commands are intuitive. +% All the titles of the sections are added automatically to the table of contents. +\section{Introduction} +Hello, my name is Colton and together we're going to explore LaTeX! + +\section{Another section} +This is the text for another section. I think it needs a subsection. + +\subsection{This is a subsection} % Subsections are also intuitive. +I think we need another one + +\subsubsection{Pythagoras} +Much better now. +\label{subsec:pythagoras} + +% By using the asterisk we can suppress LaTeX's inbuilt numbering. +% This works for other LaTeX commands as well. +\section*{This is an unnumbered section} +However not all sections have to be numbered! + +\section{Some Text notes} +LaTeX is generally pretty good about placing text where it should go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to +the source code. \\ + +\section{Lists} +Lists are one of the easiest things to create in LaTeX! I need to go shopping +tomorrow, so let's make a grocery list. +\begin{enumerate} % This creates an "enumerate" environment. + % \item tells the enumerate to increment + \item Salad. + \item 27 watermelon. + \item A single jackrabbit. + % we can even override the item number by using [] + \item[how many?] Medium sized squirt guns. + + Not a list item, but still part of the enumerate. + +\end{enumerate} % All environments must have an end. + +\section{Math} + +One of the primary uses for LaTeX is to produce academic articles or +technical papers. Usually in the realm of math and science. As such, +we need to be able to add special symbols to our paper! \\ + +Math has many symbols, far beyond what you can find on a keyboard; +Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ + +Sets and relations play a vital role in many mathematical research papers. +Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ +% Notice how I needed to add $ signs before and after the symbols. This is +% because when writing, we are in text-mode. +% However, the math symbols only exist in math-mode. +% We can enter math-mode from text mode with the $ signs. +% The opposite also holds true. Variable can also be rendered in math-mode. +% We can also enter math mode with \[\] + +\[a^2 + b^2 = c^2 \] + +My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. +I haven't found a Greek letter that yet that LaTeX doesn't know about! + +Operators are essential parts of a mathematical document: +trigonometric functions ($\sin$, $\cos$, $\tan$), +logarithms and exponentials ($\log$, $\exp$), +limits ($\lim$), etc. +have per-defined LaTeX commands. +Let's write an equation to see how it's done: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Fractions(Numerator-denominators) can be written in these forms: + +% 10 / 7 +$^{10}/_{7}$ + +% Relatively complex fractions can be written as +% \frac{numerator}{denominator} +$\frac{n!}{k!(n - k)!}$ \\ + +We can also insert equations in an "equation environment". + +% Display math with the equation 'environment' +\begin{equation} % enters math-mode + c^2 = a^2 + b^2. + \label{eq:pythagoras} % for referencing +\end{equation} % all \begin statements must have an end statement + +We can then reference our new equation! +Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also +the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: +figures, equations, sections, etc. + +Summations and Integrals are written with sum and int commands: + +% Some LaTeX compilers will complain if there are blank lines +% In an equation environment. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figures} + +Let's insert a Figure. Figure placement can get a little tricky. +I definitely have to lookup the placement options each time. + +\begin{figure}[H] % H here denoted the placement option. + \centering % centers the figure on the page + % Inserts a figure scaled to 0.8 the width of the page. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Commented out for compilation purposes. Please use your imagination. + \caption{Right triangle with sides $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Table} +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 $ + \hline % a horizontal line + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Hyperlinks} % Coming soon + +\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 we a verbatim +environment. + +% There are other packages that exist (i.e. minty, lstlisting, etc.) +% but verbatim is the bare-bones basic one. +\begin{verbatim} + print("Hello World!") + a%b; % look! We can use % signs in verbatim. + random = 4; #decided by fair random dice roll +\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 compiles). \\ +Getting to the final document using LaTeX consists of the following steps: + \begin{enumerate} + \item Write the document in plain text (the "source code"). + \item Compile source code to produce a pdf. + The compilation step looks something like this (in Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of +software. So, you get to see Step 1, but not Step 2 completely. +Step 2 is still happening behind the scenes. + +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 +format you defined in Step 1. + +\section{End} + +That's all for now! + +% end the document +\end{document} +``` + +## Más información sobre LaTeX + +* El wikilibro LaTeX: [https://es.wikibooks.org/wiki/Manual_de_LaTeX](https://es.wikibooks.org/wiki/Manual_de_LaTeX) +* Un tutorial real: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) -- cgit v1.2.3 From 23b35d9da0b3c1de5ff6a0b262b08020f0f56c4f Mon Sep 17 00:00:00 2001 From: roymiloh Date: Sat, 31 Oct 2015 17:20:03 +0200 Subject: [C#/en] Fix to "extension methods" over using "extension functions", it's more accurate. --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index dfdd98de..d6c503ae 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -630,7 +630,7 @@ on a new line! ""Wow!"", the masses cried"; public static class Extensions { - // EXTENSION FUNCTIONS + // EXTENSION METHODS public static void Print(this object obj) { Console.WriteLine(obj.ToString()); -- cgit v1.2.3 From 09cbaa6536e13dc2e4e20d8222423968cd989492 Mon Sep 17 00:00:00 2001 From: Abdul Alim Date: Sat, 31 Oct 2015 23:28:39 +0800 Subject: [JSON/ms-my] Added Malay (Malaysia) translation for JSON --- ms-my/json-my.html.markdown | 102 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 ms-my/json-my.html.markdown diff --git a/ms-my/json-my.html.markdown b/ms-my/json-my.html.markdown new file mode 100644 index 00000000..2d2da519 --- /dev/null +++ b/ms-my/json-my.html.markdown @@ -0,0 +1,102 @@ +--- +language: json +filename: learnjson-ms.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"] +translators: + - ["abdalim", "https://github.com/abdalim"] +lang: ms-my +--- + +Disebabkan JSON adalah format pertukaran-data yang sangat ringkas, panduan ini +kemungkinan besar adalah Learn X in Y Minutes yang paling mudah. + +JSON dalam bentuk paling aslinya sebenarnya tidak mempunyai sebarang komentar, +tetapi kebanyakan pembaca menerima komen dalam bentuk C (`\\`,`/* */`). Beberapa +pembaca juga bertoleransi terhadap koma terakhir (iaitu koma selepas elemen +terakhir di dalam array atau selepas ciri terakhir sesuatu objek), tetapi semua +ini harus dielakkan dan dijauhkan untuk keserasian yang lebih baik. + +Untuk tujuan ini bagaimanapun, semua di dalam panduan ini adalah 100% JSON yang +sah. Luckily, it kind of speaks for itself. + +Sebuah nilai JSON harus terdiri dari salah satu, iaitu, nombor, string, array, +objek atau salah satu dari nama literal berikut: true, false, null. + +Pelayar web yang menyokong adalah: Firefox 3.5+, Internet Explorer 8.0+, Chrome +1.0+, Opera 10.0+, dan Safari 4.0+. + +Sambungan fail untuk fail - fail JSON adalah ".json" dan jenis MIME untuk teks +JSON adalah "application/json". + +Banyak bahasa aturcara mempunyai fungsi untuk menyirikan (mengekod) dan +menyah-sirikan (men-dekod) data JSON kepada struktur data asal. Javascript +mempunyai sokongon tersirat untuk memanipulasi teks JSON sebagai data. + +Maklumat lebih lanjut boleh dijumpai di http://www.json.org/ + +JSON dibina pada dua struktur: +* Sebuah koleksi pasangan nama/nilai. Di dalam pelbagai bahasa aturcara, ini +direalisasikan sebagai objek, rekod, "struct", "dictionary", "hash table", +senarai berkunci, atau "associative array". +* Sebuah senarai nilai yang tersusun. Dalam kebanyakan bahasa aturcara, ini +direalisasikan sebagai array, vektor, senarai atau urutan. + +Sebuah objek dengan pelbagai pasangan nama/nilai. + +```json +{ + "kunci": "nilai", + + "kekunci": "harus sentiasa dibalut dengan 'double quotes'", + "nombor": 0, + "strings": "Hellø, wørld. Semua unicode dibenarkan, bersama \"escaping\".", + "ada bools?": true, + "tiada apa - apa": null, + + "nombor besar": 1.2e+100, + + "objek": { + "komen": "Sebahagian besar struktur akan terdiri daripada objek.", + + "array": [0, 1, 2, 3, "Array boleh mempunyai sebarang jenis data di dalamnya.", 5], + + "objek lain": { + "komen": "Objek boleh dibina dengan pelbagai lapisan, sangat berguna." + } + }, + + "kebendulan": [ + { + "punca potassium": ["pisang"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "stail alternatif": { + "komen": "cuba lihat ini!" + , "posisi koma": "tidak mengapa - selagi ia adalah sebelum nama atau kunci seterusnya, maka ia sah" + , "komen lain": "sungguh bagus" + } +} +``` + +Sebuah array sahaja yang mengandungi nilai - nilai juga adalah JSON yang sah. + +```json +[1, 2, 3, "text", true] +``` + +Objek - objek boleh menjadi sebahagian dari array juga. + +```json +[{"nama": "Abe", "umur": 25}, {"nama": "Jemah", "umur": 29}, {"name": "Yob", "umur": 31}] +``` -- cgit v1.2.3 From fd512d12fcda159469d9450416a527a0a17f2774 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20P=C3=A9rez?= Date: Sat, 31 Oct 2015 16:45:36 +0100 Subject: Translate learn LaTeX to es-ES --- es-es/latex-es.html.markdown | 241 +++++++++++++++++++------------------------ 1 file changed, 107 insertions(+), 134 deletions(-) diff --git a/es-es/latex-es.html.markdown b/es-es/latex-es.html.markdown index 11bac4fc..6743ad80 100644 --- a/es-es/latex-es.html.markdown +++ b/es-es/latex-es.html.markdown @@ -10,146 +10,131 @@ filename: learn-latex-es.tex --- ```tex -% All comment lines start with % -% There are no multi-line comments +% Todas las líneas comentadas comienzan con % +% No existen los comentarios multilínea -% LaTeX is NOT a "What You See Is What You Get" word processing software like -% MS Word, or OpenOffice Writer +% LaTeX NO es un software de procesamiento de texto que cumple con +% "Lo que ves es lo que tienes" como MS Word u OpenOffice -% Every LaTeX command starts with a backslash (\) +% Todos los comandos de LaTeX comienzan con una contrabarra (\) -% LaTeX documents start with a defining the type of document it's compiling -% Other document types include book, report, presentations, etc. -% The options for the document appear in the [] brackets. In this case -% it specifies we want to use 12pt font. +% Los documentos LaTeX comienzan definiendo el tipo de documento que se va a +% compilar. Algunos tipos de documentos son libros, informes, presentaciones, +% etc. Las opciones para el documento comienzan en los corchetes []. En este +% caso, se especifica que queremos utilizar una fuente de tamaño 12pt. \documentclass[12pt]{article} -% Next we define the packages the document uses. -% If you want to include graphics, colored text, or -% source code from another language file into your document, -% you need to enhance the capabilities of LaTeX. This is done by adding packages. -% I'm going to include the float and caption packages for figures. +% A continuación, definimos los paquetes que utilizará el documento. +% Si quieres incluir gráficos, texto coloreado o código fuente de otro lenguaje, +% debes extender las funciones de LaTeX. Esto se consigue añadiendo paquetes. +% A continuación se incluirán los paquetes float y caption para figuras. \usepackage{caption} \usepackage{float} -% We can define some other document properties too! +% También podemos definir otras propiedades en el documento \author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} \date{\today} \title{Learn LaTeX in Y Minutes!} -% Now we're ready to begin the document -% Everything before this line is called "The Preamble" +% Ahora estamos preparados para comenzar el documento +% Todo lo que se encuentre antes de esta línea se llama "El Preámbulo" \begin{document} -% if we set the author, date, title fields, we can have LaTeX -% create a title page for us. +% Si especificamos el autor, fecha y título, LaTeX creará una página como título +% por nosotros \maketitle -% Most research papers have abstract, you can use the predefined commands for this. -% This should appear in its logical order, therefore, after the top matter, -% but before the main sections of the body. -% This command is available in the document classes article and report. +% La mayoría de los artículos de investigación tienen un abstract. Es posible +% utilizar comandos predefinidos para ello. +% Esto debería aparecer en su orden lógico. Tras el título pero antes de las +% secciones principales del cuerpo. +% Este comando está disponible en los tipos de documentos article y report. \begin{abstract} - LaTeX documentation written as LaTeX! How novel and totally not my idea! + Documentación de LaTex escrita en LaTex. \end{abstract} -% Section commands are intuitive. -% All the titles of the sections are added automatically to the table of contents. -\section{Introduction} -Hello, my name is Colton and together we're going to explore LaTeX! +% Los comandos de sección son intuitivos. +% Todos los títulos de secciones son añadidos automáticamente a la tabla de contenidos. +\section{Introducción} +Hola, mi nombre es Mario Pérez y estoy traduciendo este documento para aprender LaTex. -\section{Another section} -This is the text for another section. I think it needs a subsection. +\section{Otra sección} +Este es el texto de otra sección. Creo que necesitará una subsección. -\subsection{This is a subsection} % Subsections are also intuitive. -I think we need another one +\subsection{Esto es una subsección} % Las subsecciones también son fáciles. +Creo que necesitamos otra más. -\subsubsection{Pythagoras} -Much better now. -\label{subsec:pythagoras} +\subsubsection{Pitágoras} +Mejor ahora. +\label{subsec:pitagoras} -% By using the asterisk we can suppress LaTeX's inbuilt numbering. -% This works for other LaTeX commands as well. -\section*{This is an unnumbered section} -However not all sections have to be numbered! +% Utilizando el asterisco podemos decirle a LaTeX que no ponga los números de secciones y subsecciones. +% Esto también funciona con otros comandos de LaTeX. +\section*{Esto es una sección no numerada} +¡No todas las secciones tienen que estar numeradas! -\section{Some Text notes} -LaTeX is generally pretty good about placing text where it should go. If -a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to -the source code. \\ +\section{Algunas notas} +LaTeX es generalmente bastante bueno situando el texto donde debe ir. Si una lína \\ necesita \\ ser \\ rota \\ puedes poner \textbackslash\textbackslash en el código fuente. \\ -\section{Lists} -Lists are one of the easiest things to create in LaTeX! I need to go shopping -tomorrow, so let's make a grocery list. -\begin{enumerate} % This creates an "enumerate" environment. - % \item tells the enumerate to increment - \item Salad. - \item 27 watermelon. - \item A single jackrabbit. - % we can even override the item number by using [] - \item[how many?] Medium sized squirt guns. +\section{Listas} +Las listas son de las cosas más fáciles de crear en LaTeX. Necesito ir a comprar mañana, así que vamos a crear una lista de la compra. +\begin{enumerate} % Esto crea una lista numerada. + % \item crea un elemento + \item Ensalada. + \item 27 sandías. + \item Pescado. + % podemos incluso sobreescribir el número del ítem usando [] + \item[cuántos?] Plátanos. - Not a list item, but still part of the enumerate. + No es un ítem de la lista, pero sigue siendo parte de la enumeración. -\end{enumerate} % All environments must have an end. +\end{enumerate} % Todos los contextos deben tener un final. -\section{Math} +\section{Matemáticas} -One of the primary uses for LaTeX is to produce academic articles or -technical papers. Usually in the realm of math and science. As such, -we need to be able to add special symbols to our paper! \\ +Uno de los usos principales de LaTeX es la producción de artículos académicos o técnicos. Normalmente relacionados con la ciencia y las matemáticas. Debido a esto, necesitamos poder añadir símbolos especiales a nuestro artículo.\\ -Math has many symbols, far beyond what you can find on a keyboard; -Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ +En matemáticas hay muchos símbolos. Más de los que podemos encontrar en un teclado. Flechas o letras por nombrar un par.\\ -Sets and relations play a vital role in many mathematical research papers. -Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ -% Notice how I needed to add $ signs before and after the symbols. This is -% because when writing, we are in text-mode. -% However, the math symbols only exist in math-mode. -% We can enter math-mode from text mode with the $ signs. -% The opposite also holds true. Variable can also be rendered in math-mode. -% We can also enter math mode with \[\] +Algunos símbolos juegan un papel fundamental en muchos artículos de investigación matemática. Así es como se establece que todo Y pertenece a X: $\forall$ x $\in$ X. \\ +He necesitado añadir el signo $ antes de los símbolos. Esto se debe a que cuando escribimos, estamos en modo texto. Sin embargo, los símbolos solo pueden utilizarse en modo matemático, al cual se entra con el signo $. +% Lo opuesto también se cumple. Una variable también puede ser mostrada en modo matemático, al que también se puede entrar con \[\] \[a^2 + b^2 = c^2 \] -My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. -I haven't found a Greek letter that yet that LaTeX doesn't know about! +Mi letra griega favorita es $\xi$. También me gustan $\beta$, $\gamma$ y $\sigma$. +Todavía no he encontrado una letra griega que LaTeX no conozca. -Operators are essential parts of a mathematical document: -trigonometric functions ($\sin$, $\cos$, $\tan$), -logarithms and exponentials ($\log$, $\exp$), -limits ($\lim$), etc. -have per-defined LaTeX commands. -Let's write an equation to see how it's done: \\ +Los operadores son también una parte esencial de un documento matemático: +funciones trigonométricas ($\sin$, $\cos$, $\tan$), logaritmos y exponenciales ($\log$, $\exp$), límites ($\lim$), etc. tienen comandos predefinidos en LaTeX. + +Vamos a escribir una ecuación para ver cómo se hace: \\ $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ -Fractions(Numerator-denominators) can be written in these forms: +Las fracciones (numeradores-denominadores) pueden escribirse de la siguiente forma: % 10 / 7 $^{10}/_{7}$ -% Relatively complex fractions can be written as -% \frac{numerator}{denominator} +% Las fracciones relativamente complejas pueden escribirse como +% \frac{numerador}{denominador} $\frac{n!}{k!(n - k)!}$ \\ -We can also insert equations in an "equation environment". +También podemos insertar ecuaciones en un contexto de ecuación. -% Display math with the equation 'environment' -\begin{equation} % enters math-mode +% Mostrar matemáticas en el contexto de ecuaciones +\begin{equation} % entra en modo matemático c^2 = a^2 + b^2. - \label{eq:pythagoras} % for referencing -\end{equation} % all \begin statements must have an end statement + \label{eq:pitagoras} % para referencias +\end{equation} % Todos los contextos deben tener un final. -We can then reference our new equation! -Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also -the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: -figures, equations, sections, etc. +Podemos referenciar nuestra nueva ecuación. +Ecuación ~\ref{eq:pythagoras} también se conoce como el Teorema de Pitágoras, el cual también se encuentra en la sección ~\ref{subsec:pythagoras}. Muchas cosas pueden ser etiquetadas: figures, equations, sections, etc. -Summations and Integrals are written with sum and int commands: +Los sumatorios e integrales son escritor son los comandos sum e int: -% Some LaTeX compilers will complain if there are blank lines -% In an equation environment. +% Algunos compiladores de LaTeX se quejarán si hay líneas en blanco +% En un contexto de ecuación. \begin{equation} \sum_{i=0}^{5} f_{i} \end{equation} @@ -157,79 +142,67 @@ Summations and Integrals are written with sum and int commands: \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x \end{equation} -\section{Figures} +\section{Figuras} -Let's insert a Figure. Figure placement can get a little tricky. -I definitely have to lookup the placement options each time. +Vamos a insertar una figura. Situarla puede ser algo complicado. -\begin{figure}[H] % H here denoted the placement option. - \centering % centers the figure on the page - % Inserts a figure scaled to 0.8 the width of the page. +\begin{figure}[H] % H aquí establece la situación de la figura. + \centering % centra la figura en la página + % Inserta una figura escalada por 0.8 el ancho de la página. %\includegraphics[width=0.8\linewidth]{right-triangle.png} - % Commented out for compilation purposes. Please use your imagination. - \caption{Right triangle with sides $a$, $b$, $c$} + % La línea anterior ha sido comentada para poder compilar este archivo. Por favor, usa tu imaginación. + \caption{Triángulo con lados $a$, $b$, $c$} \label{fig:right-triangle} \end{figure} -\subsection{Table} -We can also insert Tables in the same way as figures. +\subsection{Tablas} +También podemos insertar tablas de la misma manera que las figuras. \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. + \caption{Título para la tabla.} + % los argumentos en {} describen cómo cada fila va a ser representada. \begin{tabular}{c|cc} - Number & Last Name & First Name \\ % Column rows are separated by $ - \hline % a horizontal line + Número & Nombre & Apellido \\ + \hline % una línea horizontal 1 & Biggus & Dickus \\ 2 & Monty & Python \end{tabular} \end{table} -% \section{Hyperlinks} % Coming soon +% \section{Hyperlinks} % En construcción -\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 we a verbatim -environment. +\section{Haciendo que LaTeX no compile algo (por ejemplo, código fuente)} +Digamos que queremos incluir código fuente dentro de nuestro documento LaTex. En ese caso, debemos indicarle a LaTeX que no trate de compilarlo y simplemente lo muestre en el documento. Esto lo realizamos en el contexto verbatim. -% There are other packages that exist (i.e. minty, lstlisting, etc.) -% but verbatim is the bare-bones basic one. +% Hay otros paquetes para esta misma tarea, pero verbatim es el más básico. \begin{verbatim} - print("Hello World!") - a%b; % look! We can use % signs in verbatim. - random = 4; #decided by fair random dice roll + print("Hola Mundo!") + a%b; % Podemos usar los signos % en verbatim. + aleatorio = 4; # Número aleatorio \end{verbatim} -\section{Compiling} +\section{Compilación} -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 compiles). \\ -Getting to the final document using LaTeX consists of the following steps: +Ahora mismo te estarás preguntando cómo compilar este fabuloso documento y obtener un documento PDF.\\ +Para obtener el documento final utilizando LaTeX hay que seguir los siguientes pasos: \begin{enumerate} - \item Write the document in plain text (the "source code"). - \item Compile source code to produce a pdf. - The compilation step looks something like this (in Linux): \\ + \item Escribe el documento en texto plano. + \item Compila el código para producir un PDF. + Los pasos de compilación serán algo parecido a esto (en Linux): \\ \begin{verbatim} $pdflatex learn-latex.tex learn-latex.pdf \end{verbatim} \end{enumerate} -A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of -software. So, you get to see Step 1, but not Step 2 completely. -Step 2 is still happening behind the scenes. +Un gran número de editores LaTeX combinan ambos pasos para que sea más sencillo obtener el documento. -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 -format you defined in Step 1. +Escribe toda la información de formato en el paso 1 y con el paso 2 obtendrás el documento que has definido en el paso anterior. \section{End} -That's all for now! +Esto es todo por ahora. -% end the document +% fin del documento \end{document} ``` -- cgit v1.2.3 From db690c17c5335b746e3e7867e3d7cf5aab724a9a Mon Sep 17 00:00:00 2001 From: Rudy Affandi Date: Sat, 31 Oct 2015 10:54:55 -0700 Subject: Add PHP magic constants entry --- php.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 0504ced2..06a289f4 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -765,6 +765,13 @@ I'm a ParentClass But I'm ChildClass */ +/********************** +* Magic constants +* +*/ + +// Get directory of the file +require __DIR__ . '/vendor/autoload.php'; /********************** * Error Handling -- cgit v1.2.3 From 2cebd90205c7caedc001202b7a517971f8f1ec20 Mon Sep 17 00:00:00 2001 From: bureken Date: Sat, 31 Oct 2015 21:19:11 +0300 Subject: Comment lines fixed --- tr-tr/swift-tr.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown index c13f5ecf..15056bb8 100644 --- a/tr-tr/swift-tr.html.markdown +++ b/tr-tr/swift-tr.html.markdown @@ -25,14 +25,14 @@ import UIKit //XCode işaretlemelerle kodunuzu bölümlere ayırmanızı ve sağ üstteki metot - listesinde gruplama yapmanıza olanak sağlıyor +//listesinde gruplama yapmanıza olanak sağlıyor // MARK: Bölüm işareti // TODO: Daha sonra yapılacak // FIXME: Bu kodu düzelt -//Swift 2 de, println ve print metotları print komutunda birleştirildi. Print - otomatik olarak yeni satır ekliyor. +//Swift 2 de, println ve print metotları print komutunda birleştirildi. +//Print otomatik olarak yeni satır ekliyor. print("Merhaba dünya") // println print olarak kullanılıyor. print("Merhaba dünya", appendNewLine: false) // yeni bir satır eklemeden yazar. @@ -75,7 +75,7 @@ print("Build degiskeni: \(buildDegiskeni)") // Build degeri: 7 */ var baziOptionalString: String? = "optional" // nil olabilir. // yukarıdakiyle aynı ama ? bir postfix (sona eklenir) operatördür. (kolay -okunabilir) +//okunabilir) var someOptionalString2: Optional = "optional" @@ -104,7 +104,8 @@ if let baziOpsiyonelSabitString = baziOptionalString { // Swift değişkenlerde herhangi bir tip saklanabilir. // AnyObject == id // Objective-C deki `id` den farklı olarak, AnyObject tüm değişkenlerle - çalışabilir (Class, Int, struct, etc) +//çalışabilir +(Class, Int, struct, etc) var herhangiBirObject: AnyObject = 7 herhangiBirObject = "Değer string olarak değişti, iyi bir yöntem değil ama mümkün" @@ -234,7 +235,7 @@ func fiyatlariGetir() -> (Double, Double, Double) { let fiyatTuple = fiyatlariGetir() let fiyat = fiyatTuple.2 // 3.79 // _ (alt çizgi) kullanımı Tuple degerlerini veya diğer değerleri görmezden -gelir +//gelir let (_, fiyat1, _) = fiyatTuple // fiyat1 == 3.69 print(fiyat1 == fiyatTuple.1) // true print("Benzin fiyatı: \(fiyat)") -- cgit v1.2.3 From dc1c759c2903f15fd3c52c2241c765c65fbe9d89 Mon Sep 17 00:00:00 2001 From: Rudy Affandi Date: Sat, 31 Oct 2015 11:27:13 -0700 Subject: Add the rest of the magic constants --- php.html.markdown | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 06a289f4..5034cfd1 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -770,8 +770,32 @@ But I'm ChildClass * */ -// Get directory of the file -require __DIR__ . '/vendor/autoload.php'; +// Get current class name. Must be used inside a class declaration. +echo "Current class name is " . __CLASS__; + +// Get full path directory of a file +echo "Current directory is " . __DIR__; + + // Typical usage + require __DIR__ . '/vendor/autoload.php'; + +// Get full path of a file +echo "Current file path is " . __FILE__; + +// Get current function name +echo "Current function name is " . __FUNCTION__; + +// Get current line number +echo "Current line number is " . __LINE__; + +// Get the name of the current method. Only returns a value when used inside a trait or object declaration. +echo "Current method is " . __METHOD__; + +// Get the name of the current namespace +echo "Current namespace is " . __NAMESPACE__; + +// Get the name of the current trait. Only returns a value when used inside a trait or object declaration. +echo "Current namespace is " . __TRAIT__; /********************** * Error Handling -- cgit v1.2.3 From 96f0b3b3903c6f619b4a964a98e1cb0a463c47e6 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 00:03:58 +0800 Subject: Transated Python 2 to zh-tw. Line 01 .. 143 --- zh-tw/python-tw.html.markdown | 731 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 731 insertions(+) create mode 100644 zh-tw/python-tw.html.markdown diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown new file mode 100644 index 00000000..8381f325 --- /dev/null +++ b/zh-tw/python-tw.html.markdown @@ -0,0 +1,731 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] +translators: + - ["Michael Yeh", "https://github.com/hinet60613"] +filename: learnpython.py +--- + +Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。 + +非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。 + +註: 本篇文章適用的版本為Python 2.7,但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護,因此建議您可以從Python 3開始學Python。 +Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/). + +讓程式碼同時支援Python 2.7和3.X是可以做到的,只要引入 + [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組. + `__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼,詳細訊息請參考Python 3 教學。 + +```python + +# 單行註解從井字號開始 + +""" 多行字串可以用三個雙引號 + 包住,不過通常這種寫法會 + 被拿來當作多行註解 +""" + +#################################################### +## 1. 原始型別與運算元 +#################################################### + +# 你可以使用數字 +3 # => 3 + +# 還有四則運算 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# 除法比較麻煩,除以整數時會自動捨去小數位。 +5 / 2 # => 2 + +# 要做精確的除法,我們需要浮點數 +2.0 # 浮點數 +11.0 / 4.0 # => 2.75 精確多了! + +# 整數除法的無條件捨去對正數或負數都適用 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # 浮點數的整數也適用 +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# 我們可以用除法模組(參考第六節:模組),讓 +# 單一斜線代表普通除法,而非無條件捨去 +from __future__ import division +11/4 # => 2.75 ...普通除法 +11//4 # => 2 ...無條件捨去 + +# 取餘數 +7 % 3 # => 1 + +# 指數 (x的y次方) +2**4 # => 16 + +# 括號即先乘除後加減 +(1 + 3) * 2 # => 8 + +# 布林運算 +# 注意 "and" 和 "or" 的大小寫 +True and False #=> False +False or True #=> True + +# 用整數與布林值做運算 +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# 用not取反向 +not True # => False +not False # => True + +# 等於判斷是用 == +1 == 1 # => True +2 == 1 # => False + +# 不等於判斷是用 != +1 != 1 # => False +2 != 1 # => True + +# 更多比較 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 比較是可以串接的 +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 字串用單引號 ' 或雙引號 " 建立 +"This is a string." +'This is also a string.' + +# 字串相加會被串接再一起 +"Hello " + "world!" # => "Hello world!" +# 不用加號也可以做字串相加 +"Hello " "world!" # => "Hello world!" + +# ... 也可以做相乘 +"Hello" * 3 # => "HelloHelloHello" + +# 字串可以被視為字元的陣列 +"This is a string"[0] # => 'T' + +# 字串的格式化可以用百分之符號 % +# 儘管在Python 3.1後這個功能被廢棄了,並且在 +# 之後的版本會被移除,但還是可以了解一下 +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x,y) + +# 新的格式化方式是使用format函式 +# 這個方式也是較為推薦的 +"{} is a {}".format("This", "placeholder") +"{0} can be {1}".format("strings", "formatted") +# 你也可以用關鍵字,如果你不想數你是要用第幾個變數的話 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# 無(None) 是一個物件 +None # => None + +# 不要用等於符號 "==" 對 無(None)做比較 +# 用 "is" +"etc" is None # => False +None is None # => True + +# The 'is' operator tests for object identity. This isn't +# very useful when dealing with primitive values, but is +# very useful when dealing with objects. + +# Any object can be used in a Boolean context. +# The following values are considered falsey: +# - None +# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) +# - empty sequences (e.g., '', (), []) +# - empty containers (e.g., {}, set()) +# - instances of user-defined classes meeting certain conditions +# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# All other values are truthy (using the bool() function on them returns True). +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Variables and Collections +#################################################### + +# Python has a print statement +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# Simple way to get input data from console +input_string_var = raw_input("Enter some data: ") # Returns the data as a string +input_var = input("Enter some data: ") # Evaluates the data as python code +# Warning: Caution is recommended for input() method usage +# Note: In python 3, input() is deprecated and raw_input() is renamed to input() + +# No need to declare variables before assigning to them. +some_var = 5 # Convention is to use lower_case_with_underscores +some_var # => 5 + +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_other_var # Raises a name error + +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Lists store sequences +li = [] +# You can start with a prefilled list +other_li = [4, 5, 6] + +# Add stuff to the end of a list with append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# Remove from the end with pop +li.pop() # => 3 and li is now [1, 2, 4] +# Let's put it back +li.append(3) # li is now [1, 2, 4, 3] again. + +# Access a list like you would any array +li[0] # => 1 +# Assign new values to indexes that have already been initialized with = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Note: setting it back to the original value +# Look at the last element +li[-1] # => 3 + +# Looking out of bounds is an IndexError +li[4] # Raises an IndexError + +# You can look at ranges with slice syntax. +# (It's a closed/open range for you mathy types.) +li[1:3] # => [2, 4] +# Omit the beginning +li[2:] # => [4, 3] +# Omit the end +li[:3] # => [1, 2, 4] +# Select every second entry +li[::2] # =>[1, 4] +# Reverse a copy of the list +li[::-1] # => [3, 4, 2, 1] +# Use any combination of these to make advanced slices +# li[start:end:step] + +# Remove arbitrary elements from a list with "del" +del li[2] # li is now [1, 2, 3] + +# You can add lists +li + other_li # => [1, 2, 3, 4, 5, 6] +# Note: values for li and for other_li are not modified. + +# Concatenate lists with "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3, 4, 5, 6] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again + +# Get the index of the first item found +li.index(2) # => 1 +li.index(7) # Raises a ValueError as 7 is not in the list + +# Check for existence in a list with "in" +1 in li # => True + +# Examine the length with "len()" +len(li) # => 6 + + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Raises a TypeError + +# You can do all those list thingies on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# You can unpack tuples (or lists) into variables +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +d, e, f = 4, 5, 6 # you can leave out the parentheses +# Tuples are created by default if you leave out the parentheses +g = 4, 5, 6 # => (4, 5, 6) +# Now look how easy it is to swap two values +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys as a list with "keys()" +filled_dict.keys() # => ["three", "two", "one"] +# Note - Dictionary key ordering is not guaranteed. +# Your results might not match this exactly. + +# Get all values as a list with "values()" +filled_dict.values() # => [3, 2, 1] +# Note - Same as above regarding key ordering. + +# Check for existence of keys in a dictionary with "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError + +# Use "get()" method to avoid the KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# The get method supports a default argument when the value is missing +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# note that filled_dict.get("four") is still => None +# (get doesn't set the value in the dictionary) + +# set the value of a key with a syntax similar to lists +filled_dict["four"] = 4 # now, filled_dict["four"] => 4 + +# "setdefault()" inserts into a dictionary only if the given key isn't present +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + + +# Sets store ... well sets (which are like lists but can contain no duplicates) +empty_set = set() +# Initialize a "set()" with a bunch of values +some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) + +# order is not guaranteed, even though it may sometimes look sorted +another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4]) + +# Since Python 2.7, {} can be used to declare a set +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Add more items to a set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Do set union with | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True + +# Check for existence in a set with in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Control Flow +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. Indentation is significant in python! +# prints "some_var is smaller than 10" +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # This elif clause is optional. + print "some_var is smaller than 10." +else: # This is optional too. + print "some_var is indeed 10." + + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use {0} to interpolate formatted strings. (See above.) + print "{0} is a mammal".format(animal) + +""" +"range(number)" returns a list of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" returns a list of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block + +# Works on Python 2.6 and up: +try: + # Use "raise" to raise an error + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. +except (TypeError, NameError): + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks + print "All good!" # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print "We can clean up resources here" + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print line + +#################################################### +## 4. Functions +#################################################### + +# Use "def" to create new functions +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # Return values with a return statement + +# Calling functions with parameters +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# Another way to call functions is with keyword arguments +add(y=6, x=5) # Keyword arguments can arrive in any order. + + +# You can define functions that take a variable number of +# positional args, which will be interpreted as a tuple if you do not use the * +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# You can define functions that take a variable number of +# keyword args, as well, which will be interpreted as a dict if you do not use ** +def keyword_args(**kwargs): + return kwargs + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# When calling functions, you can do the opposite of args/kwargs! +# Use * to expand positional args and use ** to expand keyword args. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) + +# you can pass args and kwargs along to other functions that take args/kwargs +# by expanding them with * and ** respectively +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Function Scope +x = 5 + +def set_x(num): + # Local var x not the same as global variable x + x = num # => 43 + print x # => 43 + +def set_global_x(num): + global x + print x # => 5 + x = num # global var x is now set to 6 + print x # => 6 + +set_x(43) +set_global_x(6) + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# There are built-in higher order functions +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nice maps and filters +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + + +#################################################### +## 5. Classes +#################################################### + +# We subclass from object to get a class. +class Human(object): + + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by python but that live in user-controlled + # namespaces. You should not invent such names on your own. + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # Initialize property + self.age = 0 + + + # An instance method. All methods take "self" as the first argument + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + # A property is just like a getter. + # It turns the method age() into an read-only attribute + # of the same name. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + + +# Instantiate a class +i = Human(name="Ian") +print i.say("hi") # prints out "Ian: hi" + +j = Human("Joel") +print j.say("hello") # prints out "Joel: hello" + +# Call our class method +i.get_species() # => "H. sapiens" + +# Change the shared attribute +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Call the static method +Human.grunt() # => "*grunt*" + +# Update the property +i.age = 42 + +# Get the property +i.age # => 42 + +# Delete the property +del i.age +i.age # => raises an AttributeError + + +#################################################### +## 6. Modules +#################################################### + +# You can import modules +import math +print math.sqrt(16) # => 4 + +# You can get specific functions from a module +from math import ceil, floor +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# you can also test that the functions are equivalent +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + + +#################################################### +## 7. Advanced +#################################################### + +# Generators help you make lazy code +def double_numbers(iterable): + for i in iterable: + yield i + i + +# A generator creates values on the fly. +# Instead of generating and returning all values at once it creates one in each +# iteration. This means values bigger than 15 wont be processed in +# double_numbers. +# Note xrange is a generator that does the same thing range does. +# Creating a list 1-900000000 would take lot of time and space to be made. +# xrange creates an xrange generator object instead of creating the entire list +# like range does. +# We use a trailing underscore in variable names when we want to use a name that +# would normally collide with a python keyword +xrange_ = xrange(1, 900000000) + +# will double all numbers until a result >=30 found +for i in double_numbers(xrange_): + print i + if i >= 30: + break + + +# Decorators +# in this example beg wraps say +# Beg will call say. If say_please is True then it will change the returned +# message +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 09cd1ab461ad8b560824f687cc818d7708aea427 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 00:40:41 +0800 Subject: Add lang of translation. Translate to Line 255 --- zh-tw/python-tw.html.markdown | 129 +++++++++++++++++++++--------------------- 1 file changed, 65 insertions(+), 64 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 8381f325..8e9ca79a 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -8,6 +8,7 @@ contributors: translators: - ["Michael Yeh", "https://github.com/hinet60613"] filename: learnpython.py +lang: zh-tw --- Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。 @@ -142,115 +143,115 @@ None # => None "etc" is None # => False None is None # => True -# The 'is' operator tests for object identity. This isn't -# very useful when dealing with primitive values, but is -# very useful when dealing with objects. - -# Any object can be used in a Boolean context. -# The following values are considered falsey: -# - None -# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) -# - empty sequences (e.g., '', (), []) -# - empty containers (e.g., {}, set()) -# - instances of user-defined classes meeting certain conditions -# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# 'is' 運算元是用來識別物件的。對原始型別來說或許沒什麼用, +# 但對物件來說是很有用的。 + +# 任何物件都可以被當作布林值使用 +# 以下的值會被視為是False : +# - 無(None) +# - 任何型別的零 (例如: 0, 0L, 0.0, 0j) +# - 空序列 (例如: '', (), []) +# - 空容器 (例如: {}, set()) +# - 自定義型別的實體,且滿足某些條件 +# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ # -# All other values are truthy (using the bool() function on them returns True). +# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值). bool(0) # => False bool("") # => False #################################################### -## 2. Variables and Collections +## 2. 變數與集合 #################################################### -# Python has a print statement +# Python的輸出很方便 print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! -# Simple way to get input data from console -input_string_var = raw_input("Enter some data: ") # Returns the data as a string -input_var = input("Enter some data: ") # Evaluates the data as python code -# Warning: Caution is recommended for input() method usage -# Note: In python 3, input() is deprecated and raw_input() is renamed to input() +# 從命令列獲得值也很方便 +input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數 +input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行 +# 注意: 請謹慎使用input()函式 +# 註: 在Python 3中,input()已被棄用,raw_input()已被更名為input() -# No need to declare variables before assigning to them. -some_var = 5 # Convention is to use lower_case_with_underscores +# 使用變數前不需要先宣告 +some_var = 5 # 方便好用 +lower_case_with_underscores some_var # => 5 -# Accessing a previously unassigned variable is an exception. -# See Control Flow to learn more about exception handling. -some_other_var # Raises a name error +# 存取沒有被賦值的變數會造成例外 +# 請參考錯誤流程部分做例外處理 +some_other_var # 造成 NameError -# if can be used as an expression -# Equivalent of C's '?:' ternary operator +# if可以當判斷式使用 +# 相當於C語言中的二元判斷式 "yahoo!" if 3 > 2 else 2 # => "yahoo!" -# Lists store sequences +# 串列型態可以儲存集合 li = [] -# You can start with a prefilled list +# 你可以預先填好串列內容 other_li = [4, 5, 6] -# Add stuff to the end of a list with append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# Remove from the end with pop +# 用append()在串列後新增東西 append +li.append(1) # 此時 li 內容為 [1] +li.append(2) # 此時 li 內容為 [1, 2] +li.append(4) # 此時 li 內容為 [1, 2, 4] +li.append(3) # 此時 li 內容為 [1, 2, 4, 3] +# 用pop()移除串列尾端的元素 li.pop() # => 3 and li is now [1, 2, 4] -# Let's put it back +# 然後再塞回去 li.append(3) # li is now [1, 2, 4, 3] again. -# Access a list like you would any array +# 你可以像存取陣列一樣的存取串列 li[0] # => 1 -# Assign new values to indexes that have already been initialized with = +# 用等號 = 給串列中特定索引的元素賦值 li[0] = 42 li[0] # => 42 -li[0] = 1 # Note: setting it back to the original value -# Look at the last element +li[0] = 1 # 註: 將其設定回原本的值 +# 用 -1 索引值查看串列最後一個元素 li[-1] # => 3 -# Looking out of bounds is an IndexError +# 存取超過範圍會產生IndexError li[4] # Raises an IndexError -# You can look at ranges with slice syntax. -# (It's a closed/open range for you mathy types.) +# 你可以用切片語法來存取特定範圍的值 +# (相當於數學中的左閉右開區間,即包含最左邊界,但不包含右邊界) li[1:3] # => [2, 4] -# Omit the beginning +# 略過開頭元素 li[2:] # => [4, 3] -# Omit the end +# 略過結尾元素 li[:3] # => [1, 2, 4] -# Select every second entry +# 每隔兩個元素取值 li[::2] # =>[1, 4] -# Reverse a copy of the list +# 串列反轉 li[::-1] # => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] +# 你可以任意組合來達到你想要的效果 +# li[開始索引:結束索引:間隔] -# Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] +# 用 "del" 從串列中移除任意元素 +del li[2] # 現在 li 內容為 [1, 2, 3] -# You can add lists +# 你可以做串列相加 li + other_li # => [1, 2, 3, 4, 5, 6] -# Note: values for li and for other_li are not modified. +# 註: li 及 other_li 沒有被更動 -# Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +# 用 "extend()" 做串列串接 +li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6] -# Remove first occurrence of a value -li.remove(2) # li is now [1, 3, 4, 5, 6] -li.remove(2) # Raises a ValueError as 2 is not in the list +# 移除特定值的第一次出現 +li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6] +li.remove(2) # 2 不在串列中,造成 ValueError -# Insert an element at a specific index -li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again +# 在特定位置插入值 +li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6] -# Get the index of the first item found +# 取得特定值在串列中第一次出現的位置 li.index(2) # => 1 -li.index(7) # Raises a ValueError as 7 is not in the list +li.index(7) # 7 不在串列中,造成 ValueError -# Check for existence in a list with "in" +# 用 "in" 檢查特定值是否出現在串列中 1 in li # => True -# Examine the length with "len()" +# 用 "len()" 取得串列長度 len(li) # => 6 -- cgit v1.2.3 From 6c9bf0dc5bccf644439346763f36b047a898a694 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 02:06:40 +0800 Subject: Translate to Sec. 4 finished. --- zh-tw/python-tw.html.markdown | 197 +++++++++++++++++++++--------------------- 1 file changed, 100 insertions(+), 97 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 8e9ca79a..073c5e91 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Andre Polykanine", "https://github.com/Oire"] - ["evuez", "http://github.com/evuez"] translators: - - ["Michael Yeh", "https://github.com/hinet60613"] + - ["Michael Yeh", "https://hinet60613.github.io/"] filename: learnpython.py lang: zh-tw --- @@ -255,137 +255,139 @@ li.index(7) # 7 不在串列中,造成 ValueError len(li) # => 6 -# Tuples are like lists but are immutable. +# 元組(Tuple,以下仍用原文)類似於串列,但是它是不可改變的 tup = (1, 2, 3) tup[0] # => 1 -tup[0] = 3 # Raises a TypeError +tup[0] = 3 # 產生TypeError -# You can do all those list thingies on tuples too +# 能對串列做的東西都可以對tuple做 len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True -# You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -d, e, f = 4, 5, 6 # you can leave out the parentheses -# Tuples are created by default if you leave out the parentheses +# 你可以把tuple拆開並分別將值存入不同變數 +a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3 +d, e, f = 4, 5, 6 # 也可以不寫括號 +# 如果不加括號,預設會產生tuple g = 4, 5, 6 # => (4, 5, 6) -# Now look how easy it is to swap two values +# 你看,交換兩個值很簡單吧 e, d = d, e # d is now 5 and e is now 4 -# Dictionaries store mappings +# 字典(Dictionary)用來儲存映射關係 empty_dict = {} -# Here is a prefilled dictionary +# 你可以對字典做初始化 filled_dict = {"one": 1, "two": 2, "three": 3} -# Look up values with [] +# 用 [] 取值 filled_dict["one"] # => 1 -# Get all keys as a list with "keys()" +# 用 "keys()" 將所有的Key輸出到一個List中 filled_dict.keys() # => ["three", "two", "one"] -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. +# 註: 字典裡key的排序是不固定的 +# 你的執行結果可能與上面不同 +# 譯註: 只能保證所有的key都有出現,但不保證順序 -# Get all values as a list with "values()" +# 用 "valuess()" 將所有的Value輸出到一個List中 filled_dict.values() # => [3, 2, 1] -# Note - Same as above regarding key ordering. +# 註: 同上,不保證順序 -# Check for existence of keys in a dictionary with "in" +# 用 "in" 來檢查指定的Key是否在字典中 "one" in filled_dict # => True 1 in filled_dict # => False -# Looking up a non-existing key is a KeyError +# 查詢不存在的Key會造成KeyError filled_dict["four"] # KeyError -# Use "get()" method to avoid the KeyError +# 用 "get()" 來避免KeyError +# 若指定的Key不存在的話會得到None filled_dict.get("one") # => 1 filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing +# "get()" 函式支援預設值,當找不到指定的值時,會回傳指定的預設值 filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4 -# note that filled_dict.get("four") is still => None -# (get doesn't set the value in the dictionary) +# 注意此時 filled_dict.get("four") 仍然為 None +# (get()此時並沒有產生出任何的值) -# set the value of a key with a syntax similar to lists -filled_dict["four"] = 4 # now, filled_dict["four"] => 4 +# 像操作list一樣,對指定的Key賦值 +filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4 -# "setdefault()" inserts into a dictionary only if the given key isn't present -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 +# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary +filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5 -# Sets store ... well sets (which are like lists but can contain no duplicates) +# 集合(Set)被用來儲存...集合。 +# 跟串列(List)有點像,但集合內不會有重複的元素 empty_set = set() -# Initialize a "set()" with a bunch of values -some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) +# 初始化 "set()" 並給定一些值 +some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入 -# order is not guaranteed, even though it may sometimes look sorted -another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4]) +# 一樣,不保證順序,就算真的有照順序排也只是你運氣好 +another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4]) -# Since Python 2.7, {} can be used to declare a set +# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} -# Add more items to a set +# 加入更多元素進入Set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} -# Do set intersection with & +# 用 & 來對兩個集合取交集 other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} -# Do set union with | +# 用 | 來對兩個集合取聯集 filled_set | other_set # => {1, 2, 3, 4, 5, 6} -# Do set difference with - +# 用 - 來將第二個集合內有的元素移出第一個集合 {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} -# Do set symmetric difference with ^ +# 用 ^ 來對兩個集合取差集 {1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} -# Check if set on the left is a superset of set on the right +# 檢查左邊是否為右邊的母集 {1, 2} >= {1, 2, 3} # => False -# Check if set on the left is a subset of set on the right +# 檢查左邊是否為右邊的子集 {1, 2} <= {1, 2, 3} # => True -# Check for existence in a set with in +# 用 in 來檢查某元素是否存在於集合內 2 in filled_set # => True 10 in filled_set # => False #################################################### -## 3. Control Flow +## 3. 控制流程 #################################################### -# Let's just make a variable +# 首先,先宣告一個變數 some_var = 5 -# Here is an if statement. Indentation is significant in python! -# prints "some_var is smaller than 10" +# 這邊是 if 判斷式。注意,縮排對Python是很重要的。 +# 下面應該會印出 "some_var is smaller than 10" if some_var > 10: print "some_var is totally bigger than 10." -elif some_var < 10: # This elif clause is optional. +elif some_var < 10: # elif 可有可無 print "some_var is smaller than 10." -else: # This is optional too. +else: # else 也可有可無 print "some_var is indeed 10." """ -For loops iterate over lists -prints: +For 迴圈會遞迴整的List +下面的程式碼會輸出: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: - # You can use {0} to interpolate formatted strings. (See above.) + # 你可以用{0}來組合0出格式化字串 (見上面.) print "{0} is a mammal".format(animal) """ -"range(number)" returns a list of numbers -from zero to the given number -prints: +"range(number)" 回傳一個包含從0到給定值的數字List, +下面的程式碼會輸出: 0 1 2 @@ -395,9 +397,9 @@ for i in range(4): print i """ -"range(lower, upper)" returns a list of numbers -from the lower number to the upper number -prints: +"range(lower, upper)" 回傳一個包含從給定的下限 +到給定的上限的數字List +下面的程式碼會輸出: 4 5 6 @@ -407,8 +409,8 @@ for i in range(4, 8): print i """ -While loops go until a condition is no longer met. -prints: +While迴圈會執行到條件不成立為止 +下面的程式碼會輸出: 0 1 2 @@ -417,62 +419,62 @@ prints: x = 0 while x < 4: print x - x += 1 # Shorthand for x = x + 1 + x += 1 # x = x + 1 的簡寫 -# Handle exceptions with a try/except block +# 用try/except處理例外 -# Works on Python 2.6 and up: +# 適用Python 2.6及以上版本 try: - # Use "raise" to raise an error + # 用 "raise" 來發起例外 raise IndexError("This is an index error") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # 毫無反應,就只是個什麼都沒做的pass。通常這邊會讓你做對例外的處理 except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks - print "All good!" # Runs only if the code in try raises no exceptions -finally: # Execute under all circumstances + pass # 有需要的話,多種例外可以一起處理 +else: # else 可有可無,但必須寫在所有的except後 + print "All good!" # 只有在try的時候沒有產生任何except才會被執行 +finally: # 不管什麼情況下一定會被執行 print "We can clean up resources here" -# Instead of try/finally to cleanup resources you can use a with statement +# 除了try/finally以外,你可以用 with 來簡單的處理清理動作 with open("myfile.txt") as f: for line in f: print line #################################################### -## 4. Functions +## 4. 函式 #################################################### -# Use "def" to create new functions +# 用 "def" 來建立新函式 def add(x, y): print "x is {0} and y is {1}".format(x, y) - return x + y # Return values with a return statement + return x + y # 用 "return" 來回傳值 -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +# 用參數來呼叫韓式 +add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. +# 你也可以寫上參數名稱來呼叫函式 +add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行 -# You can define functions that take a variable number of -# positional args, which will be interpreted as a tuple if you do not use the * +# 你可以定義接受多個變數的函式,這些變數是按照順序排序的 +# 如果不加*的話會被解讀為tuple def varargs(*args): return args varargs(1, 2, 3) # => (1, 2, 3) -# You can define functions that take a variable number of -# keyword args, as well, which will be interpreted as a dict if you do not use ** +# 你可以定義接受多個變數的函式,這些變數是按照keyword排序的 +# 如果不加**的話會被解讀為dictionary def keyword_args(**kwargs): return kwargs -# Let's call it to see what happens +# 呼叫看看會發生什麼事吧 keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} -# You can do both at once, if you like +# 如果你想要,你也可以兩個同時用 def all_the_args(*args, **kwargs): print args print kwargs @@ -482,39 +484,40 @@ all_the_args(1, 2, a=3, b=4) prints: {"a": 3, "b": 4} """ -# When calling functions, you can do the opposite of args/kwargs! -# Use * to expand positional args and use ** to expand keyword args. +# 呼叫函式時,你可以做反向的操作 +# 用 * 將變數展開為順序排序的變數 +# 用 ** 將變數展開為Keyword排序的變數 args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # 等同於 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 等同於 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 等同於 foo(1, 2, 3, 4, a=3, b=4) -# you can pass args and kwargs along to other functions that take args/kwargs -# by expanding them with * and ** respectively +# 你可以把args跟kwargs傳到下一個函式內 +# 分別用 * 跟 ** 將它展開就可以了 def pass_all_the_args(*args, **kwargs): all_the_args(*args, **kwargs) print varargs(*args) print keyword_args(**kwargs) -# Function Scope +# 函式範圍 x = 5 def set_x(num): - # Local var x not the same as global variable x + # 區域變數 x 和全域變數 x 不是同一個東西 x = num # => 43 print x # => 43 def set_global_x(num): global x print x # => 5 - x = num # global var x is now set to 6 + x = num # 全域變數 x 在set_global_x(6)被設定為 6 print x # => 6 set_x(43) set_global_x(6) -# Python has first class functions +# Python有一級函式 def create_adder(x): def adder(y): return x + y @@ -523,23 +526,23 @@ def create_adder(x): add_10 = create_adder(10) add_10(3) # => 13 -# There are also anonymous functions +# 也有匿名函式 (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 -# There are built-in higher order functions +# 還有內建的高階函式 map(add_10, [1, 2, 3]) # => [11, 12, 13] map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -# We can use list comprehensions for nice maps and filters +# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用 [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### -## 5. Classes +## 5. 類別 #################################################### # We subclass from object to get a class. -- cgit v1.2.3 From e2b93f579cbcbb58612081b46f4460cd0255edb3 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 02:18:21 +0800 Subject: Finish translation of Sec. 6 --- zh-tw/python-tw.html.markdown | 44 +++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 073c5e91..d113f90c 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -545,25 +545,25 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] ## 5. 類別 #################################################### -# We subclass from object to get a class. +# 我們可以由object繼承出一個新的類別 class Human(object): - # A class attribute. It is shared by all instances of this class + # 類別的參數,被所有這個類別的實體所共用 species = "H. sapiens" - # Basic initializer, this is called when this class is instantiated. - # Note that the double leading and trailing underscores denote objects - # or attributes that are used by python but that live in user-controlled - # namespaces. You should not invent such names on your own. + # 基礎建構函式,當class被實體化的時候會被呼叫 + # 注意前後的雙底線代表物件 + # 還有被python用,但實際上是在使用者控制的命名 + # 空間內的參數。你不應該自己宣告這樣的名稱。 def __init__(self, name): - # Assign the argument to the instance's name attribute + # 將函式引入的參數 name 指定給實體的 name 參數 self.name = name - # Initialize property + # 初始化屬性 self.age = 0 - # An instance method. All methods take "self" as the first argument + # 一個實體的方法(method)。 所有的method都以self為第一個參數 def say(self, msg): return "{0}: {1}".format(self.name, msg) @@ -626,41 +626,41 @@ i.age # => raises an AttributeError #################################################### -## 6. Modules +## 6. 模組 #################################################### -# You can import modules +# 你可以引入模組來做使用 import math print math.sqrt(16) # => 4 + # math.sqrt()為取根號 -# You can get specific functions from a module +# 你可以只從模組取出特定幾個函式 from math import ceil, floor print ceil(3.7) # => 4.0 print floor(3.7) # => 3.0 -# You can import all functions from a module. -# Warning: this is not recommended +# 你可以將所有的函式從模組中引入 +# 注意:不建議這麼做 from math import * -# You can shorten module names +# 你可以用 as 簡寫模組名稱 import math as m math.sqrt(16) == m.sqrt(16) # => True -# you can also test that the functions are equivalent +# 你也可以測試函示是否相等 from math import sqrt math.sqrt == m.sqrt == sqrt # => True -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. +# Python的模組就只是一般的Python檔。 +# 你可以自己的模組自己寫、自己的模組自己引入 +# 模組的名稱和檔案名稱一樣 -# You can find out which functions and attributes -# defines a module. +# 你可以用dir()來查看有哪些可用函式和屬性 import math dir(math) #################################################### -## 7. Advanced +## 7. 進階 #################################################### # Generators help you make lazy code -- cgit v1.2.3 From 3544a43d117d7b63de2c3443250270d92d00dce9 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 02:27:42 +0800 Subject: Finish Sec. 7 translation. --- zh-tw/python-tw.html.markdown | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index d113f90c..797fc6ed 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -663,34 +663,30 @@ dir(math) ## 7. 進階 #################################################### -# Generators help you make lazy code +# 產生器(Generator)可以讓你寫更懶惰的程式碼 def double_numbers(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# Note xrange is a generator that does the same thing range does. -# Creating a list 1-900000000 would take lot of time and space to be made. -# xrange creates an xrange generator object instead of creating the entire list -# like range does. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword +# 產生器可以讓你即時的產生值 +# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時 +# 產生值。 這也意味著大於15的值不會在double_numbers中產生。 +# 這邊,xrange()做的事情和range()一樣 +# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間 +# xrange() 建立一個產生器物件,而不是如range()建立整個List +# 我們用底線來避免可能和python的關鍵字重複的名稱 xrange_ = xrange(1, 900000000) -# will double all numbers until a result >=30 found +# 下面的程式碼會把所有的值乘以兩倍,直到出現大於30的值 for i in double_numbers(xrange_): print i if i >= 30: break -# Decorators -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message +# 裝飾子 +# 在這個範例中,beg會綁在say上 +# Beg會呼叫say。 如果say_please為True的話,它會更改回傳的訊息 from functools import wraps @@ -715,9 +711,9 @@ print say() # Can you buy me a beer? print say(say_please=True) # Can you buy me a beer? Please! I am poor :( ``` -## Ready For More? +## 準備好學更多了嗎? -### Free Online +### 線上免費資源 * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) @@ -728,7 +724,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) -### Dead Tree +### 或買本書? * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 2ecf370ce4e8b6644863e92652f9b63717ab3e6e Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 02:32:25 +0800 Subject: Sec. 6 translated. All sections translated. Hooray. --- zh-tw/python-tw.html.markdown | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 797fc6ed..10b4669c 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -567,60 +567,59 @@ class Human(object): def say(self, msg): return "{0}: {1}".format(self.name, msg) - # A class method is shared among all instances - # They are called with the calling class as the first argument + # 一個類別方法會被所有的實體所共用 + # 他們會以類別為第一參數的方式被呼叫 @classmethod def get_species(cls): return cls.species - # A static method is called without a class or instance reference + # 靜態方法 @staticmethod def grunt(): return "*grunt*" - # A property is just like a getter. - # It turns the method age() into an read-only attribute - # of the same name. + # 屬性就像是用getter取值一樣 + # 它將方法 age() 轉為同名的、只能讀取的屬性 @property def age(self): return self._age - # This allows the property to be set + # 這樣寫的話可以讓屬性被寫入新的值 @age.setter def age(self, age): self._age = age - # This allows the property to be deleted + # 這樣寫的話允許屬性被刪除 @age.deleter def age(self): del self._age -# Instantiate a class +# 將類別實體化 i = Human(name="Ian") print i.say("hi") # prints out "Ian: hi" j = Human("Joel") print j.say("hello") # prints out "Joel: hello" -# Call our class method +# 呼叫類別方法 i.get_species() # => "H. sapiens" -# Change the shared attribute +# 更改共用的屬性 Human.species = "H. neanderthalensis" i.get_species() # => "H. neanderthalensis" j.get_species() # => "H. neanderthalensis" -# Call the static method +# 呼叫靜態方法 Human.grunt() # => "*grunt*" -# Update the property +# 更新屬性 i.age = 42 -# Get the property +# 取得屬性 i.age # => 42 -# Delete the property +# 移除屬性 del i.age i.age # => raises an AttributeError -- cgit v1.2.3 From a25d4db0bcfb9325f69f68a2532df6fd88f4e78d Mon Sep 17 00:00:00 2001 From: rainjay Date: Tue, 3 Nov 2015 11:09:19 +0800 Subject: fix typo --- zh-tw/python-tw.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 10b4669c..c4706c43 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -450,7 +450,7 @@ def add(x, y): print "x is {0} and y is {1}".format(x, y) return x + y # 用 "return" 來回傳值 -# 用參數來呼叫韓式 +# 用參數來呼叫函式 add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 # 你也可以寫上參數名稱來呼叫函式 -- cgit v1.2.3 From 92a736f5e06473d454f197b8017dc542ba8c404c Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:02:00 -0500 Subject: Added solidity --- solidity.html.markdown | 381 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 381 insertions(+) create mode 100644 solidity.html.markdown diff --git a/solidity.html.markdown b/solidity.html.markdown new file mode 100644 index 00000000..6409828a --- /dev/null +++ b/solidity.html.markdown @@ -0,0 +1,381 @@ +--- +language: Solidity +filename: learnSolidity.sol +contributors: + - ["Nemil Dalal", "https://www.nemil.com"] +--- + +Solidity is a statically typed, contract programming language for [Ethereum](https://www.ethereum.org/) that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. + +Solidity lets you program on Ethereum, a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. + +As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. + +```javascript +// Let's start with a simple Bank contract, before diving into to the key components of the language + +// Start with a Natspec comment (the three slashes) that can be used +// for documentation - and as descriptive data for UI elements +/// @title A simple deposit/withdrawal bank built on Bitcoin + +// All contracts are declared and named (in CamelCase) +contract AcmeBank { + // Declare state variables outside a function, + // these are persistent throughout the life of the contract + + // a dictionary that maps addresses to balances + mapping (address -> uint) balances; + + // the 'public' makes 'owner' externally readable by users or contracts + // (but not writeable), the 'constant' means this value to be + // changed after initialization + address public constant owner; + + // Constructor, can receive one or many variables here + function AcmeBank() { + // msg is a default variable that provides both the + // contract messager's address and amount + owner = msg.address; + // the owner has no additional rights, we're setting it for + // illustrative purposes + } + + function deposit(uint balance) { + balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable + + return balances[msg.sender]; + } + + function withdraw(uint withdrawAmount) returns (uint remainingBalance) { + if(balances[msg.sender] >= withdrawAmount) { + balances[msg.sender] -= withdrawAmount; + balances[msg.sender].send(withdrawAmount); + + return balances[msg.sender]; + } + } + + // The 'constant' prevents the function from editing state variables + function balance() constant { + return balances[msg.sender]; + } + + // Fallback function + // This function is called if invalid data is sent or ether without data; + // Added so that ether sent to this contract is reverted if the contract fails + // otherwise, the sender loses their money; you should add this in most contracts + function () { throw; } +} +// End example + +// Now let's go through the basics of Solidity + +// 1. DATA TYPES +// uint is the data type typically used for currency (there are no doubles +// or floats) and for dates +uint x; +int const a = 8; // int of 256 bits, cannot be changed after instantiation +uint8 b; +int64 c; +// int256 is same as int +// For both int and uint, you can explicitly set space in steps of 8, +// e.g., int8, int16 +uint248 e; + +// Type casting +int x = int(b) + +bool b = true; // or do 'var b = true;' for inferred typing + +// Addresses - holds 20 byte/160 bit Ethereum addresses to another contract +// ('Contract Account)') or person/external entity ('External Account') +address public owner; // Add 'public' field to indicate publicly/externally accessible, a getter is automatically created, but NOT a setter + +// All addresses can be sent ether in the following way: +owner.send(SOME_BALANCE); // returns false on failure +owner.balance; // the balance of the owner + +// Bytes are provided from 1 to 32 +byte a; // byte is same as bytes1 +bytes32 b; + +// Dynamically sized +bytes m; // A special array, same as byte[] (but packed tightly) +// same as bytes, but does not allow length or index access (for now) +string n = 'hello'; + +// Type inference +// var does inferred typing based on first assignment, +// can't be used in functions parameters +var a = true; +// there are edge cases where inference leads to a value being set (e.g., an uint 8) +// that is different from what the user wanted (uint16), so use carefully + +// by default, all values are set to 0 on instantiation + +// Delete can be called on most types, and will set the values to 0 +uint x = 5; +delete(x); // x is now 0 + +// 2. DATA STRUCTURES +// Arrays +bytes32[] names; +uint newLength = names.push("John"); // adding returns new length of the array +// Length +names.length; // get length +names.length = 1; // lengths can also be set, unlike many other languages + +// Dictionaries (any type to any other type) +mapping (string -> uint) public balances; +balances["john"] = 1; +console.log(balances[jill]); // is 0, all non-set key values return zeroes +// The 'public' lets you do the following from another contract +contractName.balances("john"); // returns 1 +// The 'public' keyword here created a getter (but not setter) that behaves like the following: +function balances(address _account) returns (uint balance) { + return balances[_account]; +} + +// To delete +delete(balances["John"]); +delete(balances); // deletes all elements + +// Unlike languages like Javascript, you cannot iterate through all elements in +// a map, without knowing the source keys + +// Structs and enums + struct Bank { // note the capital + address owner; + uint balance; + } +Bank b = Bank({ + owner: msg.sender, + balance: 5 +}); +delete(b); // set all values to 0, except any mappings + +// Enums +enum State { Created, Locked, Inactive }; +State public state; // Declare variable from enum +state = State.Created; + +// 3. Variables of note +// storage - A persistent storage hash (does not need to be declared) +storage['abc'] = 'def'; // maps 256 bit words to 256 bit words + +// tx - This transaction +tx.origin // address, sender of the transaction +tx.gasprice // uint, gas price of the transaction + +// msg - The current message received by the contract +msg.sender; // address, The address of the sender +msg.value; // uint, The amount of gas provided to this contract in wei +msg.data // bytes, complete call data + +// balance of the current contract (both contract and external accounts +// have balances) - often used at the end of a contracts life to send the +// remaining balance to a party +this.balance +// block +now // uint, current time, alias for block.timestamp +block.number // uint, current block number +block.difficulty // uint, current block difficulty +block.blockhash(1) // returns bytes32, only provides for most recent 256 block + +// 4. FUNCTIONS AND MORE +// A. Functions +// Simple function +function increment(uint x) returns (uint) { + x += 1; + return x; +} + +// Functions can return many arguments, and by specifying the returned arguments +// you don't need to explicity return +function increment(uint x, uint y) returns (uint x, uint y) { + x += 1; + y += 1; +} +// This function would have been called like this, and assigned to a tuple +uint (a,b) = increment(1,1); + +// The 'constant' indicates and ensures that a function does not/cannot change the persistent variables +uint y; + +function increment(uint x) constant returns (uint x) { + x += 1; + y += 1; // this line would fail + // as y is a state variable, and can't be changed in a constant function +} + +// There are a few 'function visibility specifiers' that can be placed where 'constant' +// is, which include: +// internal (can only be called by an internal function, not one external to the contract) +// public - visibile externally and internally +// private - only visible in the current contract + +// Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable +function a() { + var z = b; + b(); +} + +function b() { + +} + +// B. Events +// Events are an easy way to notify external listeners that something changed +// You typically decalre them after your contract parameters +event Sent(address from, address to, uint amount); + +// You then call it in a function, when you want to trigger it +sent(from, to, amount); + +// For an external party (a contract or external entity), to watch +// for an event, you write the following: +Coin.Sent().watch({}, '', function(error, result) { + if (!error) { + console.log("Coin transfer: " + result.args.amount + + " coins were sent from " + result.args.from + + " to " + result.args.to + "."); + console.log("Balances now:\n" + + "Sender: " + Coin.balances.call(result.args.from) + + "Receiver: " + Coin.balances.call(result.args.to)); + } +} +// This is a common paradigm for one contract to depend on another (e.g., a +// contract that depends on the current exchange rate provided by another +// contract) + +// C. Modifiers +// Modifiers let you validate inputs to functions +// The '_' (underscore) must be included, and is an indicator that the +// function being called should be placed there +modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } + +// You can then append it right after the function declaration +function test() + onlyBefore() +{ + +} + +// 5. BRANCHING AND LOOPS + +// All basic logic blocks work - including if/else, for, while, break, continue, return +// switch is not provided +// Syntax is the same as javascript, but there is no type conversion from +// non-boolean to boolean + +// 6. CALLING AN EXTERNAL CONTRACT + +contract infoFeed { + function info() returns (uint ret) { return 42; } +} + +contract Consumer { + InfoFeed feed; // create a variable that will point to a contract on the blockchain + function setFeed(address addr) { + // Link to the contract by creating on the address + feed = InfoFeed(addr); + } + function callFeed() { + // T final parentheses call the contract, optionally adding + // custom value or gas numbers + feed.info.value(10).gas(800)(); + } +} + +// 7. CONTRACT DESIGN PATTERNS + +// A. Obfuscation +// Remember that all variables are publicly viewable on the blockchain, so +// anything that needs some privacy needs to be obfuscated (e.g., hashed) + +// B. Throwing +// Throwing +throw; // throwing is easily done, and reverts unused money to the sender +// You can't currently catch + +// A common design pattern is: +if (!addr.send(123)) { + throw; +} + +// C. Suicide +// Suicide +suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) + +// D. Storage optimization +// Reading and writing can be expensive, as data needs to be stored in the +// blockchain forever - this encourages smart ways to use memory (eventually, +// compilation may better handle this, but for now there are benefits to +// planning your data structures) + +// *** EXAMPLE: Let's do a more complex example *** +// [TODO: Decide what a more complex example looks like, needs a few // characteristics: +// - has a 'constant' state variable +// - has a state machine (uses modifier) +// - sends money to an address +// - gets information from another contract (we'll show code for both contracts) +// - Shows inheritance +// - show variables being passed in on instantiation (and guard code to throw if variables not provided) +// Ideas: +// - crowdfunding? +// - Peer to peer insurance +// ] + +// *** END EXAMPLE *** + +// Some final points +// 7. NATIVE FUNCTIONS + +// Currency units +// By default, currency is defined using wei, the smallest unit of Ether +uint minAmount = 1 wei; +uint a = 1 finney; // 1 ether = 1000 finney +// There are a number of other units, see: http://ether.fund/tool/converter + +// Time units +1 == 1 second +1 minutes == 60 seconds + + +// You typically multiply a variable times the unit, as these units are not +// directly stored in a variable +uint x = 5; +(x * 1 days); // 5 days + +// Be careful about leap seconds and leap years when using equality statements for time (instead, prefer greater than/less than) + +// Cryptography +// All strings passed are concatenated before the hash is run +sha3("ab", "cd"); +ripemd160("abc"); +sha256("def"); + +// These are natspec comments, when a user is asked to confirm a transaction +/// +/** */ + +// 8. COMMON MISTAKES +// A few common mistakes +// You cannot restrict a human or computer from reading the content of +// your transaction or a transaction's state + +// All data to the start of time is stored in the blockchain, so you and +// anyone can observe all previous data states + +// 9. STYLE NOTES +// Use 4 spaces for indentation +// (Python's PEP8 is used as the baseline style guide, including its general philosophy) +``` + +## Additional resources +- [Solidity Docs](https://ethereum.github.io/solidity/docs/home/) +- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. +- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) +- [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) + +Feel free to send a pull request with any edits - or email nemild -/at-/ gmail \ No newline at end of file -- cgit v1.2.3 From d5bcbceb21954d0f8739fb841fc511aa32c2bcc6 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:07:17 -0500 Subject: Fixed withdrawal check --- solidity.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 6409828a..79debed6 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -49,7 +49,10 @@ contract AcmeBank { function withdraw(uint withdrawAmount) returns (uint remainingBalance) { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - balances[msg.sender].send(withdrawAmount); + + if (!balances[msg.sender].send(withdrawAmount)) { + balances[msg.sender] += withdrawAmount; + } return balances[msg.sender]; } -- cgit v1.2.3 From 08f3ee3687fc18286fdb3825f0fc1fd74c086798 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:39:05 -0500 Subject: Added remove function --- solidity.html.markdown | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 79debed6..bcbdec5f 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -35,15 +35,13 @@ contract AcmeBank { function AcmeBank() { // msg is a default variable that provides both the // contract messager's address and amount - owner = msg.address; - // the owner has no additional rights, we're setting it for - // illustrative purposes + owner = msg.address; // msg.address refers to the address of the contract creator } function deposit(uint balance) { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable - return balances[msg.sender]; + return balances[msg.sender]; // msg.sender refers to the contract caller } function withdraw(uint withdrawAmount) returns (uint remainingBalance) { @@ -58,6 +56,13 @@ contract AcmeBank { } } + // It's good practice to have a remove function, which disables this contract + function remove () { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } + } + // The 'constant' prevents the function from editing state variables function balance() constant { return balances[msg.sender]; -- cgit v1.2.3 From 1f4738cbc75f789992270c3926cf9cdd30c4674a Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 24 Nov 2015 00:09:10 -0500 Subject: Several fixes per Andreas's feedback --- solidity.html.markdown | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index bcbdec5f..88ccd817 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -14,28 +14,30 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language +// START EXAMPLE // Start with a Natspec comment (the three slashes) that can be used // for documentation - and as descriptive data for UI elements /// @title A simple deposit/withdrawal bank built on Bitcoin // All contracts are declared and named (in CamelCase) +// They are similar to 'class' in other languages (and allow capabilities like inheritance) contract AcmeBank { // Declare state variables outside a function, // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address -> uint) balances; + mapping (address => uint) balances; // the 'public' makes 'owner' externally readable by users or contracts // (but not writeable), the 'constant' means this value to be // changed after initialization - address public constant owner; + address public owner; // Constructor, can receive one or many variables here function AcmeBank() { // msg is a default variable that provides both the // contract messager's address and amount - owner = msg.address; // msg.address refers to the address of the contract creator + owner = msg.sender; // msg.sender refers to the address of the contract creator } function deposit(uint balance) { @@ -48,7 +50,7 @@ contract AcmeBank { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - if (!balances[msg.sender].send(withdrawAmount)) { + if (!msg.sender.send(withdrawAmount)) { balances[msg.sender] += withdrawAmount; } @@ -56,7 +58,7 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this contract + // It's good practice to have a remove function, which disables this contract - but does mean that users have to trust the owner function remove () { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner @@ -74,7 +76,7 @@ contract AcmeBank { // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } } -// End example +// END EXAMPLE // Now let's go through the basics of Solidity @@ -82,7 +84,7 @@ contract AcmeBank { // uint is the data type typically used for currency (there are no doubles // or floats) and for dates uint x; -int const a = 8; // int of 256 bits, cannot be changed after instantiation +int constant a = 8; // int of 256 bits, cannot be changed after instantiation uint8 b; int64 c; // int256 is same as int @@ -134,7 +136,7 @@ names.length; // get length names.length = 1; // lengths can also be set, unlike many other languages // Dictionaries (any type to any other type) -mapping (string -> uint) public balances; +mapping (string => uint) public balances; balances["john"] = 1; console.log(balances[jill]); // is 0, all non-set key values return zeroes // The 'public' lets you do the following from another contract @@ -322,13 +324,14 @@ suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the add // planning your data structures) // *** EXAMPLE: Let's do a more complex example *** -// [TODO: Decide what a more complex example looks like, needs a few // characteristics: +// [TODO: Decide what a more complex example looks like, needs a few characteristics: // - has a 'constant' state variable // - has a state machine (uses modifier) // - sends money to an address // - gets information from another contract (we'll show code for both contracts) // - Shows inheritance // - show variables being passed in on instantiation (and guard code to throw if variables not provided) +// - Shows the swapping out of a contract // Ideas: // - crowdfunding? // - Peer to peer insurance @@ -375,7 +378,9 @@ sha256("def"); // All data to the start of time is stored in the blockchain, so you and // anyone can observe all previous data states -// 9. STYLE NOTES +// 9. TESTING + +// 10. STYLE NOTES // Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) ``` -- cgit v1.2.3 From 700f3e7a1cb6ef5b905eac7ec3fe3aa2e713c079 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 15:45:03 -0500 Subject: Many minor updates --- solidity.html.markdown | 226 +++++++++++++++++++++++++++++++------------------ 1 file changed, 145 insertions(+), 81 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 88ccd817..0fa1fddc 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -14,7 +14,7 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language -// START EXAMPLE +// ** START EXAMPLE ** // Start with a Natspec comment (the three slashes) that can be used // for documentation - and as descriptive data for UI elements /// @title A simple deposit/withdrawal bank built on Bitcoin @@ -22,31 +22,30 @@ As Solidity and Ethereum are under active development, experimental or beta feat // All contracts are declared and named (in CamelCase) // They are similar to 'class' in other languages (and allow capabilities like inheritance) contract AcmeBank { - // Declare state variables outside a function, + // Declare state variables outside a function, // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address => uint) balances; + mapping (address => uint) balances; + + // the 'public' makes 'owner' externally readable by users or contracts + // (but not writeable) - + address public owner; - // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable), the 'constant' means this value to be - // changed after initialization - address public owner; - // Constructor, can receive one or many variables here function AcmeBank() { - // msg is a default variable that provides both the + // msg is a default variable that provides both the // contract messager's address and amount owner = msg.sender; // msg.sender refers to the address of the contract creator } - - function deposit(uint balance) { + + function deposit(uint balance) public { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable return balances[msg.sender]; // msg.sender refers to the contract caller } - function withdraw(uint withdrawAmount) returns (uint remainingBalance) { + function withdraw(uint withdrawAmount) public returns (uint remainingBalance) { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; @@ -58,8 +57,9 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this contract - but does mean that users have to trust the owner - function remove () { + // It's good practice to have a remove function, which disables this + // contract - but does mean that users have to trust the owner + function remove() { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner } @@ -71,29 +71,35 @@ contract AcmeBank { } // Fallback function - // This function is called if invalid data is sent or ether without data; + // The fallback function is called if none of the other functions matches the given function identifier. + // It is often meant to be called when invalid data is sent or ether without data. // Added so that ether sent to this contract is reverted if the contract fails // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } } -// END EXAMPLE +// ** END EXAMPLE ** // Now let's go through the basics of Solidity -// 1. DATA TYPES +// 1. DATA TYPES AND ASSOCIATED METHOD // uint is the data type typically used for currency (there are no doubles // or floats) and for dates -uint x; -int constant a = 8; // int of 256 bits, cannot be changed after instantiation +uint x; + + +// with 'constant', the compiler replaces each occurence with the acutal value +// int of 256 bits, cannot be changed after instantiation +int constant a = 8; +int256 constant a = 8; // same effect as line above, here the 256 is explict + +// For both int and uint, you can explicitly set space in steps of 8 +// e.g., int8, int16 uint8 b; int64 c; -// int256 is same as int -// For both int and uint, you can explicitly set space in steps of 8, -// e.g., int8, int16 uint248 e; // Type casting -int x = int(b) +int x = int(b); bool b = true; // or do 'var b = true;' for inferred typing @@ -115,21 +121,22 @@ bytes m; // A special array, same as byte[] (but packed tightly) string n = 'hello'; // Type inference -// var does inferred typing based on first assignment, +// var does inferred typing based on first assignment, // can't be used in functions parameters var a = true; -// there are edge cases where inference leads to a value being set (e.g., an uint 8) +// there are edge cases where inference leads to a value being set (e.g., an uint 8) // that is different from what the user wanted (uint16), so use carefully // by default, all values are set to 0 on instantiation -// Delete can be called on most types, and will set the values to 0 +// Delete can be called on most types, and will set the values to 0 by assignment uint x = 5; delete(x); // x is now 0 // 2. DATA STRUCTURES // Arrays -bytes32[] names; +bytes32[5] nicknames; // static array +bytes32[] names; // dynamic array uint newLength = names.push("John"); // adding returns new length of the array // Length names.length; // get length @@ -153,13 +160,13 @@ delete(balances); // deletes all elements // Unlike languages like Javascript, you cannot iterate through all elements in // a map, without knowing the source keys -// Structs and enums +// Structs and enums struct Bank { // note the capital address owner; uint balance; } Bank b = Bank({ - owner: msg.sender, + owner: msg.sender, balance: 5 }); delete(b); // set all values to 0, except any mappings @@ -168,29 +175,39 @@ delete(b); // set all values to 0, except any mappings enum State { Created, Locked, Inactive }; State public state; // Declare variable from enum state = State.Created; +// enums can be explicitly converted to ints -// 3. Variables of note -// storage - A persistent storage hash (does not need to be declared) -storage['abc'] = 'def'; // maps 256 bit words to 256 bit words +// Data locations: Memory vs. storage - all complex types (arrays, structs) have a data location +// 'memory' does not persist, 'storage' does +// Default is 'storage' for local and state variables; 'memory' for function parameters -// tx - This transaction -tx.origin // address, sender of the transaction -tx.gasprice // uint, gas price of the transaction +// 3. Variables of note +// ** this ** +this; // the address of the current contract +// 'balance' often used at the end of a contracts life to send the +// remaining balance to a party +this.balance; +this.someFunction(); // calls a function externally (via a message call, not via an internal jump) -// msg - The current message received by the contract +// ** msg - The current message received by the contract ** ** msg.sender; // address, The address of the sender msg.value; // uint, The amount of gas provided to this contract in wei -msg.data // bytes, complete call data +msg.data; // bytes, complete call data +msg.gas; // remaining gas -// balance of the current contract (both contract and external accounts -// have balances) - often used at the end of a contracts life to send the -// remaining balance to a party -this.balance -// block +// ** tx - This transaction ** +tx.origin; // address, sender of the transaction +tx.gasprice; // uint, gas price of the transaction + +// ** block - Information about the current block ** now // uint, current time, alias for block.timestamp -block.number // uint, current block number -block.difficulty // uint, current block difficulty -block.blockhash(1) // returns bytes32, only provides for most recent 256 block +block.number; // uint, current block number +block.difficulty; // uint, current block difficulty +block.blockhash(1); // returns bytes32, only provides for most recent 256 blocks +block.gasLimit(); + +// ** storage - A persistent storage hash (does not need to be declared) ** +storage['abc'] = 'def'; // maps 256 bit words to 256 bit words // 4. FUNCTIONS AND MORE // A. Functions @@ -236,13 +253,13 @@ function b() { // B. Events // Events are an easy way to notify external listeners that something changed -// You typically decalre them after your contract parameters +// You typically declare them after your contract parameters event Sent(address from, address to, uint amount); // You then call it in a function, when you want to trigger it sent(from, to, amount); -// For an external party (a contract or external entity), to watch +// For an external party (a contract or external entity), to watch // for an event, you write the following: Coin.Sent().watch({}, '', function(error, result) { if (!error) { @@ -254,53 +271,89 @@ Coin.Sent().watch({}, '', function(error, result) { "Receiver: " + Coin.balances.call(result.args.to)); } } -// This is a common paradigm for one contract to depend on another (e.g., a +// This is a common paradigm for one contract to depend on another (e.g., a // contract that depends on the current exchange rate provided by another // contract) // C. Modifiers -// Modifiers let you validate inputs to functions -// The '_' (underscore) must be included, and is an indicator that the +// Modifiers let you validate inputs to functions such as a minimal balance or user authentication +// It's similar to a guard clause in other languages + +// The '_' (underscore) must be included as the last line in the function body, and is an indicator that the // function being called should be placed there modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } // You can then append it right after the function declaration -function test() - onlyBefore() -{ - +function changeOwner(newOwner) + onlyBefore(someTime) + { + owner = newOwner; } // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return // switch is not provided -// Syntax is the same as javascript, but there is no type conversion from -// non-boolean to boolean -// 6. CALLING AN EXTERNAL CONTRACT +// Syntax is the same as javascript, but there is no type conversion from +// non-boolean to boolean, so comparison operators must be used to get the boolean value + +// 6. OBJECTS/CONTRACTS +// A. Calling an external contract contract infoFeed { function info() returns (uint ret) { return 42; } } contract Consumer { InfoFeed feed; // create a variable that will point to a contract on the blockchain - function setFeed(address addr) { + + // Set feed to an existing contract + function setFeed(address addr) { // Link to the contract by creating on the address - feed = InfoFeed(addr); + feed = InfoFeed(addr); } - function callFeed() { - // T final parentheses call the contract, optionally adding + + // Set feed based to a new instance of the contract + function createNewFeed() { + feed = new InfoFeed(); + } + + function callFeed() { + // T final parentheses call the contract, optionally adding // custom value or gas numbers feed.info.value(10).gas(800)(); } } +// B. Inheritance + +// Order matters, last inherited contract (i.e., 'def') can override parts of the previously +// inherited contracts +contact MyContract is abc, def("a custom argument to def") { + +// Override function + + function z() { + if (msg.sender == owner) { + def.z(); // call overridden function + } + } + + }; + +// C. Import + +import "filename"; +import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; + +// Importing is under active development and will change +// Importing cannot currently be done at the command line + // 7. CONTRACT DESIGN PATTERNS // A. Obfuscation -// Remember that all variables are publicly viewable on the blockchain, so +// Remember that all variables are publicly viewable on the blockchain, so // anything that needs some privacy needs to be obfuscated (e.g., hashed) // B. Throwing @@ -317,26 +370,34 @@ if (!addr.send(123)) { // Suicide suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) +// This is a common pattern that lets the owner end the contract +function remove() { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } +} + // D. Storage optimization -// Reading and writing can be expensive, as data needs to be stored in the -// blockchain forever - this encourages smart ways to use memory (eventually, -// compilation may better handle this, but for now there are benefits to +// Reading and writing can be expensive, as data needs to be stored in the +// blockchain forever - this encourages smart ways to use memory (eventually, +// compilation may better handle this, but for now there are benefits to // planning your data structures) // *** EXAMPLE: Let's do a more complex example *** + +// ** START EXAMPLE ** // [TODO: Decide what a more complex example looks like, needs a few characteristics: // - has a 'constant' state variable -// - has a state machine (uses modifier) +// - has a state machine (and uses modifier) // - sends money to an address // - gets information from another contract (we'll show code for both contracts) // - Shows inheritance // - show variables being passed in on instantiation (and guard code to throw if variables not provided) -// - Shows the swapping out of a contract +// - Shows the swapping out of a contract address // Ideas: // - crowdfunding? // - Peer to peer insurance // ] - // *** END EXAMPLE *** // Some final points @@ -353,7 +414,7 @@ uint a = 1 finney; // 1 ether = 1000 finney 1 minutes == 60 seconds -// You typically multiply a variable times the unit, as these units are not +// You typically multiply a variable times the unit, as these units are not // directly stored in a variable uint x = 5; (x * 1 days); // 5 days @@ -366,22 +427,22 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); -// These are natspec comments, when a user is asked to confirm a transaction -/// -/** */ +// 8. COMMON MISTAKES/MISCONCEPTIONS +// A few common mistakes and misconceptions: -// 8. COMMON MISTAKES -// A few common mistakes -// You cannot restrict a human or computer from reading the content of +// A. You cannot restrict a human or computer from reading the content of // your transaction or a transaction's state -// All data to the start of time is stored in the blockchain, so you and -// anyone can observe all previous data states +// All data to the start of time is stored in the blockchain, so you and +// anyone can observe all previous data stats -// 9. TESTING +// When you don't specify public on a variable, you are indicating that other *contracts* can't +// read the data - but any person can still read the data -// 10. STYLE NOTES -// Use 4 spaces for indentation +// TODO + +// 9. STYLE NOTES +// Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) ``` @@ -391,4 +452,7 @@ sha256("def"); - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) -Feel free to send a pull request with any edits - or email nemild -/at-/ gmail \ No newline at end of file +## Information purposefully excluded +- Libraries + +Feel free to send a pull request with any edits - or email nemild -/at-/ gmail -- cgit v1.2.3 From ec6172fc5e904c65e672ca22bbc6102a94a60ec9 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 15:48:47 -0500 Subject: Formatting --- solidity.html.markdown | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 0fa1fddc..2adfc00b 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -81,12 +81,12 @@ contract AcmeBank { // Now let's go through the basics of Solidity -// 1. DATA TYPES AND ASSOCIATED METHOD + +// 1. DATA TYPES AND ASSOCIATED METHODS // uint is the data type typically used for currency (there are no doubles // or floats) and for dates uint x; - // with 'constant', the compiler replaces each occurence with the acutal value // int of 256 bits, cannot be changed after instantiation int constant a = 8; @@ -133,6 +133,7 @@ var a = true; uint x = 5; delete(x); // x is now 0 + // 2. DATA STRUCTURES // Arrays bytes32[5] nicknames; // static array @@ -181,6 +182,7 @@ state = State.Created; // 'memory' does not persist, 'storage' does // Default is 'storage' for local and state variables; 'memory' for function parameters + // 3. Variables of note // ** this ** this; // the address of the current contract @@ -209,6 +211,7 @@ block.gasLimit(); // ** storage - A persistent storage hash (does not need to be declared) ** storage['abc'] = 'def'; // maps 256 bit words to 256 bit words + // 4. FUNCTIONS AND MORE // A. Functions // Simple function @@ -290,6 +293,7 @@ function changeOwner(newOwner) owner = newOwner; } + // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return @@ -298,6 +302,7 @@ function changeOwner(newOwner) // Syntax is the same as javascript, but there is no type conversion from // non-boolean to boolean, so comparison operators must be used to get the boolean value + // 6. OBJECTS/CONTRACTS // A. Calling an external contract @@ -350,6 +355,7 @@ import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; // Importing is under active development and will change // Importing cannot currently be done at the command line + // 7. CONTRACT DESIGN PATTERNS // A. Obfuscation @@ -383,6 +389,8 @@ function remove() { // compilation may better handle this, but for now there are benefits to // planning your data structures) + + // *** EXAMPLE: Let's do a more complex example *** // ** START EXAMPLE ** @@ -400,7 +408,7 @@ function remove() { // ] // *** END EXAMPLE *** -// Some final points + // 7. NATIVE FUNCTIONS // Currency units @@ -427,6 +435,7 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); + // 8. COMMON MISTAKES/MISCONCEPTIONS // A few common mistakes and misconceptions: @@ -441,6 +450,7 @@ sha256("def"); // TODO + // 9. STYLE NOTES // Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) -- cgit v1.2.3 From 4b7d7e3d2e86e6e2d5b95b518864ecd89392d7c0 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:01:51 -0500 Subject: Spelling and grammar --- solidity.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2adfc00b..3e47f080 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -72,7 +72,7 @@ contract AcmeBank { // Fallback function // The fallback function is called if none of the other functions matches the given function identifier. - // It is often meant to be called when invalid data is sent or ether without data. + // Typically, called when invalid data is sent to the contract or ether without data. // Added so that ether sent to this contract is reverted if the contract fails // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } @@ -87,10 +87,10 @@ contract AcmeBank { // or floats) and for dates uint x; -// with 'constant', the compiler replaces each occurence with the acutal value +// with 'constant', the compiler replaces each occurrence with the actual value // int of 256 bits, cannot be changed after instantiation int constant a = 8; -int256 constant a = 8; // same effect as line above, here the 256 is explict +int256 constant a = 8; // same effect as line above, here the 256 is explicit // For both int and uint, you can explicitly set space in steps of 8 // e.g., int8, int16 @@ -221,7 +221,7 @@ function increment(uint x) returns (uint) { } // Functions can return many arguments, and by specifying the returned arguments -// you don't need to explicity return +// you don't need to explicitly return function increment(uint x, uint y) returns (uint x, uint y) { x += 1; y += 1; @@ -241,7 +241,7 @@ function increment(uint x) constant returns (uint x) { // There are a few 'function visibility specifiers' that can be placed where 'constant' // is, which include: // internal (can only be called by an internal function, not one external to the contract) -// public - visibile externally and internally +// public - visible externally and internally // private - only visible in the current contract // Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable -- cgit v1.2.3 From 8ef890b0de22d9fd14572f4ac171a238ea4f3f20 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:14:26 -0500 Subject: Added sample contracts --- solidity.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/solidity.html.markdown b/solidity.html.markdown index 3e47f080..2b461a95 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -462,6 +462,10 @@ sha256("def"); - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +## Sample contracts +- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) +- [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) + ## Information purposefully excluded - Libraries -- cgit v1.2.3 From add8f68f1acdceca1b9e09d6458627c515e73047 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:51:53 -0500 Subject: Add exposition around example bank --- solidity.html.markdown | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2b461a95..77648e51 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -13,6 +13,10 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language +// This bank has three main capabilities: +// - deposit +// - withdrawal +// - check balance // ** START EXAMPLE ** // Start with a Natspec comment (the three slashes) that can be used @@ -57,14 +61,6 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this - // contract - but does mean that users have to trust the owner - function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } - } - // The 'constant' prevents the function from editing state variables function balance() constant { return balances[msg.sender]; @@ -406,6 +402,14 @@ function remove() { // - crowdfunding? // - Peer to peer insurance // ] + // It's good practice to have a remove function, which disables this + // contract - but does mean that users have to trust the owner + // For a decentralized bank without a trusted part + function remove() { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } + } // *** END EXAMPLE *** -- cgit v1.2.3 From 541c278de4b253090b27a1ef126f5ed27e050f7c Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 17:23:41 -0500 Subject: Minor updates --- solidity.html.markdown | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 77648e51..298b01f3 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -30,10 +30,13 @@ contract AcmeBank { // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address => uint) balances; + // the private means that other contracts can't see balances + // but the data is still available to all other parties on the + // blockchain + mapping (address => uint) private balances; // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable) - + // (but not writeable) address public owner; // Constructor, can receive one or many variables here @@ -125,9 +128,10 @@ var a = true; // by default, all values are set to 0 on instantiation -// Delete can be called on most types, and will set the values to 0 by assignment +// Delete can be called on most types +// (it does NOT destroy the value, but rather sets the value to 0 by assignment) uint x = 5; -delete(x); // x is now 0 +delete x; // x is now 0 // 2. DATA STRUCTURES @@ -151,8 +155,8 @@ function balances(address _account) returns (uint balance) { } // To delete -delete(balances["John"]); -delete(balances); // deletes all elements +delete balances["John"]; +delete balances; // deletes all elements // Unlike languages like Javascript, you cannot iterate through all elements in // a map, without knowing the source keys @@ -166,7 +170,7 @@ Bank b = Bank({ owner: msg.sender, balance: 5 }); -delete(b); // set all values to 0, except any mappings +delete b; // set all variables in struct to 0, except any mappings // Enums enum State { Created, Locked, Inactive }; @@ -226,6 +230,7 @@ function increment(uint x, uint y) returns (uint x, uint y) { uint (a,b) = increment(1,1); // The 'constant' indicates and ensures that a function does not/cannot change the persistent variables +// Constant function execute locally, not on the blockchain uint y; function increment(uint x) constant returns (uint x) { @@ -469,6 +474,7 @@ sha256("def"); ## Sample contracts - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) - [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) +- [State of Dapps](http://dapps.ethercasts.com/) ## Information purposefully excluded - Libraries -- cgit v1.2.3 From ad19e8803a4ebc21f16d3407cf64f368b0745597 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 5 Dec 2015 15:18:15 +0100 Subject: [PowerShell/en]: didn't recognize code blocks --- powershell.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/powershell.html.markdown b/powershell.html.markdown index 4bc1ab39..8920d254 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -18,6 +18,7 @@ rather than plain text. [Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) If you are uncertain about your environment: + ``` Get-ExecutionPolicy -List Set-ExecutionPolicy AllSigned @@ -33,6 +34,7 @@ $PSVersionTable ``` Getting help: + ``` # Find commands Get-Command about_* # alias: gcm @@ -49,6 +51,7 @@ Update-Help # Run as admin ``` The tutorial starts here: + ``` # As you already figured, comments start with # @@ -292,6 +295,7 @@ $Shortcut.Save() Configuring your shell + ``` # $Profile is the full path for your `Microsoft.PowerShell_profile.ps1` # All code there will be executed when the PS session starts -- cgit v1.2.3 From 73fbc7f75512ac61493e4f82f0fc5108229124f3 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Sun, 6 Dec 2015 00:00:07 +0800 Subject: Rename file by adding -tw suffix. --- zh-tw/python-tw.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index c4706c43..472b39ab 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -7,7 +7,7 @@ contributors: - ["evuez", "http://github.com/evuez"] translators: - ["Michael Yeh", "https://hinet60613.github.io/"] -filename: learnpython.py +filename: learnpython-tw.py lang: zh-tw --- -- cgit v1.2.3 From 2f85645c9f988663c2f584fb23392d873fc3c8e9 Mon Sep 17 00:00:00 2001 From: Anton Davydov Date: Wed, 9 Dec 2015 00:03:06 +0300 Subject: [common-lisp/en] Fix code in examples --- common-lisp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 2b1f5de4..9a23bc26 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -339,7 +339,7 @@ nil ; for false - and the empty list ;; The () in the above is the list of arguments for the function (defun hello (name) - (format nil "Hello, ~a " name)) + (format nil "Hello, ~a" name)) (hello "Steve") ; => "Hello, Steve" @@ -430,7 +430,7 @@ nil ; for false - and the empty list (defun walker (n) (if (zerop n) :walked - (walker (1- n)))) + (walker (- n 1)))) (walker 5) ; => :walked -- cgit v1.2.3 From fb4f346686e49658d3d74f6656b20138649cfedd Mon Sep 17 00:00:00 2001 From: we-build-dreams Date: Thu, 10 Dec 2015 12:21:21 +0000 Subject: Update elm.html.markdown only typos --- elm.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/elm.html.markdown b/elm.html.markdown index 8c191509..f8564c4b 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -76,13 +76,13 @@ snd ("elm", 42) -- 42 -- Records are like tuples but the fields have names. -- Notice that equals signs, not colons, are used. -{ x = 3, y = 7} +{ x = 3, y = 7 } -- Access a field with a dot and the field name. -{ x = 3, y = 7}.x -- 3 +{ x = 3, y = 7 }.x -- 3 -- Or with an accessor fuction, a dot and then the field name. -.y { x = 3, y = 7} -- 7 +.y { x = 3, y = 7 } -- 7 -- Update the fields of a record. (It must have the fields already.) { person | @@ -126,7 +126,7 @@ case List.head aList of multiply a b = a * b --- Apply (call) a function by passing it arguments (no commas necessay). +-- Apply (call) a function by passing it arguments (no commas necessary). multiply 7 6 -- 42 -- Partially apply a function by passing only some of its arguments. @@ -168,7 +168,7 @@ fib n = else fib (n - 1) + fib (n - 2) -List.map fib [0..8] -- [1, 1, 2, 3, 5, 8,13, 21, 34] +List.map fib [0..8] -- [1, 1, 2, 3, 5, 8, 13, 21, 34] listLength aList = case aList of -- cgit v1.2.3 From 8bc9ebe08d792f560939db1e39077c800d15497b Mon Sep 17 00:00:00 2001 From: Mario Martinez Date: Fri, 11 Dec 2015 11:01:23 -0600 Subject: Updated to sdkman instead of GVM for installing groovy --- groovy.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 8fb1b346..37e3b20c 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -13,8 +13,8 @@ Groovy - A dynamic language for the Java platform [Read more here.](http://groov /* Set yourself up: - 1) Install GVM - http://gvmtool.net/ - 2) Install Groovy: gvm install groovy + 1) Install SDKMAN - http://sdkman.io/ + 2) Install Groovy: sdk install groovy 3) Start the groovy console by typing: groovyConsole */ -- cgit v1.2.3 From 8d7085893535825ea6879e3f29ee0eb614a16f9b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Fri, 11 Dec 2015 13:07:01 -0500 Subject: Few minor fixes --- solidity.html.markdown | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 298b01f3..7f925918 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -5,9 +5,9 @@ contributors: - ["Nemil Dalal", "https://www.nemil.com"] --- -Solidity is a statically typed, contract programming language for [Ethereum](https://www.ethereum.org/) that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. +Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. -Solidity lets you program on Ethereum, a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. +Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. @@ -46,7 +46,7 @@ contract AcmeBank { owner = msg.sender; // msg.sender refers to the address of the contract creator } - function deposit(uint balance) public { + function deposit(uint balance) public returns (uint) { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable return balances[msg.sender]; // msg.sender refers to the contract caller @@ -65,7 +65,7 @@ contract AcmeBank { } // The 'constant' prevents the function from editing state variables - function balance() constant { + function balance() constant returns (uint) { return balances[msg.sender]; } @@ -90,6 +90,7 @@ uint x; // int of 256 bits, cannot be changed after instantiation int constant a = 8; int256 constant a = 8; // same effect as line above, here the 256 is explicit +uint constant VERSION_ID = 0x123A1; // A hex constant // For both int and uint, you can explicitly set space in steps of 8 // e.g., int8, int16 @@ -285,12 +286,14 @@ Coin.Sent().watch({}, '', function(error, result) { // The '_' (underscore) must be included as the last line in the function body, and is an indicator that the // function being called should be placed there -modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } +modifier onlyAfter(uint _time) { if (now <= _time) throw; _ } +modifier onlyOwner { if (msg.sender == owner) _ } // You can then append it right after the function declaration function changeOwner(newOwner) - onlyBefore(someTime) - { +onlyAfter(someTime) +onlyOwner() +{ owner = newOwner; } @@ -298,7 +301,7 @@ function changeOwner(newOwner) // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return -// switch is not provided +// Unlike other languages, the 'switch' statement is NOT provided // Syntax is the same as javascript, but there is no type conversion from // non-boolean to boolean, so comparison operators must be used to get the boolean value @@ -377,7 +380,7 @@ if (!addr.send(123)) { // Suicide suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) -// This is a common pattern that lets the owner end the contract +// This is a common contract pattern that lets the owner end the contract, and receive remaining funds function remove() { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner @@ -391,7 +394,6 @@ function remove() { // planning your data structures) - // *** EXAMPLE: Let's do a more complex example *** // ** START EXAMPLE ** @@ -472,6 +474,7 @@ sha256("def"); - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) ## Sample contracts +- [Dapp Bin](https://github.com/ethereum/dapp-bin) - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) - [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) -- cgit v1.2.3 From 4aca8f16dfec1a9341648b0ff1724ada01cdc2b0 Mon Sep 17 00:00:00 2001 From: Max Goldstein Date: Sun, 13 Dec 2015 13:29:50 -0500 Subject: [elm/en] Minor copyediting --- elm.html.markdown | 68 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/elm.html.markdown b/elm.html.markdown index 8c191509..67a0006d 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -38,11 +38,10 @@ not False -- True 1 < 10 -- True -- Strings and characters -"This is a string." -'a' -- character -'You cant use single quotes for strings.' -- error! +"This is a string because it uses double quotes." +'a' -- characters in single quotes --- Strings can be appended +-- Strings can be appended. "Hello " ++ "world!" -- "Hello world!" {-- Lists, Tuples, and Records --} @@ -53,10 +52,10 @@ not False -- True -- The second example can also be written with two dots. [1..5] --- Append lists just like strings +-- Append lists just like strings. [1..5] ++ [6..10] == [1..10] -- True --- To add one item, use "cons" +-- To add one item, use "cons". 0 :: [1..5] -- [0, 1, 2, 3, 4, 5] -- The head and tail of a list are returned as a Maybe. Instead of checking @@ -64,6 +63,7 @@ not False -- True List.head [1..5] -- Just 1 List.tail [1..5] -- Just [2, 3, 4, 5] List.head [] -- Nothing +-- List.functionName means the function lives in the List module. -- Every element in a tuple can be a different type, but a tuple has a -- fixed length. @@ -74,23 +74,24 @@ List.head [] -- Nothing fst ("elm", 42) -- "elm" snd ("elm", 42) -- 42 --- Records are like tuples but the fields have names. --- Notice that equals signs, not colons, are used. +-- Records are like tuples but the fields have names. The order of fields +-- doesn't matter. Notice that record values use equals signs, not colons. { x = 3, y = 7} -- Access a field with a dot and the field name. { x = 3, y = 7}.x -- 3 --- Or with an accessor fuction, a dot and then the field name. +-- Or with an accessor fuction, which is a dot and the field name on its own. .y { x = 3, y = 7} -- 7 -- Update the fields of a record. (It must have the fields already.) { person | name = "George" } -{ physics | - position = physics.position + physics.velocity, - velocity = physics.velocity + physics.acceleration } +-- Update multiple fields at once, using the current values. +{ particle | + position = particle.position + particle.velocity, + velocity = particle.velocity + particle.acceleration } {-- Control Flow --} @@ -111,11 +112,15 @@ else -- Use case statements to pattern match on different possibilities. case aList of [] -> "matches the empty list" + [x]-> "matches a list of exactly one item, " ++ toString x x::xs -> "matches a list of at least one item whose head is " ++ toString x +-- Pattern matches go in order. If we put [x] last, it would never match because +-- x::xs also matches (xs would be the empty list). Matches do not "fall through". +-- Pattern match on a Maybe. case List.head aList of Just x -> "The head is " ++ toString x - Nothing -> "The list was empty" + Nothing -> "The list was empty." {-- Functions --} @@ -151,8 +156,8 @@ area (width, height) = area (6, 7) -- 42 --- Use curly brackets to pattern match record field names --- Use let to define intermediate values +-- Use curly brackets to pattern match record field names. +-- Use let to define intermediate values. volume {width, height, depth} = let area = width * height @@ -161,7 +166,7 @@ volume {width, height, depth} = volume { width = 3, height = 2, depth = 7 } -- 42 --- Functions can be recursive +-- Functions can be recursive. fib n = if n < 2 then 1 @@ -170,12 +175,13 @@ fib n = List.map fib [0..8] -- [1, 1, 2, 3, 5, 8,13, 21, 34] +-- Another recursive function (use List.length in real code). listLength aList = case aList of [] -> 0 x::xs -> 1 + listLength xs --- Function application happens before any infix operation +-- Function calls happen before any infix operator. Parens indicate precedence. cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 -- First degrees is applied to 30, then the result is passed to the trig -- functions, which is then squared, and the addition happens last. @@ -191,7 +197,7 @@ cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 True : Bool -- Functions have types too. Read -> as "goes to". Think of the rightmost type --- as the type of the return value. +-- as the type of the return value, and the others as arguments. not : Bool -> Bool round : Float -> Int @@ -226,7 +232,7 @@ type alias Point3D = { x : Float, y : Float, z : Float } otherOrigin : Point3D otherOrigin = Point3D 0 0 0 --- But it's still the same type, you can equate them +-- But it's still the same type, so you can equate them. origin == otherOrigin -- True -- By contrast, defining a union type creates a type that didn't exist before. @@ -236,14 +242,15 @@ type Direction = North | South | East | West -- Tags can carry other values of known type. This can work recursively. type IntTree = Leaf | Node Int IntTree IntTree - -- "Leaf" and "Node" are the tags. Everything following a tag is a type. + -- Tags can be used as values or functions. root : IntTree root = Node 7 Leaf Leaf -- Union types (and type aliases) can use type variables. type Tree a = Leaf | Node a (Tree a) (Tree a) +-- "The type tree of a is a leaf, or a node of a, tree of a, and tree of a." -- You can pattern match union tags. The uppercase tags must be matched exactly. -- The lowercase variables will match anything. Underscore also matches @@ -260,21 +267,20 @@ leftmostElement tree = {-- Modules and Imports --} --- The core libraries are organized into modulues, as are any third-party --- libraries you may use. For large projects, you can define your own modulues. +-- The core libraries are organized into modules, as are any third-party +-- libraries you may use. For large projects, you can define your own modules. -- Put this at the top of the file. If omitted, you're in Main. module Name where --- By default, everything is exported. --- Limit what values and types are exported -module Name (Type, value) where +-- By default, everything is exported. You can specify exports explicity. +module Name (MyType, myValue) where -- One common pattern is to export a union type but not its tags. This is known -- as an "opaque type", and is frequently used in libraries. --- Import code from other modules to use it in this one --- Places Dict in scope, so you can call Dict.insert +-- Import code from other modules to use it in this one. +-- Places Dict in scope, so you can call Dict.insert. import Dict -- Imports the Dict module and the Dict type, so your annotations don't have to @@ -318,6 +324,8 @@ $ elm repl -- Install a new package, and record it in elm-package.json. $ elm package install evancz/elm-html +-- See what changed between versions of a package. +$ elm package diff evancz/elm-html 3.0.0 4.0.2 -- Elm's package manager enforces semantic versioning, so minor version bumps -- will never break your build! ``` @@ -335,12 +343,14 @@ Here are some useful resources. * Documentation for [Elm's core libraries](http://package.elm-lang.org/packages/elm-lang/core/latest/). Take note of: * [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), which is imported by default - * Data structures like [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set) + * [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) and its cousin [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), commonly used for missing values or error handling + * Data structures like [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set) * JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) and [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode) -* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay with examples on how to organize code into components. +* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay by Elm's creator with examples on how to organize code into components. * The [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Everyone is friendly and helpful. +* [Scope in Elm](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) and [How to Read a Type Annotation](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). More community guides on the basics of Elm, written for JavaScript developers. Go out and write some Elm! -- cgit v1.2.3 From 0b8a0526249264c7ac34069adf3159f2b72771a8 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 18:03:47 -0500 Subject: Add info on references, modules, and objects These topics are central to modern usage of Perl. --- perl.html.markdown | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 125 insertions(+), 7 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 1b86f410..85f3974e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -5,6 +5,7 @@ language: perl filename: learnperl.pl contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Dan Book", "http://github.com/Grinnz"] --- Perl 5 is a highly capable, feature-rich programming language with over 25 years of development. @@ -14,7 +15,6 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f ```perl # Single line comments start with a number sign. - #### Perl variable types # Variables begin with a sigil, which is a symbol showing the type. @@ -37,7 +37,9 @@ my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23); - +# Array elements are accessed using square brackets, with a $ to indicate +# one value will be returned. +my $second = $animals[1]; ## Hashes # A hash represents a set of key/value pairs: @@ -50,11 +52,39 @@ my %fruit_color = ( apple => "red", banana => "yellow", ); + +# Hash elements are accessed using curly braces, again with the $ sigil. +my $color = $fruit_color{apple}; + # Scalars, arrays and hashes are documented more fully in perldata. # (perldoc perldata). -# More complex data types can be constructed using references, which allow you -# to build lists and hashes within lists and hashes. +#### References + +# More complex data types can be constructed using references, which allow +# you to build arrays and hashes within arrays and hashes. + +my $array_ref = \@array; +my $hash_ref = \%hash; +my @array_of_arrays = (\@array1, \@array2, \@array3); + +# You can also create anonymous arrays or hashes, returning a reference: + +my $fruits = ["apple", "banana"]; +my $colors = {apple => "red", banana => "yellow"}; + +# References can be dereferenced by prefixing the appropriate sigil. + +my @fruits_array = @$fruits; +my %colors_hash = %$colors; + +# As a shortcut, the arrow operator can be used to dereference and access a +# single value. + +my $first = $array_ref->[0]; +my $value = $hash_ref->{banana}; + +# See perlreftut and perlref for more in-depth documentation on references. #### Conditional and looping constructs @@ -105,6 +135,9 @@ for (@elements) { # the Perlish post-condition way again print for @elements; +# iterating through the keys and values of a referenced hash +print $hash_ref->{$_} for keys %$hash_ref; + #### Regular expressions # Perl's regular expression support is both broad and deep, and is the subject @@ -151,11 +184,96 @@ sub logger { # Now we can use the subroutine just as any other built-in function: logger("We have a logger subroutine!"); -``` -#### Using Perl modules +#### Modules + +# A module is a set of Perl code, usually subroutines, which can be used in +# other Perl code. It is usually stored in a file with the extension .pm so +# that Perl can find it. + +package MyModule; + +sub trim { + my $string = shift; + $string =~ s/^\s+//; + $string =~ s/\s+$//; + return $string; +} + +1; + +# From elsewhere: + +use MyModule; +MyModule::trim($string); + +# The Exporter module can help with making subroutines exportable, so they +# can be used like this: + +use MyModule 'trim'; +trim($string); + +# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) and +# provide a range of features to help you avoid reinventing the wheel. A +# number of popular modules like Exporter are included with the Perl +# distribution itself. See perlmod for more details on modules in Perl. + +#### Objects + +# Objects in Perl are just references that know which class (package) they +# belong to, so that methods (subroutines) called on it can be found there. +# The bless function is used in constructors (usually new) to set this up. +# However, you never need to call it yourself if you use a module like Moose +# or Moo (see below). + +package MyCounter; + +sub new { + my $class = shift; + my $self = {count => 0}; + return bless $self, $class; +} + +sub count { + my $self = shift; + return $self->{count}; +} + +sub increment { + my $self = shift; + $self->{count}++; +} + +1; + +# Methods can be called on a class or object instance with the arrow operator. + +my $counter = MyCounter->new; +print $counter->count, "\n"; # 0 +$counter->increment; +print $counter->count, "\n"; # 1 + +# The modules Moose and Moo from CPAN can help you set up your object classes. +# They provide a constructor and simple syntax for declaring attributes. This +# class can be used equivalently to the one above. + +package MyCounter; +use Moo; + +has 'count' => (is => 'rwp', default => 0, init_arg => undef); + +sub increment { + my $self = shift; + $self->_set_count($self->count + 1); +} + +1; + +# Object-oriented programming is covered more thoroughly in perlootut, and its +# low-level implementation in Perl is covered in perlobj. +``` -Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN (http://www.cpan.org/). A number of popular modules are included with the Perl distribution itself. +#### FAQ perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. -- cgit v1.2.3 From 35b3c490ce06fb94b8b51bd7f5ceb1638401fb1a Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:22:29 -0500 Subject: Add blurb about strict and warnings --- perl.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/perl.html.markdown b/perl.html.markdown index 85f3974e..ab71a6ab 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -15,6 +15,16 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f ```perl # Single line comments start with a number sign. +#### Strict and warnings + +use strict; +use warnings; + +# All perl scripts and modules should include these lines. Strict causes +# compilation to fail in cases like misspelled variable names, and warnings +# will print warning messages in case of common pitfalls like concatenating +# to an undefined value. + #### Perl variable types # Variables begin with a sigil, which is a symbol showing the type. -- cgit v1.2.3 From 88af462c699b9f48310a9624bb6bbe94b7101af1 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:39:37 -0500 Subject: use strict and warnings in example modules --- perl.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/perl.html.markdown b/perl.html.markdown index ab71a6ab..d919e00e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -202,6 +202,8 @@ logger("We have a logger subroutine!"); # that Perl can find it. package MyModule; +use strict; +use warnings; sub trim { my $string = shift; @@ -237,6 +239,8 @@ trim($string); # or Moo (see below). package MyCounter; +use strict; +use warnings; sub new { my $class = shift; @@ -268,7 +272,7 @@ print $counter->count, "\n"; # 1 # class can be used equivalently to the one above. package MyCounter; -use Moo; +use Moo; # imports strict and warnings has 'count' => (is => 'rwp', default => 0, init_arg => undef); -- cgit v1.2.3 From 16d879d712878e2d1aa262dc1218b6543aec99c9 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:51:57 -0500 Subject: add missing use line --- perl.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/perl.html.markdown b/perl.html.markdown index d919e00e..61e8cd0e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -262,6 +262,7 @@ sub increment { # Methods can be called on a class or object instance with the arrow operator. +use MyCounter; my $counter = MyCounter->new; print $counter->count, "\n"; # 0 $counter->increment; -- cgit v1.2.3 From 16cc4d464e135560c5d9f1495b6d9cd871e7182d Mon Sep 17 00:00:00 2001 From: Mark Green Date: Wed, 16 Dec 2015 16:47:32 +0000 Subject: Add a Factor tutorial --- factor.html | 182 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 factor.html diff --git a/factor.html b/factor.html new file mode 100644 index 00000000..a0726420 --- /dev/null +++ b/factor.html @@ -0,0 +1,182 @@ +--- +language: factor +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnfactor.factor +--- + +Factor is a modern stack-based language, based on Forth, created by Slava Pestov. + +Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. + +``` +! This is a comment + +! Like Forth, all programming is done by manipulating the stack. +! Stating a literal value pushes it onto the stack. +5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode + +! Those numbers get added to the stack, from left to right. +! .s prints out the stack non-destructively. +.s ! 5 2 3 56 76 23 65 + +! Arithmetic works by manipulating data on the stack. +5 4 + ! No output + +! `.` pops the top result from the stack and prints it. +. ! 9 + +! More examples of arithmetic: +6 7 * . ! 42 +1360 23 - . ! 1337 +12 12 / . ! 1 +13 2 mod . ! 1 + +99 neg . ! -99 +-99 abs . ! 99 +52 23 max . ! 52 +52 23 min . ! 23 + +! A number of words are provided to manipulate the stack, collectively known as shuffle words. + +3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3 +2 5 swap / ! swap the top with the second element: 5 / 2 +4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2 +1 2 3 nip .s ! remove the second item (similar to drop): 1 3 +1 2 clear .s ! wipe out the entire stack +1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 +1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3 + +! Creating Words +! The `:` word sets Factor into compile mode until it sees the `;` word. +: square ( n -- n ) dup * ; ! No output +5 square . ! 25 + +! We can view what a word does too. +! \ suppresses evaluation of a word and pushes its identifier on the stack instead. +\ square see ! : square ( n -- n ) dup * ; + +! After the name of the word to create, the declaration between brackets gives the stack effect. +! We can use whatever names we like inside the declaration: +: weirdsquare ( camel -- llama ) dup * ; + +! Provided their count matches the word's stack effect: +: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong +: doubledup ( a -- a a a ) dup dup ; ! Ok +: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok + +! Where Factor differs from Forth is in the use of quotations. +! A quotation is a block of code that is pushed on the stack as a value. +! [ starts quotation mode; ] ends it. +[ 2 + ] ! Quotation that adds 2 is left on the stack +4 swap call . ! 6 + +! And thus, higher order words. TONS of higher order words. +2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3 +3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4 +1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4 +4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 ) +1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values +2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack + +! Conditionals +! Any value is true except the built-in value f. +! A built-in value t does exist, but its use isn't essential. +! Conditionals are higher order words as with the combinators above. + +5 [ "Five is true" . ] when ! Five is true +0 [ "Zero is true" . ] when ! Zero is true +f [ "F is true" . ] when ! No output +f [ "F is false" . ] unless ! F is false +2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true + +! By default the conditionals consume the value under test, but starred variants +! leave it alone if it's true: + +5 [ . ] when* ! 5 +f [ . ] when* ! No output, empty stack, f is consumed because it's false + + +! Loops +! You've guessed it.. these are higher order words too. + +5 [ . ] each-integer ! 0 1 2 3 4 +4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 +5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello + +! Here's a list: +{ 2 4 6 8 } ! Goes on the stack as one item + +! Loop through the list: +{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9 +{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack + +! Loop reducing or building lists: +{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 } +{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8) +{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 +1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 } +1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 } + +! If all else fails, a general purpose while loop: +1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times + ! Yes, it's hard to read + ! That's what all those variant loops are for + +! Variables +! Usually Factor programs are expected to keep all data on the stack. +! Using named variables makes refactoring harder (and it's called Factor for a reason) +! Global variables, if you must: + +SYMBOL: name ! Creates name as an identifying word +"Bob" name set-global ! No output +name get-global . ! "Bob" + +! Named local variables are considered an extension but are available +! In a quotation.. +[| m n ! Quotation captures top two stack values into m and n + | m n + ] ! Read them + +! Or in a word.. +:: lword ( -- ) ! Note double colon to invoke lexical variable extension + 2 :> c ! Declares immutable variable c to hold 2 + c . ; ! Print it out + +! In a word declared this way, the input side of the stack declaration +! becomes meaningful and gives the variable names stack values are captured into +:: double ( a -- result ) a 2 * ; + +! Variables are declared mutable by ending their name with a shriek +:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a + a ! Push a + a 2 * a! ! Multiply a by 2 and store result back in a + a ; ! Push new value of a +5 mword2 ! Stack: 5 10 + +! Lists and Sequences +! We saw above how to push a list onto the stack + +0 { 1 2 3 4 } nth ! Access a particular member of a list: 1 +10 { 1 2 3 4 } nth ! Error: sequence index out of bounds +1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2 +10 { 1 2 3 4 } ?nth ! No error if out of bounds: f + +{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } +{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } +"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } +"Concat" "enate" append ! "Concatenate" - strings are sequences too +"Concatenate" "Reverse " prepend ! "Reverse Concatenate" +{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" +{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" + +! And if you want to get meta, quotations are sequences and can be dismantled.. +0 [ 2 + ] nth ! 2 +1 [ 2 + ] nth ! + +[ 2 + ] \ - suffix ! Quotation [ 2 + - ] + + +``` + +##Ready For More? + +* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html) -- cgit v1.2.3 From b19714080a8ac76c027851e9b4c80372def81f7b Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Thu, 17 Dec 2015 01:48:19 +0800 Subject: Fix some typo and non-fluency. --- zh-tw/python-tw.html.markdown | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 472b39ab..f8602769 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -69,11 +69,11 @@ from __future__ import division # 指數 (x的y次方) 2**4 # => 16 -# 括號即先乘除後加減 +# 用括號改變運算順序 (1 + 3) * 2 # => 8 # 布林運算 -# 注意 "and" 和 "or" 的大小寫 +# 注意 "and" 和 "or" 要用小寫 True and False #=> False False or True #=> True @@ -178,7 +178,7 @@ some_var = 5 # 方便好用 lower_case_with_underscores some_var # => 5 -# 存取沒有被賦值的變數會造成例外 +# 對沒有被賦值的變數取值會造成例外 # 請參考錯誤流程部分做例外處理 some_other_var # 造成 NameError @@ -191,15 +191,15 @@ li = [] # 你可以預先填好串列內容 other_li = [4, 5, 6] -# 用append()在串列後新增東西 append +# 用append()在串列後新增東西 li.append(1) # 此時 li 內容為 [1] li.append(2) # 此時 li 內容為 [1, 2] li.append(4) # 此時 li 內容為 [1, 2, 4] li.append(3) # 此時 li 內容為 [1, 2, 4, 3] # 用pop()移除串列尾端的元素 -li.pop() # => 3 and li is now [1, 2, 4] +li.pop() # => 3 ,此時 li 內容為 [1, 2, 4] # 然後再塞回去 -li.append(3) # li is now [1, 2, 4, 3] again. +li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3] # 你可以像存取陣列一樣的存取串列 li[0] # => 1 @@ -272,7 +272,7 @@ d, e, f = 4, 5, 6 # 也可以不寫括號 # 如果不加括號,預設會產生tuple g = 4, 5, 6 # => (4, 5, 6) # 你看,交換兩個值很簡單吧 -e, d = d, e # d is now 5 and e is now 4 +e, d = d, e # 此時 d 的值為 5 且 e 的值為 4 # 字典(Dictionary)用來儲存映射關係 @@ -289,7 +289,7 @@ filled_dict.keys() # => ["three", "two", "one"] # 你的執行結果可能與上面不同 # 譯註: 只能保證所有的key都有出現,但不保證順序 -# 用 "valuess()" 將所有的Value輸出到一個List中 +# 用 "values()" 將所有的Value輸出到一個List中 filled_dict.values() # => [3, 2, 1] # 註: 同上,不保證順序 @@ -457,16 +457,14 @@ add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行 -# 你可以定義接受多個變數的函式,這些變數是按照順序排序的 -# 如果不加*的話會被解讀為tuple +# 你可以定義接受多個變數的函式,用*來表示參數tuple def varargs(*args): return args varargs(1, 2, 3) # => (1, 2, 3) -# 你可以定義接受多個變數的函式,這些變數是按照keyword排序的 -# 如果不加**的話會被解讀為dictionary +# 你可以定義接受多個變數的函式,用**來表示參數dictionary def keyword_args(**kwargs): return kwargs @@ -555,6 +553,7 @@ class Human(object): # 注意前後的雙底線代表物件 # 還有被python用,但實際上是在使用者控制的命名 # 空間內的參數。你不應該自己宣告這樣的名稱。 + # 注意前後的雙底線代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 def __init__(self, name): # 將函式引入的參數 name 指定給實體的 name 參數 self.name = name -- cgit v1.2.3 From 4b4024b49581d0f80aa3ce815b726bac1af99ef7 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Thu, 17 Dec 2015 01:51:19 +0800 Subject: Fix typo --- zh-tw/python-tw.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index f8602769..553181d8 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -550,10 +550,8 @@ class Human(object): species = "H. sapiens" # 基礎建構函式,當class被實體化的時候會被呼叫 - # 注意前後的雙底線代表物件 - # 還有被python用,但實際上是在使用者控制的命名 - # 空間內的參數。你不應該自己宣告這樣的名稱。 - # 注意前後的雙底線代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 + # 注意前後的雙底線 + # 代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 def __init__(self, name): # 將函式引入的參數 name 指定給實體的 name 參數 self.name = name -- cgit v1.2.3 From da5ace143bd2a1fdfb73d8d56774968c787a7ae2 Mon Sep 17 00:00:00 2001 From: Max Goldstein Date: Wed, 16 Dec 2015 19:55:33 -0500 Subject: Mention unit; line breaks for style --- elm.html.markdown | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/elm.html.markdown b/elm.html.markdown index f395e85b..944ab770 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -74,6 +74,10 @@ List.head [] -- Nothing fst ("elm", 42) -- "elm" snd ("elm", 42) -- 42 +-- The empty tuple, or "unit", is sometimes used as a placeholder. +-- It is the only value of its type, also called "Unit". +() + -- Records are like tuples but the fields have names. The order of fields -- doesn't matter. Notice that record values use equals signs, not colons. { x = 3, y = 7 } @@ -116,6 +120,7 @@ case aList of x::xs -> "matches a list of at least one item whose head is " ++ toString x -- Pattern matches go in order. If we put [x] last, it would never match because -- x::xs also matches (xs would be the empty list). Matches do not "fall through". +-- The compiler will alert you to missing or extra cases. -- Pattern match on a Maybe. case List.head aList of @@ -226,11 +231,13 @@ origin = { x = 0, y = 0, z = 0 } -- You can give existing types a nice name with a type alias. -type alias Point3D = { x : Float, y : Float, z : Float } +type alias Point3D = + { x : Float, y : Float, z : Float } -- If you alias a record, you can use the name as a constructor function. otherOrigin : Point3D -otherOrigin = Point3D 0 0 0 +otherOrigin = + Point3D 0 0 0 -- But it's still the same type, so you can equate them. origin == otherOrigin -- True @@ -238,23 +245,27 @@ origin == otherOrigin -- True -- By contrast, defining a union type creates a type that didn't exist before. -- A union type is so called because it can be one of many possibilities. -- Each of the possibilities is represented as a "tag". -type Direction = North | South | East | West +type Direction = + North | South | East | West -- Tags can carry other values of known type. This can work recursively. -type IntTree = Leaf | Node Int IntTree IntTree +type IntTree = + Leaf | Node Int IntTree IntTree -- "Leaf" and "Node" are the tags. Everything following a tag is a type. -- Tags can be used as values or functions. root : IntTree -root = Node 7 Leaf Leaf +root = + Node 7 Leaf Leaf -- Union types (and type aliases) can use type variables. -type Tree a = Leaf | Node a (Tree a) (Tree a) --- "The type tree of a is a leaf, or a node of a, tree of a, and tree of a." +type Tree a = + Leaf | Node a (Tree a) (Tree a) +-- "The type tree-of-a is a leaf, or a node of a, tree-of-a, and tree-of-a." --- You can pattern match union tags. The uppercase tags must be matched exactly. --- The lowercase variables will match anything. Underscore also matches --- anything, but signifies that you aren't using it. +-- Pattern match union tags. The uppercase tags will be matched exactly. The +-- lowercase variables will match anything. Underscore also matches anything, +-- but signifies that you aren't using it. leftmostElement : Tree a -> Maybe a leftmostElement tree = case tree of -- cgit v1.2.3 From ecf5050e07747f4cc33a57ea11513a7ab3f66285 Mon Sep 17 00:00:00 2001 From: Chris Warrick Date: Thu, 17 Dec 2015 16:54:53 +0100 Subject: Remove incorrect list indentation in perl-pl --- pl-pl/perl-pl.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown index 9e8ade5b..029ca006 100644 --- a/pl-pl/perl-pl.html.markdown +++ b/pl-pl/perl-pl.html.markdown @@ -163,7 +163,7 @@ z repozytorium CPAN do zrealizowania konkretnego zadania. #### Do doczytania - - [perl-tutorial](http://perl-tutorial.org/) - - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html) - - [perldoc](http://perldoc.perl.org/) - - wbudowane w Perla: `perldoc perlintro` \ No newline at end of file + - [perl-tutorial](http://perl-tutorial.org/) + - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - wbudowane w Perla: `perldoc perlintro` -- cgit v1.2.3 From 442479a3c87d41fe1abf6ad344bb8733ef924fc8 Mon Sep 17 00:00:00 2001 From: Ondrej Simek Date: Thu, 17 Dec 2015 21:30:03 +0100 Subject: [markdown/cz] Fix missing 'lang' in front matter --- cs-cz/markdown.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 637f0ab6..4cba38b4 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Michal Martinek", "https://github.com/MichalMartinek"] filename: markdown.md +lang: cs-cz --- Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná -- cgit v1.2.3 From d0527c0428698c325a55ee046d0897c4e70a6ccc Mon Sep 17 00:00:00 2001 From: Mark Green Date: Fri, 18 Dec 2015 01:17:08 +0000 Subject: Wolfram Language tutorial --- wolfram.md | 137 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 wolfram.md diff --git a/wolfram.md b/wolfram.md new file mode 100644 index 00000000..4514006d --- /dev/null +++ b/wolfram.md @@ -0,0 +1,137 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnwolfram.nb +--- + +The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts. + +Wolfram Language has several interfaces: +* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input. +* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic +* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend + +The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. + +``` +(* This is a comment *) + +(* In Mathematica instead of using these comments you can create a text cell + and annotate your code with nicely typeset text and images *) + +(* Typing an expression returns the result *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Function Call *) +(* Note, function names (and everything else) are case sensitive *) +Sin[Pi/2] (* 1 *) + +(* Alternate Syntaxes for Function Call with one parameter *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Every syntax in WL has some equivalent as a function call *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Using a variable for the first time defines it and makes it global *) +x = 5 (* 5 *) +x == 5 (* True, C-style assignment and equality testing *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* I wasn't kidding when I said EVERYTHING has a function equivalent *) +x (* 20 *) + +(* Because WL is based on a computer algebra system, *) +(* using undefined variables is fine, they just obstruct evaluation *) +cow + 5 (* 5 + cow, cow is undefined so can't evaluate further *) +cow + 5 + 10 (* 15 + cow, it'll evaluate what it can *) +% (* 15 + cow, % fetches the last return *) +% - cow (* 15, undefined variable cow cancelled out *) +moo = cow + 5 (* Beware, moo now holds an expression, not a number! *) + +(* Defining a function *) +Double[x_] := x * 2 (* Note := to prevent immediate evaluation of the RHS + And _ after x to indicate no pattern matching constraints *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, @-syntax avoids queues of close brackets *) +(Pi/2) // Sin // Double(* 2, //-syntax lists functions in execution order *) + +(* For imperative-style programming use ; to separate statements *) +(* Discards any output from LHS and runs RHS *) +MyFirst[] := (Print@"Hello"; Print@"World") (* Note outer parens are critical + ;'s precedence is lower than := *) +MyFirst[] (* Hello World *) + +(* C-Style For Loop *) +PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Create an association *) +myHash[["Green"]] (* 2, use it *) +myHash[["Green"]] := 5 (* 5, update it *) +myHash[["Puce"]] := 3.5 (* 3.5, extend it *) +KeyDropFrom[myHash, "Green"] (* Wipes out key Green *) +Keys[myHash] (* {Red} *) +Values[myHash] (* {1} *) + +(* And you can't do any demo of Wolfram without showing this off *) +Manipulate[y^2, {y, 0, 20}] (* Return a reactive user interface that displays y^2 + and allows y to be adjusted between 0-20 with a slider. + Only works on graphical frontends *) +``` + +##Ready For More? + +* [Wolfram Language Documentation Center](http://reference.wolfram.com/language/) -- cgit v1.2.3 From dc97e779bce838ea4f1d1e51a20d78b253048406 Mon Sep 17 00:00:00 2001 From: Eric McCormick Date: Fri, 18 Dec 2015 09:35:15 -0600 Subject: replaced < and > in pre block the pre block was already inside a pre/code block in the rendered page, making it harder to read --- coldfusion.html.markdown | 50 +++++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index d49ad254..482612fe 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -233,40 +233,38 @@ ColdFusion started as a tag-based language. Almost all functionality is availabl Code for reference (Functions must return something to support IE) -
-<cfcomponent>
-	<cfset this.hello = "Hello" />
-	<cfset this.world = "world" />
-
-	<cffunction name="sayHello">
-		<cfreturn this.hello & ", " & this.world & "!" />
-	</cffunction>
+
+	
+	
+
+	
+		
+	
 	
-	<cffunction name="setHello">
-		<cfargument name="newHello" type="string" required="true" />
+	
+		
 		
-		<cfset this.hello = arguments.newHello />
+		
 		 
-		<cfreturn true />
-	</cffunction>
+		
+	
 	
-	<cffunction name="setWorld">
-		<cfargument name="newWorld" type="string" required="true" />
+	
+		
 		
-		<cfset this.world = arguments.newWorld />
+		
 		 
-		<cfreturn true />
-	</cffunction>
+		
+	
 	
-	<cffunction name="getHello">
-		<cfreturn this.hello />
-	</cffunction>
+	
+		
+	
 	
-	<cffunction name="getWorld">
-		<cfreturn this.world />
-	</cffunction>
-</cfcomponent>
-
+ + + + -- cgit v1.2.3 From e7d5e2878841aae872b293127f47e4a4d211475b Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sat, 19 Dec 2015 17:09:57 +0100 Subject: fix typos/mistakes --- it-it/python-it.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown index 49bbab08..3a4099e7 100644 --- a/it-it/python-it.html.markdown +++ b/it-it/python-it.html.markdown @@ -44,7 +44,7 @@ Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxi # restituito in automatico il risultato intero. 5 / 2 # => 2 -# Per le divisioni con la virgbola abbiamo bisogno di parlare delle variabili floats. +# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats. 2.0 # Questo è un float 11.0 / 4.0 # => 2.75 ahhh...molto meglio @@ -118,7 +118,7 @@ not False # => True # Un nuovo modo per fomattare le stringhe è il metodo format. # Questo metodo è quello consigliato "{0} possono essere {1}".format("le stringhe", "formattate") -# Puoi usare della parole chiave se non vuoi contare +# Puoi usare delle parole chiave se non vuoi contare "{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna") # None è un oggetto @@ -202,7 +202,7 @@ li[::-1] # => [3, 4, 2, 1] del li[2] # li è ora [1, 2, 3] # Puoi sommare le liste li + altra_li # => [1, 2, 3, 4, 5, 6] -# Nota: i valori per li ed _altri_li non sono modificati. +# Nota: i valori per li ed altra_li non sono modificati. # Concatena liste con "extend()" li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6] @@ -288,7 +288,7 @@ filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # Aggiungere elementi ad un set filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5} -# Fai interazioni su un set con & +# Fai intersezioni su un set con & other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} @@ -378,8 +378,8 @@ except IndexError as e: pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero. except (TypeError, NameError): pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. -else: # Optional clause to the try/except block. Must follow all except blocks - print "All good!" # Viene eseguita solo se il codice dentro try non genera eccezioni +else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except + print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni finally: # Eseguito sempre print "Possiamo liberare risorse qui" @@ -405,7 +405,7 @@ aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni # Puoi definire funzioni che accettano un numero variabile di argomenti posizionali -# che verranno interpretati come come tuple se non usi il * +# che verranno interpretati come tuple se non usi il * def varargs(*args): return args @@ -495,7 +495,7 @@ class Human(object): species = "H. sapiens" # Costruttore base, richiamato quando la classe viene inizializzata. - # Si noti che il doppio leading e l'underscore finali denotano oggetti + # Si noti che il doppio leading e gli underscore finali denotano oggetti # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato # dall'utente. Non dovresti usare nomi di questo genere. def __init__(self, name): @@ -575,7 +575,7 @@ dir(math) ## 7. Avanzate #################################################### -# Generators help you make lazy code +# I generatori ti aiutano a fare codice pigro def double_numbers(iterable): for i in iterable: yield i + i @@ -611,7 +611,7 @@ def beg(target_function): def wrapper(*args, **kwargs): msg, say_please = target_function(*args, **kwargs) if say_please: - return "{} {}".format(msg, "Please! I am poor :(") + return "{} {}".format(msg, "Per favore! Sono povero :(") return msg return wrapper @@ -619,17 +619,17 @@ def beg(target_function): @beg def say(say_please=False): - msg = "Can you buy me a beer?" + msg = "Puoi comprarmi una birra?" return msg, say_please -print say() # Can you buy me a beer? -print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +print say() # Puoi comprarmi una birra? +print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :( ``` -## Ready For More? +## Pronto per qualcosa di più? -### Free Online +### Gratis Online * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) @@ -640,7 +640,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) -### Dead Tree +### Libri cartacei * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 7560ea819965604099a3ed1dbf4e2fa8919e929b Mon Sep 17 00:00:00 2001 From: George Gognadze Date: Thu, 24 Dec 2015 23:24:09 +0400 Subject: typo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit some type mistakes. It is: syntaxtically It should be: syntactically It is: iLoveC Better: ILoveC It is: passed to ≈the function It should be: passed to the function It is: error It should be: Error --- c.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 8226ddef..d92d2ee6 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -239,7 +239,7 @@ int main (int argc, char** argv) z = (e > f) ? e : f; // => 10 "if e > f return e, else return f." // Increment and decrement operators: - char *s = "iLoveC"; + char *s = "ILoveC"; int j = 0; s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. j = 0; @@ -321,7 +321,7 @@ int main (int argc, char** argv) break; default: // if `some_integral_expression` didn't match any of the labels - fputs("error!\n", stderr); + fputs("Error!\n", stderr); exit(-1); break; } @@ -497,7 +497,7 @@ int add_two_ints(int x1, int x2) /* Functions are call by value. When a function is called, the arguments passed to -≈the function are copies of the original arguments (except arrays). Anything you +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. @@ -726,7 +726,7 @@ Header files are an important part of c as they allow for the connection of c source files and can simplify code and definitions by seperating them into seperate files. -Header files are syntaxtically similar to c source files but reside in ".h" +Header files are syntactically similar to c source files but reside in ".h" files. They can be included in your c source file by using the precompiler command #include "example.h", given that example.h exists in the same directory as the c file. -- cgit v1.2.3 From 5556d6e839796e06179afec99443bf0a63a23afa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leo=20B=C3=A4rring?= Date: Sat, 26 Dec 2015 20:15:51 +0100 Subject: changed code output to as stated in comments The comments state that Foo::Bar::inc in the package variable example should increase $Foo::Bar::n and then print it. This did not happen, as `say ++$n;` was placed outside the block of the sub Foo::Bar::inc. The commit puts `say ++$n;` inside the block of Foo::Bar::inc. --- perl6.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1829f964..1457999a 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -803,9 +803,8 @@ module Foo::Bar { my sub unavailable { # `my sub` is the default say "Can't access me from outside, I'm my !"; } + say ++$n; # increment the package variable and output its value } - - say ++$n; # lexically-scoped variables are still available } say $Foo::Bar::n; #=> 1 Foo::Bar::inc; #=> 2 -- cgit v1.2.3 From e31dc8b5a7937d25a681747d05b6227d63849c6d Mon Sep 17 00:00:00 2001 From: Owen Rodda Date: Sun, 27 Dec 2015 16:29:52 -0500 Subject: Fix #2040 --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1829f964..323bc0b3 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -103,7 +103,7 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional - say "I might return `(Any)` (Perl's "null"-like value) if I don't have + say "I might return `(Any)` (Perl's 'null'-like value) if I don't have an argument passed, or I'll return my argument"; $arg; } -- cgit v1.2.3 From 4a3538d60c156cf82598dfd06d2ae4f7e0c4404f Mon Sep 17 00:00:00 2001 From: Pranit Bauva Date: Mon, 28 Dec 2015 21:43:09 +0530 Subject: Add different array declaration syntax --- julia.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/julia.html.markdown b/julia.html.markdown index ef3ea244..2810555e 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -151,12 +151,16 @@ a = Int64[] # => 0-element Int64 Array # 1-dimensional array literals can be written with comma-separated values. b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] +b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6] b[1] # => 4 b[end] # => 6 # 2-dimentional arrays use space-separated values and semicolon-separated rows. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] +# Arrays of a particular Type +b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6] + # Add stuff to the end of a list with push! and append! push!(a,1) # => [1] push!(a,2) # => [1,2] -- cgit v1.2.3 From 6749790c8d08aa5aaa06fd0501fd6bdd012ee29b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 17:11:00 -0500 Subject: Many edits --- solidity.html.markdown | 739 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 499 insertions(+), 240 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7f925918..a6620986 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -5,134 +5,194 @@ contributors: - ["Nemil Dalal", "https://www.nemil.com"] --- -Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. +Solidity lets you program on [Ethereum](https://www.ethereum.org/), a +blockchain-based virtual machine that allows the creation and +computation of smart contracts, without needing centralized or trusted parties. -Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. +Solidity is a statically typed, contract programming language that has +similarities to Javascript and C. Like objects in OOP, each contract contains +state variables, functions, and common data types. Contract-specific features +include modifier (guard) clauses, event notifiers for listeners, and custom +global variables. -As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. +Some Ethereum contract examples include crowdfunding, voting, and blind auctions. + +As Solidity and Ethereum are under active development, experimental or beta +features are explicitly marked, and subject to change. Pull requests welcome. ```javascript -// Let's start with a simple Bank contract, before diving into to the key components of the language -// This bank has three main capabilities: -// - deposit -// - withdrawal -// - check balance +// First, a simple Bank contract +// Allows deposits, withdrawals, and balance checks -// ** START EXAMPLE ** -// Start with a Natspec comment (the three slashes) that can be used -// for documentation - and as descriptive data for UI elements -/// @title A simple deposit/withdrawal bank built on Bitcoin - -// All contracts are declared and named (in CamelCase) -// They are similar to 'class' in other languages (and allow capabilities like inheritance) -contract AcmeBank { - // Declare state variables outside a function, - // these are persistent throughout the life of the contract - - // a dictionary that maps addresses to balances - // the private means that other contracts can't see balances - // but the data is still available to all other parties on the - // blockchain +// simple_bank.sol (note .sol extension) +/* **** START EXAMPLE **** */ + +// Start with Natspec comment (the three slashes) +// used for documentation - and as descriptive data for UI elements/actions + +/// @title SimpleBank +/// @author nemild + +/* 'contract' has similarities to 'class' in other languages (class variables, +inheritance, etc.) */ +contract SimpleBank { // CamelCase + // Declare state variables outside function, persist through life of contract + + // dictionary that maps addresses to balances mapping (address => uint) private balances; - // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable) + // "private" means that other contracts can't directly query balances + // but data is still viewable to other parties on blockchain + address public owner; + // 'public' makes externally readable (not writeable) by users or contracts - // Constructor, can receive one or many variables here + // Events - publicize actions to external listeners + event DepositMade(address accountAddress, uint amount); + + // Constructor, can receive one or many variables here; only one allowed function AcmeBank() { - // msg is a default variable that provides both the - // contract messager's address and amount - owner = msg.sender; // msg.sender refers to the address of the contract creator + // msg provides contract messager's address and amount + // msg.sender is contract caller (address of contract creator) + owner = msg.sender; } - function deposit(uint balance) public returns (uint) { - balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable + /// @notice Deposit ether into bank + /// @return The balance of the user after the deposit is made + function deposit() public returns (uint) { + balances[msg.sender] += msg.value; + // no "this." or "self." required with state variable + // all values initialized to 0 by default + + DepositMade(msg.sender, msg.value); // fire event - return balances[msg.sender]; // msg.sender refers to the contract caller + return balances[msg.sender]; } - function withdraw(uint withdrawAmount) public returns (uint remainingBalance) { - if(balances[msg.sender] >= withdrawAmount) { - balances[msg.sender] -= withdrawAmount; + /// @notice Withdraw ether from bank + /// @dev This does not return any excess ether sent to it + /// @param withdrawAmount amount you want to withdraw + /// @return The balance remaining for the user + function withdraw(uint withdrawAmount) public returns (uint remainingBal) { + if(balances[msg.sender] >= withdrawAmount) { + balances[msg.sender] -= withdrawAmount; if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; + balances[msg.sender] += withdrawAmount; // to be safe } - return balances[msg.sender]; + return balances[msg.sender]; } } - // The 'constant' prevents the function from editing state variables + /// @notice Get balance + /// @return The balance of the user + // 'constant' prevents function from editing state variables; + // allows function to run locally/off blockchain function balance() constant returns (uint) { - return balances[msg.sender]; + return balances[msg.sender]; } - // Fallback function - // The fallback function is called if none of the other functions matches the given function identifier. - // Typically, called when invalid data is sent to the contract or ether without data. - // Added so that ether sent to this contract is reverted if the contract fails - // otherwise, the sender loses their money; you should add this in most contracts - function () { throw; } + // Fallback function - Called if other functions don't match call or + // sent ether without data + // Typically, called when invalid data is sent + // Added so ether sent to this contract is reverted if the contract fails + // otherwise, the sender's money is transferred to contract + function () { + throw; // throw reverts state to before call + } } // ** END EXAMPLE ** -// Now let's go through the basics of Solidity +// Now, the basics of Solidity // 1. DATA TYPES AND ASSOCIATED METHODS -// uint is the data type typically used for currency (there are no doubles -// or floats) and for dates +// uint used for currency amount (there are no doubles +// or floats) and for dates (in unix time) uint x; -// with 'constant', the compiler replaces each occurrence with the actual value // int of 256 bits, cannot be changed after instantiation int constant a = 8; + +// with 'constant', compiler replaces each occurrence with actual value int256 constant a = 8; // same effect as line above, here the 256 is explicit uint constant VERSION_ID = 0x123A1; // A hex constant -// For both int and uint, you can explicitly set space in steps of 8 -// e.g., int8, int16 +// Be careful that you don't overflow, and protect against attacks that do + +// For int and uint, can explicitly set space in steps of 8 up to 256 +// e.g., int8, int16, int24 uint8 b; int64 c; uint248 e; +// No random functions built in, use other contracts for randomness + // Type casting int x = int(b); bool b = true; // or do 'var b = true;' for inferred typing -// Addresses - holds 20 byte/160 bit Ethereum addresses to another contract -// ('Contract Account)') or person/external entity ('External Account') -address public owner; // Add 'public' field to indicate publicly/externally accessible, a getter is automatically created, but NOT a setter +// Addresses - holds 20 byte/160 bit Ethereum addresses +// No arithmetic allowed +address public owner; -// All addresses can be sent ether in the following way: +// Types of accounts: +// Contract account: address set on create (func of creator address, num transactions sent) +// External Account: (person/external entity): address created from public key + +// Add 'public' field to indicate publicly/externally accessible +// a getter is automatically created, but NOT a setter + +// All addresses can be sent ether owner.send(SOME_BALANCE); // returns false on failure -owner.balance; // the balance of the owner +if (owner.send) {} // typically wrap in 'if', as contract addresses have +// functions have executed on send and can fail + +// can override send by defining your own -// Bytes are provided from 1 to 32 +// Can check balance +owner.balance; // the balance of the owner (user or contract) + + +// Bytes available from 1 to 32 byte a; // byte is same as bytes1 -bytes32 b; +bytes2 b; +bytes32 c; + +// Dynamically sized bytes +bytes m; // A special array, same as byte[] array (but packed tightly) +// More expensive than byte1-byte32, so use those when possible -// Dynamically sized -bytes m; // A special array, same as byte[] (but packed tightly) // same as bytes, but does not allow length or index access (for now) -string n = 'hello'; +string n = "hello"; // stored in UTF8, note double quotes, not single +// string utility functions to be added in future +// prefer bytes32/bytes, as UTF8 uses more storage -// Type inference +// Type inferrence // var does inferred typing based on first assignment, // can't be used in functions parameters var a = true; -// there are edge cases where inference leads to a value being set (e.g., an uint 8) -// that is different from what the user wanted (uint16), so use carefully +// use carefully, inference may provide wrong type +// e.g., an int8, when a counter needs to be int16 + +// var can be used to assign function to variable +function a(uint x) returns (uint) { + return x * 2; +} +var f = a; +f(22); // call // by default, all values are set to 0 on instantiation // Delete can be called on most types -// (it does NOT destroy the value, but rather sets the value to 0 by assignment) +// (does NOT destroy value, but sets value to 0, the initial value) uint x = 5; -delete x; // x is now 0 + + +// Destructuring/Tuples +(x, y) = (2, 7); // assign/swap multiple value // 2. DATA STRUCTURES @@ -142,74 +202,97 @@ bytes32[] names; // dynamic array uint newLength = names.push("John"); // adding returns new length of the array // Length names.length; // get length -names.length = 1; // lengths can also be set, unlike many other languages +names.length = 1; // lengths can be set (for dynamic arrays in storage only) + +// multidimensional array +uint x[][5]; // arr with 5 dynamic array elements (opp order of most languages) // Dictionaries (any type to any other type) mapping (string => uint) public balances; -balances["john"] = 1; -console.log(balances[jill]); // is 0, all non-set key values return zeroes -// The 'public' lets you do the following from another contract -contractName.balances("john"); // returns 1 -// The 'public' keyword here created a getter (but not setter) that behaves like the following: +balances["charles"] = 1; +console.log(balances["ada"]); // is 0, all non-set key values return zeroes +// 'public' allows following from another contract +contractName.balances("claude"); // returns 1 +// 'public' created a getter (but not setter) like the following: function balances(address _account) returns (uint balance) { - return balances[_account]; + return balances[_account]; } +// Nested mappings +mapping (address => mapping (address => uint) balances) public custodians; + // To delete delete balances["John"]; -delete balances; // deletes all elements +delete balances; // sets all elements to 0 -// Unlike languages like Javascript, you cannot iterate through all elements in -// a map, without knowing the source keys +// Unlike other languages, CANNOT iterate through all elements in +// mapping, without knowing source keys - can build data structure +// on top to do this // Structs and enums - struct Bank { // note the capital - address owner; - uint balance; - } +struct Bank { + address owner; + uint balance; +} Bank b = Bank({ - owner: msg.sender, - balance: 5 + owner: msg.sender, + balance: 5 }); -delete b; // set all variables in struct to 0, except any mappings +// or +Bank c = Bank(msg.sender, 5); + +c.amount = 5; // set to new value +delete b; +// sets to initial value, set all variables in struct to 0, except mappings // Enums -enum State { Created, Locked, Inactive }; +enum State { Created, Locked, Inactive }; // often used for state machine State public state; // Declare variable from enum state = State.Created; // enums can be explicitly converted to ints +uint createdState = uint(State.Created); // 0 -// Data locations: Memory vs. storage - all complex types (arrays, structs) have a data location +// Data locations: Memory vs. storage vs. stack - all complex types (arrays, +// structs) have a data location // 'memory' does not persist, 'storage' does -// Default is 'storage' for local and state variables; 'memory' for function parameters +// Default is 'storage' for local and state variables; 'memory' for func params +// stack holds small local variables + +// for most types, can explicitly set which data location to use + +// 3. Simple operators +// Comparisons, bit operators and arithmetic operators are provided +// exponentiation: ** +// exclusive or: ^ +// bitwise negation: ~ -// 3. Variables of note + +// 4. Global Variables of note // ** this ** -this; // the address of the current contract -// 'balance' often used at the end of a contracts life to send the -// remaining balance to a party +this; // address of contract +// often used at end of contract life to send remaining balance to party this.balance; -this.someFunction(); // calls a function externally (via a message call, not via an internal jump) +this.someFunction(); // calls func externally via call, not via internal jump -// ** msg - The current message received by the contract ** ** -msg.sender; // address, The address of the sender -msg.value; // uint, The amount of gas provided to this contract in wei +// ** msg - Current message received by the contract ** ** +msg.sender; // address of sender +msg.value; // amount of gas provided to this contract in wei msg.data; // bytes, complete call data msg.gas; // remaining gas // ** tx - This transaction ** -tx.origin; // address, sender of the transaction -tx.gasprice; // uint, gas price of the transaction - -// ** block - Information about the current block ** -now // uint, current time, alias for block.timestamp -block.number; // uint, current block number -block.difficulty; // uint, current block difficulty -block.blockhash(1); // returns bytes32, only provides for most recent 256 blocks +tx.origin; // address of sender of the transaction +tx.gasprice; // gas price of the transaction + +// ** block - Information about current block ** +now // current time (approximately), alias for block.timestamp (uses Unix time) +block.number; // current block number +block.difficulty; // current block difficulty +block.blockhash(1); // returns bytes32, only works for most recent 256 blocks block.gasLimit(); -// ** storage - A persistent storage hash (does not need to be declared) ** +// ** storage - Persistent storage hash ** storage['abc'] = 'def'; // maps 256 bit words to 256 bit words @@ -217,55 +300,61 @@ storage['abc'] = 'def'; // maps 256 bit words to 256 bit words // A. Functions // Simple function function increment(uint x) returns (uint) { - x += 1; - return x; + x += 1; + return x; } -// Functions can return many arguments, and by specifying the returned arguments -// you don't need to explicitly return +// Functions can return many arguments, and by specifying returned arguments +// name don't need to explicitly return function increment(uint x, uint y) returns (uint x, uint y) { - x += 1; - y += 1; + x += 1; + y += 1; } -// This function would have been called like this, and assigned to a tuple +// Call previous functon uint (a,b) = increment(1,1); -// The 'constant' indicates and ensures that a function does not/cannot change the persistent variables -// Constant function execute locally, not on the blockchain +// 'constant' indicates that function does not/cannot change persistent vars +// Constant function execute locally, not on blockchain uint y; function increment(uint x) constant returns (uint x) { - x += 1; - y += 1; // this line would fail - // as y is a state variable, and can't be changed in a constant function + x += 1; + y += 1; // this line would fail + // y is a state variable, and can't be changed in a constant function } -// There are a few 'function visibility specifiers' that can be placed where 'constant' -// is, which include: -// internal (can only be called by an internal function, not one external to the contract) -// public - visible externally and internally +// 'Function Visibility specifiers' +// These can be placed where 'constant' is, including: +// public - visible externally and internally (default) +// external // private - only visible in the current contract +// internal - only visible in current contract, and those deriving from it -// Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable +// Functions hoisted - and can assign a function to a variable function a() { - var z = b; - b(); + var z = b; + b(); } function b() { } + +// Prefer loops to recursion (max call stack depth is 1024) + // B. Events -// Events are an easy way to notify external listeners that something changed -// You typically declare them after your contract parameters -event Sent(address from, address to, uint amount); +// Events are notify external parties; easy to search and +// access events from outside blockchain (with lightweight clients) +// typically declare after contract parameters -// You then call it in a function, when you want to trigger it -sent(from, to, amount); +// Declare +event Sent(address from, address to, uint amount); // note capital first letter -// For an external party (a contract or external entity), to watch -// for an event, you write the following: +// Call +Sent(from, to, amount); + +// For an external party (a contract or external entity), to watch: Coin.Sent().watch({}, '', function(error, result) { if (!error) { console.log("Coin transfer: " + result.args.amount + @@ -276,195 +365,356 @@ Coin.Sent().watch({}, '', function(error, result) { "Receiver: " + Coin.balances.call(result.args.to)); } } -// This is a common paradigm for one contract to depend on another (e.g., a -// contract that depends on the current exchange rate provided by another -// contract) +// Common paradigm for one contract to depend on another (e.g., a +// contract that depends on current exchange rate provided by another) // C. Modifiers -// Modifiers let you validate inputs to functions such as a minimal balance or user authentication -// It's similar to a guard clause in other languages +// Modifiers validate inputs to functions such as minimal balance or user auth; +// similar to guard clause in other languages -// The '_' (underscore) must be included as the last line in the function body, and is an indicator that the +// '_' (underscore) often included as last line in body, and indicates // function being called should be placed there modifier onlyAfter(uint _time) { if (now <= _time) throw; _ } modifier onlyOwner { if (msg.sender == owner) _ } +// commonly used with state machines +modifier onlyIfState (State currState) { if (currState != State.A) _ } -// You can then append it right after the function declaration +// Append right after function declaration function changeOwner(newOwner) onlyAfter(someTime) onlyOwner() +onlyIfState(State.A) { - owner = newOwner; + owner = newOwner; } +// underscore can be included before end of body, +// but explicitly returning will skip, so use carefully +modifier checkValue(uint amount) { + _ + if (msg.value > amount) { + msg.sender.send(amount - msg.value); + } +} -// 5. BRANCHING AND LOOPS -// All basic logic blocks work - including if/else, for, while, break, continue, return -// Unlike other languages, the 'switch' statement is NOT provided +// 6. BRANCHING AND LOOPS -// Syntax is the same as javascript, but there is no type conversion from -// non-boolean to boolean, so comparison operators must be used to get the boolean value +// All basic logic blocks work - including if/else, for, while, break, continue +// return - but no switch +// Syntax same as javascript, but no type conversion from non-boolean +// to boolean (comparison operators must be used to get the boolean val) -// 6. OBJECTS/CONTRACTS -// A. Calling an external contract +// 7. OBJECTS/CONTRACTS + +// A. Calling external contract contract infoFeed { - function info() returns (uint ret) { return 42; } + function info() returns (uint ret) { return 42; } } contract Consumer { - InfoFeed feed; // create a variable that will point to a contract on the blockchain - - // Set feed to an existing contract - function setFeed(address addr) { - // Link to the contract by creating on the address - feed = InfoFeed(addr); - } - - // Set feed based to a new instance of the contract - function createNewFeed() { - feed = new InfoFeed(); - } - - function callFeed() { - // T final parentheses call the contract, optionally adding - // custom value or gas numbers - feed.info.value(10).gas(800)(); - } + InfoFeed feed; // points to contract on blockchain + + // Set feed to existing contract instance + function setFeed(address addr) { + // automatically cast, be careful; constructor is not called + feed = InfoFeed(addr); + } + + // Set feed to new instance of contract + function createNewFeed() { + feed = new InfoFeed(); // constructor called + } + + function callFeed() { + // final parentheses call contract, can optionally add + // custom ether value or gas + feed.info.value(10).gas(800)(); + } } // B. Inheritance -// Order matters, last inherited contract (i.e., 'def') can override parts of the previously -// inherited contracts -contact MyContract is abc, def("a custom argument to def") { +// Order matters, last inherited contract (i.e., 'def') can override parts of +// previously inherited contracts +contract MyContract is abc, def("a custom argument to def") { // Override function - - function z() { - if (msg.sender == owner) { - def.z(); // call overridden function + function z() { + if (msg.sender == owner) { + def.z(); // call overridden function from def + super.z(); // call immediate parent overriden function + } } - } +} - }; +// abstract function +function someAbstractFunction(uint x); +// cannot be compiled, so used in base/abstract contracts +// that are then implemented // C. Import import "filename"; import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; -// Importing is under active development and will change -// Importing cannot currently be done at the command line - - -// 7. CONTRACT DESIGN PATTERNS +// Importing under active development +// Cannot currently be done at command line -// A. Obfuscation -// Remember that all variables are publicly viewable on the blockchain, so -// anything that needs some privacy needs to be obfuscated (e.g., hashed) +// 8. OTHER KEYWORDS -// B. Throwing +// A. Throwing // Throwing -throw; // throwing is easily done, and reverts unused money to the sender -// You can't currently catch +throw; // reverts unused money to sender, state is reverted +// Can't currently catch -// A common design pattern is: +// Common design pattern is: if (!addr.send(123)) { - throw; + throw; } -// C. Suicide -// Suicide -suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) +// B. Selfdestruct +// selfdestruct current contract, sending funds to address (often creator) +selfdestruct(SOME_ADDRESS); + +// removes storage/code from current/future blocks +// helps thin clients, but previous data persists in blockchain -// This is a common contract pattern that lets the owner end the contract, and receive remaining funds +// Common pattern, lets owner end the contract and receive remaining funds function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } + if(msg.sender == creator) { // Only let the contract creator do this + selfdestruct(creator); // Makes contract inactive, returns funds + } } -// D. Storage optimization -// Reading and writing can be expensive, as data needs to be stored in the -// blockchain forever - this encourages smart ways to use memory (eventually, -// compilation may better handle this, but for now there are benefits to -// planning your data structures) +// May want to deactivate contract manually, rather than selfdestruct +// (ether sent to selfdestructed contract is lost) + + +// 9. CONTRACT DESIGN NOTES + +// A. Obfuscation +// Remember all variables are publicly viewable on blockchain, so +// anything that needs privacy needs to be obfuscated (e.g., hashed) + +// Steps: 1. Commit to something, 2. Reveal commitment +sha3("some_bid_amount", "some secret"); // commit + +// call contract's reveal function showing bid plus secret that hashes to SHA3 +reveal(100, "mySecret"); + +// B. Storage optimization +// Writing to blockchain can be expensive, as data stored forever encourages +// smart ways to use memory (eventually, compilation will be better, but for now +// benefits to planning data structures - and storing min amount in blockchain) + +// Cost can often be high for items like multidimensional arrays +// (cost is for storing data - not declaring unfilled variables) + +// C. Cannot restrict human or computer from reading contents of +// transaction or transaction's state + +// When 'private' specified, indicating that other *contracts* can't read +// the data directly - any other party can still read the data in blockchain +// D. All data to start of time is stored in blockchain, so +// anyone can observe all previous data and changes -// *** EXAMPLE: Let's do a more complex example *** +// E. Cron +// Contracts must be manually called to handle time-based scheduling; can create +// external code to do, or provide incentives (ether) for others to do for you +// F. State machines +// see example below for State enum and inState modifier + +// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) *** // ** START EXAMPLE ** -// [TODO: Decide what a more complex example looks like, needs a few characteristics: -// - has a 'constant' state variable -// - has a state machine (and uses modifier) -// - sends money to an address -// - gets information from another contract (we'll show code for both contracts) -// - Shows inheritance -// - show variables being passed in on instantiation (and guard code to throw if variables not provided) -// - Shows the swapping out of a contract address -// Ideas: -// - crowdfunding? -// - Peer to peer insurance -// ] - // It's good practice to have a remove function, which disables this - // contract - but does mean that users have to trust the owner - // For a decentralized bank without a trusted part - function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } + +// CrowdFunder.sol + +/// @title CrowdFunder +/// @author nemild +contract CrowdFunder { + // Variables set on create by creator + address public creator; + address public fundRecipient; // creator may be different than recipient + uint public minimumToRaise; // required to tip, else everyone gets refund + string campaignUrl; + + // Data structures + enum State { + Fundraising, + ExpiredRefundPending, + Successful, + ExpiredRefundComplete + } + struct Contribution { + uint amount; + address contributor; } -// *** END EXAMPLE *** + // State variables + State public state = State.Fundraising; // initialize on create + uint public totalRaised; + uint public raiseBy; + Contribution[] contributions; + + event fundingReceived(address addr, uint amount, uint currentTotal); + event allRefundsSent(); + event winnerPaid(address winnerAddress); + + modifier inState(State _state) { + if (state != _state) throw; + _ + } -// 7. NATIVE FUNCTIONS + modifier isCreator() { + if (msg.sender != creator) throw; + _ + } + + modifier atEndOfLifecycle() { + if(state != State.ExpiredRefundComplete && state != State.Successful) { + throw; + } + } + + function CrowdFunder( + uint timeInHoursForFundraising, + string _campaignUrl, + address _fundRecipient, + uint _minimumToRaise) + { + creator = msg.sender; + fundRecipient = _fundRecipient; + campaignUrl = _campaignUrl; + minimumToRaise = _minimumToRaise; + raiseBy = now + (timeInHoursForFundraising * 1 hours); + } + + function contribute() + public + inState(State.Fundraising) + { + contributions.push( + Contribution({ + amount: msg.value, + contributor: msg.sender + }) // use array, so can iterate + ); + totalRaised += msg.value; + + fundingReceived(msg.sender, msg.value, totalRaised); + + checkIfFundingCompleteOrExpired(); + } + + function checkIfFundingCompleteOrExpired() { + if (totalRaised > minimumToRaise) { + state = State.Successful; + payOut(); + + // could incentivize sender who initiated state change here + } else if ( now > raiseBy ) { + state = State.ExpiredRefundPending; + refundAll(); + } + } + + function payOut() + public + inState(State.Successful) + { + if(!fundRecipient.send(this.balance)) { + throw; + } + + winnerPaid(fundRecipient); + } + + function refundAll() + public + inState(State.ExpiredRefundPending) + { + uint length = contributions.length; + for (uint i = 0; i < length; i++) { + if(!contributions[i].contributor.send(contributions[i].amount)) { + throw; + } + } + + allRefundsSent(); + state = State.ExpiredRefundComplete; + } + + function removeContract() + public + isCreator() + atEndOfLifecycle() + { + selfdestruct(msg.sender); + } + + function () { throw; } +} +// ** END EXAMPLE ** + +// 10. OTHER NATIVE FUNCTIONS // Currency units -// By default, currency is defined using wei, the smallest unit of Ether +// Currency is defined using wei, smallest unit of Ether uint minAmount = 1 wei; -uint a = 1 finney; // 1 ether = 1000 finney -// There are a number of other units, see: http://ether.fund/tool/converter +uint a = 1 finney; // 1 ether == 1000 finney +// Other units, see: http://ether.fund/tool/converter // Time units 1 == 1 second 1 minutes == 60 seconds - -// You typically multiply a variable times the unit, as these units are not -// directly stored in a variable +// Can multiply a variable times unit, as units are not stored in a variable uint x = 5; (x * 1 days); // 5 days -// Be careful about leap seconds and leap years when using equality statements for time (instead, prefer greater than/less than) +// Careful about leap seconds/years with equality statements for time +// (instead, prefer greater than/less than) // Cryptography -// All strings passed are concatenated before the hash is run +// All strings passed are concatenated before hash action sha3("ab", "cd"); ripemd160("abc"); sha256("def"); +11. LOW LEVEL FUNCTIONS +// call - low level, not often used, does not provide type safety +successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); -// 8. COMMON MISTAKES/MISCONCEPTIONS -// A few common mistakes and misconceptions: +// callcode - Code at target address executed in *context* of calling contract +// provides library functionality +someContractAddress.callcode('function_name'); -// A. You cannot restrict a human or computer from reading the content of -// your transaction or a transaction's state +// 12. STYLE NOTES +// Based on Python's PEP8 style guide -// All data to the start of time is stored in the blockchain, so you and -// anyone can observe all previous data stats +// 4 spaces for indentation +// Two lines separate contract declarations (and other top level declarations) +// Avoid extraneous spaces in parentheses +// Can omit curly braces for one line statement (if, for, etc) +// else should be placed on own line -// When you don't specify public on a variable, you are indicating that other *contracts* can't -// read the data - but any person can still read the data +// 13. NATSPEC comments - used for documentation, commenting, and external UIs +// Contract natspec - always above contract definition +/// @title Contract title +/// @author Author name -// TODO +// Function natspec +/// @notice information about what function does; shown when function to execute +/// @dev Function documentation for developer - -// 9. STYLE NOTES -// Use 4 spaces for indentation -// (Python's PEP8 is used as the baseline style guide, including its general philosophy) +// Function parameter/return value natspec +/// @param someParam Some description of what the param does +/// @return Description of the return value ``` ## Additional resources @@ -472,6 +722,8 @@ sha256("def"); - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) +- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) @@ -481,5 +733,12 @@ sha256("def"); ## Information purposefully excluded - Libraries +- [Call keyword](http://solidity.readthedocs.org/en/latest/types.html) + +## Style +- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) + +## Future To Dos +- New keywords: protected, inheritable Feel free to send a pull request with any edits - or email nemild -/at-/ gmail -- cgit v1.2.3 From 8f9f9e53e825b346c49139769b8bbfd08d0bed4e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 17:13:20 -0500 Subject: Spacing --- solidity.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index a6620986..7de92fce 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -463,6 +463,7 @@ import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; // Importing under active development // Cannot currently be done at command line + // 8. OTHER KEYWORDS // A. Throwing @@ -529,6 +530,7 @@ reveal(100, "mySecret"); // F. State machines // see example below for State enum and inState modifier + // *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) *** // ** START EXAMPLE ** @@ -661,6 +663,7 @@ contract CrowdFunder { } // ** END EXAMPLE ** + // 10. OTHER NATIVE FUNCTIONS // Currency units @@ -686,7 +689,8 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); -11. LOW LEVEL FUNCTIONS + +// 11. LOW LEVEL FUNCTIONS // call - low level, not often used, does not provide type safety successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); @@ -694,6 +698,7 @@ successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); // provides library functionality someContractAddress.callcode('function_name'); + // 12. STYLE NOTES // Based on Python's PEP8 style guide @@ -703,6 +708,7 @@ someContractAddress.callcode('function_name'); // Can omit curly braces for one line statement (if, for, etc) // else should be placed on own line + // 13. NATSPEC comments - used for documentation, commenting, and external UIs // Contract natspec - always above contract definition /// @title Contract title -- cgit v1.2.3 From 43138aef5cc6a89ec0c02db03cec61ab902acb97 Mon Sep 17 00:00:00 2001 From: ethers Date: Mon, 28 Dec 2015 16:36:48 -0800 Subject: fixes in withdraw() and msg --- solidity.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7de92fce..146d6e83 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -7,7 +7,7 @@ contributors: Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and -computation of smart contracts, without needing centralized or trusted parties. +execution of smart contracts, without needing centralized or trusted parties. Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like objects in OOP, each contract contains @@ -52,7 +52,7 @@ contract SimpleBank { // CamelCase // Constructor, can receive one or many variables here; only one allowed function AcmeBank() { - // msg provides contract messager's address and amount + // msg provides details about the message that's sent to the contract // msg.sender is contract caller (address of contract creator) owner = msg.sender; } @@ -77,12 +77,12 @@ contract SimpleBank { // CamelCase if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; // to be safe + if (!msg.sender.send(withdrawAmount)) { + balances[msg.sender] += withdrawAmount; // to be safe + } } - - return balances[msg.sender]; - } + + return balances[msg.sender]; } /// @notice Get balance @@ -277,7 +277,7 @@ this.someFunction(); // calls func externally via call, not via internal jump // ** msg - Current message received by the contract ** ** msg.sender; // address of sender -msg.value; // amount of gas provided to this contract in wei +msg.value; // amount of ether provided to this contract in wei msg.data; // bytes, complete call data msg.gas; // remaining gas -- cgit v1.2.3 From 65cba2b1f5405d53e498bfa96a0e407423dd9a4e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 21:53:37 -0500 Subject: Fixed mapping --- solidity.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7de92fce..5b632c11 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -219,7 +219,7 @@ function balances(address _account) returns (uint balance) { } // Nested mappings -mapping (address => mapping (address => uint) balances) public custodians; +mapping (address => mapping (address => uint)) public custodians; // To delete delete balances["John"]; -- cgit v1.2.3 From ba3d5a6feb4a340c43b55b75516fed1d78fad9fb Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 21:58:31 -0500 Subject: Added Joseph Chow as contributor --- solidity.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2d653bf9..b73ca0e5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -2,7 +2,8 @@ language: Solidity filename: learnSolidity.sol contributors: - - ["Nemil Dalal", "https://www.nemil.com"] + - ["Nemil Dalal", "https://www.nemil.com"] + - ["Joseph Chow", ""] --- Solidity lets you program on [Ethereum](https://www.ethereum.org/), a @@ -81,7 +82,7 @@ contract SimpleBank { // CamelCase balances[msg.sender] += withdrawAmount; // to be safe } } - + return balances[msg.sender]; } -- cgit v1.2.3 From 58ebc87f5f4114c3610633a7cd9c4264647b2448 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 22:29:19 -0500 Subject: Minor edits --- solidity.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index b73ca0e5..5946c1f5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -79,7 +79,9 @@ contract SimpleBank { // CamelCase balances[msg.sender] -= withdrawAmount; if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; // to be safe + // to be safe, may be sending to contract that + // has overridden 'send' which may then fail + balances[msg.sender] += withdrawAmount; } } @@ -710,7 +712,9 @@ someContractAddress.callcode('function_name'); // else should be placed on own line -// 13. NATSPEC comments - used for documentation, commenting, and external UIs +// 13. NATSPEC COMENTS +// used for documentation, commenting, and external UIs + // Contract natspec - always above contract definition /// @title Contract title /// @author Author name @@ -740,7 +744,6 @@ someContractAddress.callcode('function_name'); ## Information purposefully excluded - Libraries -- [Call keyword](http://solidity.readthedocs.org/en/latest/types.html) ## Style - Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) -- cgit v1.2.3 From bdd8a8b0c87d58332f39facc60d6ab7d576764df Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 22:31:48 -0500 Subject: Wording --- solidity.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 5946c1f5..ebc58491 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -500,8 +500,8 @@ function remove() { // 9. CONTRACT DESIGN NOTES // A. Obfuscation -// Remember all variables are publicly viewable on blockchain, so -// anything that needs privacy needs to be obfuscated (e.g., hashed) +// All variables are publicly viewable on blockchain, so anything +// that should be totally private needs to be obfuscated (e.g., hashed w/secret) // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit -- cgit v1.2.3 From 24740321f478c25bb1dc651f6c95e11525a16781 Mon Sep 17 00:00:00 2001 From: ethers Date: Mon, 28 Dec 2015 23:45:58 -0800 Subject: update links to docs and Gitter --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index ebc58491..911aca92 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -729,17 +729,17 @@ someContractAddress.callcode('function_name'); ``` ## Additional resources -- [Solidity Docs](https://ethereum.github.io/solidity/docs/home/) +- [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) -- [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +- [Gitter Chat room](https://gitter.im/ethereum/solidity) - [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) - Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) -- [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) +- [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) ## Information purposefully excluded -- cgit v1.2.3 From 00d4fa09de191b9580dd534b8b3e6e7a297fb8d7 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Tue, 29 Dec 2015 16:59:19 +0800 Subject: Fetch lsp typo fix from upstream --- zh-cn/tmux-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 00bf35f3..64781346 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -39,7 +39,7 @@ lang: zh-cn lsp # 列出窗格 -a # 列出所有窗格 -s # 列出会话中的所有窗格 - -t # List app panes in target + -t # 列出 target 中的所有窗格 kill-window # 关闭当前窗口 -t "#" # 关闭指定的窗口 -- cgit v1.2.3 From bf609a3a0f0ce84faa617bc5c6a51b56f3571f4f Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Tue, 29 Dec 2015 17:14:18 +0800 Subject: Update tmux home page. Tmux has moved to github. --- tmux.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 868302a8..6763a781 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -240,7 +240,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | ### References -[Tmux | Home](http://tmux.sourceforge.net) +[Tmux | Home](http://tmux.github.io) [Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) -- cgit v1.2.3 From fc528c92ddbdca1d0cb3a5c8f3ad477fbc115ad9 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 10:59:01 -0500 Subject: Cleaned up data types --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index ebc58491..d84b6a68 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -117,12 +117,10 @@ uint x; // int of 256 bits, cannot be changed after instantiation int constant a = 8; - -// with 'constant', compiler replaces each occurrence with actual value int256 constant a = 8; // same effect as line above, here the 256 is explicit uint constant VERSION_ID = 0x123A1; // A hex constant +// with 'constant', compiler replaces each occurrence with actual value -// Be careful that you don't overflow, and protect against attacks that do // For int and uint, can explicitly set space in steps of 8 up to 256 // e.g., int8, int16, int24 @@ -130,6 +128,8 @@ uint8 b; int64 c; uint248 e; +// Be careful that you don't overflow, and protect against attacks that do + // No random functions built in, use other contracts for randomness // Type casting -- cgit v1.2.3 From 7e4a42d0b8cec4c0e2a6b90ad261c7755afe1136 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 11:10:39 -0500 Subject: Reorganizing later sections --- solidity.html.markdown | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 8c416be3..6705dde9 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -501,7 +501,7 @@ function remove() { // A. Obfuscation // All variables are publicly viewable on blockchain, so anything -// that should be totally private needs to be obfuscated (e.g., hashed w/secret) +// that is private needs to be obfuscated (e.g., hashed w/secret) // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit @@ -510,27 +510,28 @@ sha3("some_bid_amount", "some secret"); // commit reveal(100, "mySecret"); // B. Storage optimization -// Writing to blockchain can be expensive, as data stored forever encourages +// Writing to blockchain can be expensive, as data stored forever; encourages // smart ways to use memory (eventually, compilation will be better, but for now // benefits to planning data structures - and storing min amount in blockchain) // Cost can often be high for items like multidimensional arrays // (cost is for storing data - not declaring unfilled variables) -// C. Cannot restrict human or computer from reading contents of +// C. Data access in blockchain +// Cannot restrict human or computer from reading contents of // transaction or transaction's state -// When 'private' specified, indicating that other *contracts* can't read -// the data directly - any other party can still read the data in blockchain +// While 'private' prevents other *contracts* from reading data +// directly - any other party can still read data in blockchain -// D. All data to start of time is stored in blockchain, so +// All data to start of time is stored in blockchain, so // anyone can observe all previous data and changes -// E. Cron -// Contracts must be manually called to handle time-based scheduling; can create -// external code to do, or provide incentives (ether) for others to do for you +// D. Cron Job +// Contracts must be manually called to handle time-based scheduling; can create external +// code to regularly ping, or provide incentives (ether) for others to -// F. State machines +// E. State machines // see example below for State enum and inState modifier @@ -705,6 +706,7 @@ someContractAddress.callcode('function_name'); // 12. STYLE NOTES // Based on Python's PEP8 style guide +// Quick summary: // 4 spaces for indentation // Two lines separate contract declarations (and other top level declarations) // Avoid extraneous spaces in parentheses -- cgit v1.2.3 From d97c7be291b6bc3fb1477c30ac96b5b6cc36b9c4 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 13:05:45 -0500 Subject: Minor wording changes, typos --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 6705dde9..71a44b92 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -63,7 +63,7 @@ contract SimpleBank { // CamelCase function deposit() public returns (uint) { balances[msg.sender] += msg.value; // no "this." or "self." required with state variable - // all values initialized to 0 by default + // all values set to data type's initial value by default DepositMade(msg.sender, msg.value); // fire event @@ -289,7 +289,7 @@ tx.origin; // address of sender of the transaction tx.gasprice; // gas price of the transaction // ** block - Information about current block ** -now // current time (approximately), alias for block.timestamp (uses Unix time) +now; // current time (approximately), alias for block.timestamp (uses Unix time) block.number; // current block number block.difficulty; // current block difficulty block.blockhash(1); // returns bytes32, only works for most recent 256 blocks @@ -428,7 +428,7 @@ contract Consumer { // Set feed to new instance of contract function createNewFeed() { - feed = new InfoFeed(); // constructor called + feed = new InfoFeed(); // new instance created; constructor called } function callFeed() { -- cgit v1.2.3 From 8dd19e58eeaed93f4489ae711ef72e79135d8795 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 30 Dec 2015 18:56:24 +0800 Subject: Fetch tmuxinator from upstream --- zh-cn/tmux-cn.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 64781346..540bbf23 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -247,3 +247,5 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) [如何在 tmux 状态栏中显示 CPU / 内存占用百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From 9b8c680a2e2e1238f4130bc589367baf1a62119e Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 30 Dec 2015 19:07:19 +0800 Subject: Update translations. --- zh-cn/tmux-cn.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 540bbf23..3b38ca6b 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -39,7 +39,7 @@ lang: zh-cn lsp # 列出窗格 -a # 列出所有窗格 -s # 列出会话中的所有窗格 - -t # 列出 target 中的所有窗格 + -t "#" # 列出指定窗口中的所有窗格 kill-window # 关闭当前窗口 -t "#" # 关闭指定的窗口 @@ -56,7 +56,7 @@ lang: zh-cn ### 快捷键 -通过“前缀”快捷键,可以控制一个已经连入的tmux会话。 +通过“前缀”快捷键,可以控制一个已经连入的 tmux 会话。 ``` ---------------------------------------------------------------------- @@ -66,7 +66,7 @@ lang: zh-cn ---------------------------------------------------------------------- ? # 列出所有快捷键 - : # 进入tmux的命令提示符 + : # 进入 tmux 的命令提示符 r # 强制重绘当前客户端 c # 创建一个新窗口 @@ -127,7 +127,7 @@ set-option -g status-utf8 on # 命令回滚/历史数量限制 set -g history-limit 2048 -# Index Start +# 从 1 开始编号,而不是从 0 开始 set -g base-index 1 # 启用鼠标 @@ -144,10 +144,10 @@ bind r source-file ~/.tmux.conf # 取消默认的前缀键 C-b unbind C-b -# 设置新的前缀键 +# 设置新的前缀键 ` set-option -g prefix ` -# 再次按下前缀键时,回到之前的窗口 +# 多次按下前缀键时,切换到上一个窗口 bind C-a last-window bind ` last-window @@ -159,7 +159,7 @@ bind F12 set-option -g prefix ` setw -g mode-keys vi set-option -g status-keys vi -# 使用 vim 风格的按键在窗格间移动 +# 使用 Vim 风格的按键在窗格间移动 bind h select-pane -L bind j select-pane -D bind k select-pane -U @@ -238,14 +238,14 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | ### 参考资料 -[Tmux 主页](http://tmux.sourceforge.net) +[Tmux 主页](http://tmux.github.io) [Tmux 手册](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) [Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) -[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文)) -[如何在 tmux 状态栏中显示 CPU / 内存占用百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) +[如何在 tmux 状态栏中显示 CPU / 内存占用的百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) [管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From aed4bbbc36bf28a815d6751cde02b6b025452fb9 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 30 Dec 2015 21:38:18 +0800 Subject: Update Wiki link --- zh-cn/tmux-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 3b38ca6b..390fd4fc 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -242,7 +242,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Tmux 手册](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) -[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) +[FreeBSDChina Wiki](https://wiki.freebsdchina.org/software/t/tmux) [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文)) -- cgit v1.2.3 From 4af768019ced6c179a09180adc2b0fb9adebc1d8 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 30 Dec 2015 21:54:44 +0800 Subject: Add a tmux Chinese tutorial --- zh-cn/tmux-cn.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 390fd4fc..87afa565 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -246,6 +246,8 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文)) +[Tmux 快速教程](http://blog.jeswang.org/blog/2013/06/24/tmux-kuai-su-jiao-cheng) + [如何在 tmux 状态栏中显示 CPU / 内存占用的百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) [管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From 8fdb648cbc691de5ff8f30c7bb5d0c29385a253c Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Thu, 31 Dec 2015 15:51:09 +0800 Subject: Update tmux home page, again. --- tmux.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 6763a781..c9e3db6b 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -7,7 +7,7 @@ filename: LearnTmux.txt --- -[tmux](http://tmux.sourceforge.net) +[tmux](http://tmux.github.io) is a terminal multiplexer: it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background -- cgit v1.2.3 From d56ae11e30ff85a0b8b632506abf4ec1bad1d28e Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Thu, 31 Dec 2015 16:16:02 +0800 Subject: Finish tmux translations. --- zh-cn/tmux-cn.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 87afa565..cf865dce 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -10,9 +10,9 @@ lang: zh-cn --- -[tmux](http://tmux.sourceforge.net)是一款终端复用工具。 +[tmux](http://tmux.github.io)是一款终端复用工具。 在它的帮助下,你可以在同一个控制台上建立、访问并控制多个终端。 -你可以断开与一个tmux终端的连接,此时程序将在后台运行, +你可以断开与一个 tmux 终端的连接,此时程序将在后台运行, 当你需要时,可以随时重新连接到这个终端。 ``` @@ -70,7 +70,7 @@ lang: zh-cn r # 强制重绘当前客户端 c # 创建一个新窗口 - ! # Break the current pane out of the window. + ! # 将当前窗格从窗口中移出,成为为一个新的窗口 % # 将当前窗格分为左右两半 " # 将当前窗格分为上下两半 @@ -93,11 +93,11 @@ lang: zh-cn Left, Right M-1 到 M-5 # 排列窗格: - # 1) even-horizontal - # 2) even-vertical - # 3) main-horizontal - # 4) main-vertical - # 5) tiled + # 1) 水平等分 + # 2) 垂直等分 + # 3) 将一个窗格作为主要窗格,其他窗格水平等分 + # 4) 将一个窗格作为主要窗格,其他窗格垂直等分 + # 5) 平铺 C-Up, C-Down # 改变当前窗格的大小,每按一次增减一个单位 C-Left, C-Right -- cgit v1.2.3 From 15bd3ff223b998aad3ed2d5fc6a530adc31cb56c Mon Sep 17 00:00:00 2001 From: hyphz Date: Fri, 1 Jan 2016 01:54:11 +0000 Subject: Rename wolfram.md to wolfram.html.markdown --- wolfram.html.markdown | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++ wolfram.md | 137 -------------------------------------------------- 2 files changed, 137 insertions(+), 137 deletions(-) create mode 100644 wolfram.html.markdown delete mode 100644 wolfram.md diff --git a/wolfram.html.markdown b/wolfram.html.markdown new file mode 100644 index 00000000..4514006d --- /dev/null +++ b/wolfram.html.markdown @@ -0,0 +1,137 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnwolfram.nb +--- + +The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts. + +Wolfram Language has several interfaces: +* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input. +* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic +* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend + +The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. + +``` +(* This is a comment *) + +(* In Mathematica instead of using these comments you can create a text cell + and annotate your code with nicely typeset text and images *) + +(* Typing an expression returns the result *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Function Call *) +(* Note, function names (and everything else) are case sensitive *) +Sin[Pi/2] (* 1 *) + +(* Alternate Syntaxes for Function Call with one parameter *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Every syntax in WL has some equivalent as a function call *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Using a variable for the first time defines it and makes it global *) +x = 5 (* 5 *) +x == 5 (* True, C-style assignment and equality testing *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* I wasn't kidding when I said EVERYTHING has a function equivalent *) +x (* 20 *) + +(* Because WL is based on a computer algebra system, *) +(* using undefined variables is fine, they just obstruct evaluation *) +cow + 5 (* 5 + cow, cow is undefined so can't evaluate further *) +cow + 5 + 10 (* 15 + cow, it'll evaluate what it can *) +% (* 15 + cow, % fetches the last return *) +% - cow (* 15, undefined variable cow cancelled out *) +moo = cow + 5 (* Beware, moo now holds an expression, not a number! *) + +(* Defining a function *) +Double[x_] := x * 2 (* Note := to prevent immediate evaluation of the RHS + And _ after x to indicate no pattern matching constraints *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, @-syntax avoids queues of close brackets *) +(Pi/2) // Sin // Double(* 2, //-syntax lists functions in execution order *) + +(* For imperative-style programming use ; to separate statements *) +(* Discards any output from LHS and runs RHS *) +MyFirst[] := (Print@"Hello"; Print@"World") (* Note outer parens are critical + ;'s precedence is lower than := *) +MyFirst[] (* Hello World *) + +(* C-Style For Loop *) +PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Create an association *) +myHash[["Green"]] (* 2, use it *) +myHash[["Green"]] := 5 (* 5, update it *) +myHash[["Puce"]] := 3.5 (* 3.5, extend it *) +KeyDropFrom[myHash, "Green"] (* Wipes out key Green *) +Keys[myHash] (* {Red} *) +Values[myHash] (* {1} *) + +(* And you can't do any demo of Wolfram without showing this off *) +Manipulate[y^2, {y, 0, 20}] (* Return a reactive user interface that displays y^2 + and allows y to be adjusted between 0-20 with a slider. + Only works on graphical frontends *) +``` + +##Ready For More? + +* [Wolfram Language Documentation Center](http://reference.wolfram.com/language/) diff --git a/wolfram.md b/wolfram.md deleted file mode 100644 index 4514006d..00000000 --- a/wolfram.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -language: wolfram -contributors: - - ["hyphz", "http://github.com/hyphz/"] -filename: learnwolfram.nb ---- - -The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts. - -Wolfram Language has several interfaces: -* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input. -* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic -* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend - -The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. - -``` -(* This is a comment *) - -(* In Mathematica instead of using these comments you can create a text cell - and annotate your code with nicely typeset text and images *) - -(* Typing an expression returns the result *) -2*2 (* 4 *) -5+8 (* 13 *) - -(* Function Call *) -(* Note, function names (and everything else) are case sensitive *) -Sin[Pi/2] (* 1 *) - -(* Alternate Syntaxes for Function Call with one parameter *) -Sin@(Pi/2) (* 1 *) -(Pi/2) // Sin (* 1 *) - -(* Every syntax in WL has some equivalent as a function call *) -Times[2, 2] (* 4 *) -Plus[5, 8] (* 13 *) - -(* Using a variable for the first time defines it and makes it global *) -x = 5 (* 5 *) -x == 5 (* True, C-style assignment and equality testing *) -x (* 5 *) -x = x + 5 (* 10 *) -x (* 10 *) -Set[x, 20] (* I wasn't kidding when I said EVERYTHING has a function equivalent *) -x (* 20 *) - -(* Because WL is based on a computer algebra system, *) -(* using undefined variables is fine, they just obstruct evaluation *) -cow + 5 (* 5 + cow, cow is undefined so can't evaluate further *) -cow + 5 + 10 (* 15 + cow, it'll evaluate what it can *) -% (* 15 + cow, % fetches the last return *) -% - cow (* 15, undefined variable cow cancelled out *) -moo = cow + 5 (* Beware, moo now holds an expression, not a number! *) - -(* Defining a function *) -Double[x_] := x * 2 (* Note := to prevent immediate evaluation of the RHS - And _ after x to indicate no pattern matching constraints *) -Double[10] (* 20 *) -Double[Sin[Pi/2]] (* 2 *) -Double @ Sin @ (Pi/2) (* 2, @-syntax avoids queues of close brackets *) -(Pi/2) // Sin // Double(* 2, //-syntax lists functions in execution order *) - -(* For imperative-style programming use ; to separate statements *) -(* Discards any output from LHS and runs RHS *) -MyFirst[] := (Print@"Hello"; Print@"World") (* Note outer parens are critical - ;'s precedence is lower than := *) -MyFirst[] (* Hello World *) - -(* C-Style For Loop *) -PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Create an association *) -myHash[["Green"]] (* 2, use it *) -myHash[["Green"]] := 5 (* 5, update it *) -myHash[["Puce"]] := 3.5 (* 3.5, extend it *) -KeyDropFrom[myHash, "Green"] (* Wipes out key Green *) -Keys[myHash] (* {Red} *) -Values[myHash] (* {1} *) - -(* And you can't do any demo of Wolfram without showing this off *) -Manipulate[y^2, {y, 0, 20}] (* Return a reactive user interface that displays y^2 - and allows y to be adjusted between 0-20 with a slider. - Only works on graphical frontends *) -``` - -##Ready For More? - -* [Wolfram Language Documentation Center](http://reference.wolfram.com/language/) -- cgit v1.2.3 From 01ab402100a08e30d6f88406a55b08b744fcb375 Mon Sep 17 00:00:00 2001 From: hyphz Date: Fri, 1 Jan 2016 01:54:45 +0000 Subject: Rename factor.html to factor.html.markdown --- factor.html | 182 --------------------------------------------------- factor.html.markdown | 182 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+), 182 deletions(-) delete mode 100644 factor.html create mode 100644 factor.html.markdown diff --git a/factor.html b/factor.html deleted file mode 100644 index a0726420..00000000 --- a/factor.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -language: factor -contributors: - - ["hyphz", "http://github.com/hyphz/"] -filename: learnfactor.factor ---- - -Factor is a modern stack-based language, based on Forth, created by Slava Pestov. - -Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. - -``` -! This is a comment - -! Like Forth, all programming is done by manipulating the stack. -! Stating a literal value pushes it onto the stack. -5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode - -! Those numbers get added to the stack, from left to right. -! .s prints out the stack non-destructively. -.s ! 5 2 3 56 76 23 65 - -! Arithmetic works by manipulating data on the stack. -5 4 + ! No output - -! `.` pops the top result from the stack and prints it. -. ! 9 - -! More examples of arithmetic: -6 7 * . ! 42 -1360 23 - . ! 1337 -12 12 / . ! 1 -13 2 mod . ! 1 - -99 neg . ! -99 --99 abs . ! 99 -52 23 max . ! 52 -52 23 min . ! 23 - -! A number of words are provided to manipulate the stack, collectively known as shuffle words. - -3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3 -2 5 swap / ! swap the top with the second element: 5 / 2 -4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2 -1 2 3 nip .s ! remove the second item (similar to drop): 1 3 -1 2 clear .s ! wipe out the entire stack -1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 -1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3 - -! Creating Words -! The `:` word sets Factor into compile mode until it sees the `;` word. -: square ( n -- n ) dup * ; ! No output -5 square . ! 25 - -! We can view what a word does too. -! \ suppresses evaluation of a word and pushes its identifier on the stack instead. -\ square see ! : square ( n -- n ) dup * ; - -! After the name of the word to create, the declaration between brackets gives the stack effect. -! We can use whatever names we like inside the declaration: -: weirdsquare ( camel -- llama ) dup * ; - -! Provided their count matches the word's stack effect: -: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong -: doubledup ( a -- a a a ) dup dup ; ! Ok -: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok - -! Where Factor differs from Forth is in the use of quotations. -! A quotation is a block of code that is pushed on the stack as a value. -! [ starts quotation mode; ] ends it. -[ 2 + ] ! Quotation that adds 2 is left on the stack -4 swap call . ! 6 - -! And thus, higher order words. TONS of higher order words. -2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3 -3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4 -1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4 -4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 ) -1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values -2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack - -! Conditionals -! Any value is true except the built-in value f. -! A built-in value t does exist, but its use isn't essential. -! Conditionals are higher order words as with the combinators above. - -5 [ "Five is true" . ] when ! Five is true -0 [ "Zero is true" . ] when ! Zero is true -f [ "F is true" . ] when ! No output -f [ "F is false" . ] unless ! F is false -2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true - -! By default the conditionals consume the value under test, but starred variants -! leave it alone if it's true: - -5 [ . ] when* ! 5 -f [ . ] when* ! No output, empty stack, f is consumed because it's false - - -! Loops -! You've guessed it.. these are higher order words too. - -5 [ . ] each-integer ! 0 1 2 3 4 -4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 -5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello - -! Here's a list: -{ 2 4 6 8 } ! Goes on the stack as one item - -! Loop through the list: -{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9 -{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack - -! Loop reducing or building lists: -{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 } -{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8) -{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 -1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 } -1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 } - -! If all else fails, a general purpose while loop: -1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times - ! Yes, it's hard to read - ! That's what all those variant loops are for - -! Variables -! Usually Factor programs are expected to keep all data on the stack. -! Using named variables makes refactoring harder (and it's called Factor for a reason) -! Global variables, if you must: - -SYMBOL: name ! Creates name as an identifying word -"Bob" name set-global ! No output -name get-global . ! "Bob" - -! Named local variables are considered an extension but are available -! In a quotation.. -[| m n ! Quotation captures top two stack values into m and n - | m n + ] ! Read them - -! Or in a word.. -:: lword ( -- ) ! Note double colon to invoke lexical variable extension - 2 :> c ! Declares immutable variable c to hold 2 - c . ; ! Print it out - -! In a word declared this way, the input side of the stack declaration -! becomes meaningful and gives the variable names stack values are captured into -:: double ( a -- result ) a 2 * ; - -! Variables are declared mutable by ending their name with a shriek -:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a - a ! Push a - a 2 * a! ! Multiply a by 2 and store result back in a - a ; ! Push new value of a -5 mword2 ! Stack: 5 10 - -! Lists and Sequences -! We saw above how to push a list onto the stack - -0 { 1 2 3 4 } nth ! Access a particular member of a list: 1 -10 { 1 2 3 4 } nth ! Error: sequence index out of bounds -1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2 -10 { 1 2 3 4 } ?nth ! No error if out of bounds: f - -{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } -{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } -"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } -"Concat" "enate" append ! "Concatenate" - strings are sequences too -"Concatenate" "Reverse " prepend ! "Reverse Concatenate" -{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" -{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" - -! And if you want to get meta, quotations are sequences and can be dismantled.. -0 [ 2 + ] nth ! 2 -1 [ 2 + ] nth ! + -[ 2 + ] \ - suffix ! Quotation [ 2 + - ] - - -``` - -##Ready For More? - -* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html) diff --git a/factor.html.markdown b/factor.html.markdown new file mode 100644 index 00000000..a0726420 --- /dev/null +++ b/factor.html.markdown @@ -0,0 +1,182 @@ +--- +language: factor +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnfactor.factor +--- + +Factor is a modern stack-based language, based on Forth, created by Slava Pestov. + +Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. + +``` +! This is a comment + +! Like Forth, all programming is done by manipulating the stack. +! Stating a literal value pushes it onto the stack. +5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode + +! Those numbers get added to the stack, from left to right. +! .s prints out the stack non-destructively. +.s ! 5 2 3 56 76 23 65 + +! Arithmetic works by manipulating data on the stack. +5 4 + ! No output + +! `.` pops the top result from the stack and prints it. +. ! 9 + +! More examples of arithmetic: +6 7 * . ! 42 +1360 23 - . ! 1337 +12 12 / . ! 1 +13 2 mod . ! 1 + +99 neg . ! -99 +-99 abs . ! 99 +52 23 max . ! 52 +52 23 min . ! 23 + +! A number of words are provided to manipulate the stack, collectively known as shuffle words. + +3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3 +2 5 swap / ! swap the top with the second element: 5 / 2 +4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2 +1 2 3 nip .s ! remove the second item (similar to drop): 1 3 +1 2 clear .s ! wipe out the entire stack +1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 +1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3 + +! Creating Words +! The `:` word sets Factor into compile mode until it sees the `;` word. +: square ( n -- n ) dup * ; ! No output +5 square . ! 25 + +! We can view what a word does too. +! \ suppresses evaluation of a word and pushes its identifier on the stack instead. +\ square see ! : square ( n -- n ) dup * ; + +! After the name of the word to create, the declaration between brackets gives the stack effect. +! We can use whatever names we like inside the declaration: +: weirdsquare ( camel -- llama ) dup * ; + +! Provided their count matches the word's stack effect: +: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong +: doubledup ( a -- a a a ) dup dup ; ! Ok +: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok + +! Where Factor differs from Forth is in the use of quotations. +! A quotation is a block of code that is pushed on the stack as a value. +! [ starts quotation mode; ] ends it. +[ 2 + ] ! Quotation that adds 2 is left on the stack +4 swap call . ! 6 + +! And thus, higher order words. TONS of higher order words. +2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3 +3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4 +1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4 +4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 ) +1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values +2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack + +! Conditionals +! Any value is true except the built-in value f. +! A built-in value t does exist, but its use isn't essential. +! Conditionals are higher order words as with the combinators above. + +5 [ "Five is true" . ] when ! Five is true +0 [ "Zero is true" . ] when ! Zero is true +f [ "F is true" . ] when ! No output +f [ "F is false" . ] unless ! F is false +2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true + +! By default the conditionals consume the value under test, but starred variants +! leave it alone if it's true: + +5 [ . ] when* ! 5 +f [ . ] when* ! No output, empty stack, f is consumed because it's false + + +! Loops +! You've guessed it.. these are higher order words too. + +5 [ . ] each-integer ! 0 1 2 3 4 +4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 +5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello + +! Here's a list: +{ 2 4 6 8 } ! Goes on the stack as one item + +! Loop through the list: +{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9 +{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack + +! Loop reducing or building lists: +{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 } +{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8) +{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 +1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 } +1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 } + +! If all else fails, a general purpose while loop: +1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times + ! Yes, it's hard to read + ! That's what all those variant loops are for + +! Variables +! Usually Factor programs are expected to keep all data on the stack. +! Using named variables makes refactoring harder (and it's called Factor for a reason) +! Global variables, if you must: + +SYMBOL: name ! Creates name as an identifying word +"Bob" name set-global ! No output +name get-global . ! "Bob" + +! Named local variables are considered an extension but are available +! In a quotation.. +[| m n ! Quotation captures top two stack values into m and n + | m n + ] ! Read them + +! Or in a word.. +:: lword ( -- ) ! Note double colon to invoke lexical variable extension + 2 :> c ! Declares immutable variable c to hold 2 + c . ; ! Print it out + +! In a word declared this way, the input side of the stack declaration +! becomes meaningful and gives the variable names stack values are captured into +:: double ( a -- result ) a 2 * ; + +! Variables are declared mutable by ending their name with a shriek +:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a + a ! Push a + a 2 * a! ! Multiply a by 2 and store result back in a + a ; ! Push new value of a +5 mword2 ! Stack: 5 10 + +! Lists and Sequences +! We saw above how to push a list onto the stack + +0 { 1 2 3 4 } nth ! Access a particular member of a list: 1 +10 { 1 2 3 4 } nth ! Error: sequence index out of bounds +1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2 +10 { 1 2 3 4 } ?nth ! No error if out of bounds: f + +{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } +{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } +"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } +"Concat" "enate" append ! "Concatenate" - strings are sequences too +"Concatenate" "Reverse " prepend ! "Reverse Concatenate" +{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" +{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" + +! And if you want to get meta, quotations are sequences and can be dismantled.. +0 [ 2 + ] nth ! 2 +1 [ 2 + ] nth ! + +[ 2 + ] \ - suffix ! Quotation [ 2 + - ] + + +``` + +##Ready For More? + +* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html) -- cgit v1.2.3 From 1f0b1bfb7a8d7abe3563015bad0110d6c319208f Mon Sep 17 00:00:00 2001 From: Borislav Kosharov Date: Sat, 2 Jan 2016 18:43:19 +0200 Subject: fix parallelism example typo --- d.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d.html.markdown b/d.html.markdown index 6f88cf84..edb3bff5 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -254,7 +254,7 @@ void main() { // Use an index, access every array element by reference (because we're // going to change each element) and just call parallel on the array! foreach(i, ref elem; parallel(arr)) { - ref = sqrt(i + 1.0); + elem = sqrt(i + 1.0); } } ``` -- cgit v1.2.3 From bde8645cc7bb7f0a88b5d106cd0bd0b7e40886d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Migda=C5=82?= Date: Sun, 3 Jan 2016 19:45:54 +0100 Subject: pep8 fixes (spaces and multiline statements) in Python readability and code style matters --- pythonstatcomp.html.markdown | 103 ++++++++++++++++++++++++------------------- 1 file changed, 57 insertions(+), 46 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 78b62e33..f8d83b98 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -9,6 +9,8 @@ This is a tutorial on how to do some typical statistical programming tasks using ```python + + # 0. Getting set up ==== """ Get set up with IPython and pip install the following: numpy, scipy, pandas, @@ -25,17 +27,17 @@ This is a tutorial on how to do some typical statistical programming tasks using already using Python, there's a benefit to sticking with one language. """ -import requests # for HTTP requests (web scraping, APIs) +import requests # for HTTP requests (web scraping, APIs) import os # web scraping r = requests.get("https://github.com/adambard/learnxinyminutes-docs") -r.status_code # if 200, request was successful -r.text # raw page source -print(r.text) # prettily formatted +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted # save the page source in a file: -os.getcwd() # check what's the working directory -f = open("learnxinyminutes.html","wb") +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html", "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -44,7 +46,7 @@ fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" fn = "pets.csv" r = requests.get(fp + fn) print(r.text) -f = open(fn,"wb") +f = open(fn, "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -58,7 +60,9 @@ f.close() you've used R, you will be familiar with the idea of the "data.frame" already. """ -import pandas as pd, numpy as np, scipy as sp +import pandas as pd +import numpy as np +import scipy as sp pets = pd.read_csv(fn) pets # name age weight species @@ -74,20 +78,20 @@ pets pets.age pets["age"] -pets.head(2) # prints first 2 rows -pets.tail(1) # prints last row +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row -pets.name[1] # 'vesuvius' -pets.species[0] # 'cat' -pets["weight"][2] # 34 +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 # in R, you would expect to get 3 rows doing this, but here you get 2: pets.age[0:2] # 0 3 # 1 6 -sum(pets.age)*2 # 28 -max(pets.weight) - min(pets.weight) # 20 +sum(pets.age) * 2 # 28 +max(pets.weight) - min(pets.weight) # 20 """ If you are doing some serious linear algebra and number-crunching, you may just want arrays, not DataFrames. DataFrames are ideal for combining columns @@ -96,7 +100,8 @@ max(pets.weight) - min(pets.weight) # 20 # 3. Charts ==== -import matplotlib as mpl, matplotlib.pyplot as plt +import matplotlib as mpl +import matplotlib.pyplot as plt %matplotlib inline # To do data vizualization in Python, use matplotlib @@ -105,13 +110,17 @@ plt.hist(pets.age); plt.boxplot(pets.weight); -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); +plt.scatter(pets.age, pets.weight) +plt.xlabel("age") +plt.ylabel("weight"); # seaborn sits atop matplotlib and makes plots prettier import seaborn as sns -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); +plt.scatter(pets.age, pets.weight) +plt.xlabel("age") +plt.ylabel("weight"); # there are also some seaborn-specific plotting functions # notice how seaborn automatically labels the x-axis on this barplot @@ -141,7 +150,7 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" r = requests.get(url) fp = "hre.csv" -f = open(fp,"wb") +f = open(fp, "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -149,33 +158,33 @@ hre = pd.read_csv(fp) hre.head() """ - Ix Dynasty Name Birth Death Election 1 -0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN -1 NaN Carolingian Louis I 778 20 June 840 NaN -2 NaN Carolingian Lothair I 795 29 September 855 NaN -3 NaN Carolingian Louis II 825 12 August 875 NaN -4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN - - Election 2 Coronation 1 Coronation 2 Ceased to be Emperor -0 NaN 25 December 800 NaN 28 January 814 -1 NaN 11 September 813 5 October 816 20 June 840 -2 NaN 5 April 823 NaN 29 September 855 -3 NaN Easter 850 18 May 872 12 August 875 -4 NaN 29 December 875 NaN 6 October 877 - - Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 -0 NaN NaN NaN NaN -1 Charles I son NaN NaN -2 Louis I son NaN NaN -3 Lothair I son NaN NaN -4 Louis I son NaN NaN + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN """ # clean the Birth and Death columns -import re # module for regular expressions +import re # module for regular expressions -rx = re.compile(r'\d+$') # match trailing digits +rx = re.compile(r'\d+$') # match trailing digits """ This function applies the regular expression to an input column (here Birth, Death), flattens the resulting list, converts it to a Series object, and @@ -185,8 +194,9 @@ rx = re.compile(r'\d+$') # match trailing digits - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html """ + def extractYear(v): - return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int)) hre["BirthY"] = extractYear(hre.Birth) hre["DeathY"] = extractYear(hre.Death) @@ -199,17 +209,17 @@ sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); # use scipy to run a linear regression from scipy import stats -(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +(slope, intercept, rval, pval, stderr) = stats.linregress(hre.BirthY, hre.EstAge) # code source: http://wiki.scipy.org/Cookbook/LinearRegression # check the slope -slope # 0.0057672618839073328 +slope # 0.0057672618839073328 # check the R^2 value: -rval**2 # 0.020363950027333586 +rval**2 # 0.020363950027333586 # check the p-value -pval # 0.34971812581498452 +pval # 0.34971812581498452 # use seaborn to make a scatterplot and plot the linear regression trend line sns.lmplot("BirthY", "EstAge", data=hre); @@ -223,6 +233,7 @@ sns.lmplot("BirthY", "EstAge", data=hre); To see a version of the Holy Roman Emperors analysis using R, see - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R """ + ``` If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. -- cgit v1.2.3 From 746df3268afcd0307c0da434bf162632be3d53ea Mon Sep 17 00:00:00 2001 From: Bruno Volcov Date: Mon, 4 Jan 2016 17:28:36 -0200 Subject: remove contributors name --- ruby.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index b3ef2a4d..267889b1 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -13,7 +13,6 @@ contributors: - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gabriel Halley", https://github.com/ghalley] - - ["Bruno Volcov", https://github.com/volcov] --- -- cgit v1.2.3 From a5730e4ab931b8355704d35ee08acef75435bd83 Mon Sep 17 00:00:00 2001 From: bk2dcradle Date: Tue, 5 Jan 2016 13:25:56 +0530 Subject: Update --- c++.html.markdown | 48 +++++++----------------------------------------- 1 file changed, 7 insertions(+), 41 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 6033ca06..c1bacf6a 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -809,7 +809,7 @@ void doSomethingWithAFile(const std::string& filename) // object right at the location where it is invoked or passed as // an argument to a function. -// Example consider sorting a vector of pairs using the second +// For example, consider sorting a vector of pairs using the second // value of the pair vector > tester; @@ -820,7 +820,7 @@ tester.push_back(make_pair(5, 0)); // Pass a lambda expression as third argument to the sort function // sort is from the header -sort(tester.begin(), tester.end(), [](const pair &lhs, const pair &rhs) { +sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { return lhs.second < rhs.second; }); @@ -834,48 +834,22 @@ for(int i = 0; i < 3; i++){ dog_ids.push_back(i); } -int weight[3]; -weight[0] = 30, weight[1] = 50, weight[2] = 10; +int weight[3] = {30, 50, 10}; // Say you want to sort dog_ids according to the dogs' weights // So dog_ids should in the end become: [2, 0, 1] // Here's where lambda expressions come in handy -sort(dog_ids.begin(), dog_ids.end(), [weight](const int &lhs, const int &rhs) { +sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { return weight[lhs] < weight[rhs]; }); -// Note we captured "weight" in the above example. +// Note we captured "weight" by reference in the above example. // lambda are really useful for the case of structs // You can use lambda expressions instead of overloading // the "<" operator -struct dog{ - int weight, age; -}dogs[3]; - -dogs[0].weight = 30, dogs[0].age = 4; -dogs[1].weight = 40, dogs[1].age = 10; -dogs[2].weight = 20, dogs[2].age = 9; - -// Say I want to sort the dogs array by the dogs' weights - -sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { - return lhs.weight < rhs.weight; - }); -// dogs is now sorted according to their weight - -// Do something with the dogs - -// Now I want to sort the dogs by in descending order of their age - -sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { - return lhs.age > rhs.age; - }); -// dogs is now sorted in descending order of their age - - /////////////////////////////// // Range For (C++11 and above) /////////////////////////////// @@ -884,24 +858,16 @@ sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { int arr[] = {1, 10, 3}; for(int elem: arr){ - cout< Date: Tue, 5 Jan 2016 13:36:23 +0530 Subject: Add my Changes --- c++.html.markdown | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index f4aa2f5a..31dbe064 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -820,6 +820,73 @@ std::map fooMap; fooMap[Foo(1)] = 1; fooMap.find(Foo(1)); //true +/////////////////////////////////////// +// Lambda Expressions (C++11 and above) +/////////////////////////////////////// + +// lambdas are a convenient way of defining an anonymous function +// object right at the location where it is invoked or passed as +// an argument to a function. + +// For example, consider sorting a vector of pairs using the second +// value of the pair + +vector > tester; +tester.push_back(make_pair(3, 6)); +tester.push_back(make_pair(1, 9)); +tester.push_back(make_pair(5, 0)); + +// Pass a lambda expression as third argument to the sort function +// sort is from the header + +sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { + return lhs.second < rhs.second; + }); + +// Notice the syntax of the lambda expression, +// [] in the lambda is used to "capture" variables. +// For Example: + +vector dog_ids; +// number_of_dogs = 3; +for(int i = 0; i < 3; i++){ + dog_ids.push_back(i); +} + +int weight[3] = {30, 50, 10}; + +// Say you want to sort dog_ids according to the dogs' weights +// So dog_ids should in the end become: [2, 0, 1] + +// Here's where lambda expressions come in handy + +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. + +// lambda are really useful for the case of structs +// You can use lambda expressions instead of overloading +// the "<" operator + +/////////////////////////////// +// Range For (C++11 and above) +/////////////////////////////// + +// You can use a range for loop to iterate over a container +int arr[] = {1, 10, 3}; + +for(int elem: arr){ + cout << elem << endl; +} + +// You can use "auto" and not worry about the type of the elements of the container +// For example: + +for(auto elem: arr) { + // Do something with each element of arr +} + ///////////////////// // Fun stuff ///////////////////// -- cgit v1.2.3 From 0fbf289e3cbce3f2b6e830d5dcf1c8d3685a88a1 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 6 Jan 2016 03:14:04 +0800 Subject: Update go-fr.html.markdown --- fr-fr/go-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 16558e7e..9d8bef70 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -3,7 +3,7 @@ name: Go category: language language: Go lang: fr-fr -filename: learngo.go +filename: learngo-fr.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] -- cgit v1.2.3 From e47099866bee5e5f6d2852f4e4cbf92e4d4b0053 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 6 Jan 2016 03:17:33 +0800 Subject: Fix formatting. --- powershell.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/powershell.html.markdown b/powershell.html.markdown index 4bc1ab39..8920d254 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -18,6 +18,7 @@ rather than plain text. [Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) If you are uncertain about your environment: + ``` Get-ExecutionPolicy -List Set-ExecutionPolicy AllSigned @@ -33,6 +34,7 @@ $PSVersionTable ``` Getting help: + ``` # Find commands Get-Command about_* # alias: gcm @@ -49,6 +51,7 @@ Update-Help # Run as admin ``` The tutorial starts here: + ``` # As you already figured, comments start with # @@ -292,6 +295,7 @@ $Shortcut.Save() Configuring your shell + ``` # $Profile is the full path for your `Microsoft.PowerShell_profile.ps1` # All code there will be executed when the PS session starts -- cgit v1.2.3 From 1d65107a8fd74e67b2b9fe7e2e503a04d0db4df0 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 6 Jan 2016 04:13:33 +0800 Subject: Update latex-es.html.markdown --- es-es/latex-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/latex-es.html.markdown b/es-es/latex-es.html.markdown index 6743ad80..aff3c603 100644 --- a/es-es/latex-es.html.markdown +++ b/es-es/latex-es.html.markdown @@ -1,5 +1,6 @@ --- language: latex +lang: es-es contributors: - ["Chaitanya Krishna Ande", "http://icymist.github.io"] - ["Colton Kohnke", "http://github.com/voltnor"] -- cgit v1.2.3 From e6866f5a26dab28d2d1b5628fbb18139c36a5139 Mon Sep 17 00:00:00 2001 From: bk2dcradle Date: Fri, 8 Jan 2016 01:21:38 +0530 Subject: More Fixes --- c++.html.markdown | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 31dbe064..44cad665 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -840,16 +840,22 @@ tester.push_back(make_pair(5, 0)); // sort is from the header sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { - return lhs.second < rhs.second; - }); + return lhs.second < rhs.second; + }); // Notice the syntax of the lambda expression, -// [] in the lambda is used to "capture" variables. -// For Example: +// [] in the lambda is used to "capture" variables +// The "Capture List" defines what from the outside of the lambda should be available inside the function body and how. +// It can be either: +// 1. a value : [x] +// 2. a reference : [&x] +// 3. any variable currently in scope by reference [&] +// 4. same as 3, but by value [=] +// Example: vector dog_ids; // number_of_dogs = 3; -for(int i = 0; i < 3; i++){ +for(int i = 0; i < 3; i++) { dog_ids.push_back(i); } @@ -861,13 +867,10 @@ int weight[3] = {30, 50, 10}; // Here's where lambda expressions come in handy sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { - return weight[lhs] < weight[rhs]; - }); + return weight[lhs] < weight[rhs]; + }); // Note we captured "weight" by reference in the above example. - -// lambda are really useful for the case of structs -// You can use lambda expressions instead of overloading -// the "<" operator +// More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11 /////////////////////////////// // Range For (C++11 and above) -- cgit v1.2.3 From cc31c2f0c5032b723a1d57c971580121be07bf7f Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Thu, 7 Jan 2016 22:08:17 -0700 Subject: Fix typo referenced in Issue #2075 --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 6633b322..5082a433 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1329,7 +1329,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... -### Extra: the MAIN subroutime +### Extra: the MAIN subroutine # The `MAIN` subroutine is called when you run a Perl 6 file directly. # It's very powerful, because Perl 6 actually parses the arguments # and pass them as such to the sub. It also handles named argument (`--foo`) -- cgit v1.2.3 From 8ad537a9ba9889234a63c5a38caeab3e225856e4 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 8 Jan 2016 14:35:16 +0800 Subject: unfuck markdown doc --- cs-cz/markdown.html.markdown | 1 + markdown.html.markdown | 50 ++++++++++++++++++++++++++++---------------- 2 files changed, 33 insertions(+), 18 deletions(-) diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 637f0ab6..363af5e9 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -1,5 +1,6 @@ --- language: markdown +lang: cs-cz contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: diff --git a/markdown.html.markdown b/markdown.html.markdown index 8961c995..05eeecbe 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -26,6 +26,7 @@ specific to a certain parser. ## HTML Elements Markdown is a superset of HTML, so any HTML file is valid Markdown. + ```markdown + +
+```ruby
 def foobar
     puts "Hello world!"
 end
-\`\`\` 
-```
+```
The above text doesn't require indenting, plus Github will use syntax highlighting of the language you specify after the \`\`\` @@ -212,6 +216,7 @@ highlighting of the language you specify after the \`\`\` Horizontal rules (`
`) are easily added with three or more asterisks or hyphens, with or without spaces. + ```markdown *** --- @@ -228,58 +233,64 @@ the text to display in hard brackets [] followed by the url in parentheses () [Click me!](http://test.com/) ``` You can also add a link title using quotes inside the parentheses. + ```markdown [Click me!](http://test.com/ "Link to Test.com") ``` Relative paths work too. + ```markdown [Go to music](/music/). ``` + Markdown also supports reference style links. -```markdown -[Click this link][link1] for more info about it! -[Also check out this link][foobar] if you want to. -[link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "Alright!" -``` +
[Click this link][link1] for more info about it!
+[Also check out this link][foobar] if you want to.
+
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Alright!"
+ The title can also be in single quotes or in parentheses, or omitted entirely. The references can be anywhere in your document and the reference IDs can be anything so long as they are unique. There is also "implicit naming" which lets you use the link text as the id. -```markdown -[This][] is a link. -[this]: http://thisisalink.com/ -``` +
[This][] is a link.
+
+[this]: http://thisisalink.com/
+ But it's not that commonly used. ## Images Images are done the same way as links but with an exclamation point in front! + ```markdown ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") ``` + And reference style works as expected. -```markdown -![This is the alt-attribute.][myimage] -[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" -``` +
![This is the alt-attribute.][myimage]
 
+[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
## Miscellany ### Auto-links + ```markdown is equivalent to [http://testwebsite.com/](http://testwebsite.com/) ``` ### Auto-links for emails + ```markdown ``` ### Escaping characters + ```markdown I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. @@ -288,6 +299,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*. ### Keyboard keys In Github Flavored Markdown, you can use a `` tag to represent keyboard keys. + ```markdown Your computer crashed? Try sending a Ctrl+Alt+Del @@ -296,6 +308,7 @@ Your computer crashed? Try sending a Tables are only available in Github Flavored Markdown and are slightly cumbersome, but if you really want it: + ```markdown | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | @@ -309,5 +322,6 @@ Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop ``` + --- 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). -- cgit v1.2.3 From e4e737c37125ed831b8f4d24d2d4953814ef9722 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Fri, 8 Jan 2016 19:50:57 +0100 Subject: [PowerShell/en]: fixed typos/layout. Added some extra aliases/info. --- powershell.html.markdown | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index 8920d254..fc944b85 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -247,10 +247,12 @@ function New-Website() { [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') # Note that .NET functions MUST be called with parentheses -# while PS functions CANNOT be called with parentheses +# while PS functions CANNOT be called with parentheses. +# If you do call a cmdlet/PS function with parentheses, +# it is the same as passing a single parameter list $writer = New-Object System.IO.StreamWriter($path, $true) $writer.Write([Environment]::NewLine) -$write.Dispose() +$writer.Dispose() ### IO # Reading a value from input: @@ -268,12 +270,14 @@ Get-Command ConvertTo-*,ConvertFrom-* # Refresh your PATH $env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") + # Find Python in path $env:PATH.Split(";") | Where-Object { $_ -like "*python*"} # Change working directory without having to remember previous path Push-Location c:\temp # change working directory to c:\temp Pop-Location # change back to previous working directory +# Aliases are: pushd and popd # Unblock a directory after download Get-ChildItem -Recurse | Unblock-File @@ -308,6 +312,7 @@ if (-not (Test-Path $Profile)) { ``` Interesting Projects + * [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials * [PSGet](https://github.com/psget/psget) NuGet for PowerShell * [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!) @@ -318,6 +323,7 @@ Interesting Projects * [PowerShell Community Extensions](http://pscx.codeplex.com/) (Dead) Not covered + * WMI: Windows Management Intrumentation (Get-CimInstance) * Multitasking: Start-Job -scriptBlock {...}, * Code Signing -- cgit v1.2.3 From 759a6a29aa02d53098d571999e175b4bd03a3052 Mon Sep 17 00:00:00 2001 From: ditam Date: Fri, 8 Jan 2016 21:09:47 +0100 Subject: add language label --- hu-hu/yaml-hu.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown index aca6cd37..37ce4cb2 100644 --- a/hu-hu/yaml-hu.html.markdown +++ b/hu-hu/yaml-hu.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Tamás Diószegi", "https://github.com/ditam"] +lang: hu-hu --- A YAML egy adat sorosító nyelv, amit úgy terveztek, hogy közvetlenül is -- cgit v1.2.3 From 15a7e7ace2e61470c5b0de667d33d06a1223ba46 Mon Sep 17 00:00:00 2001 From: SWalls Date: Sun, 10 Jan 2016 17:22:32 -0700 Subject: Changed a to b in comment about list assignment, and pluralized 'variable'. --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 8cc03320..31b5bbe1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -97,13 +97,13 @@ False or True # => True 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# (is vs. ==) is checks if two variable refer to the same object, but == checks +# (is vs. ==) is checks if two variables refer to the same object, but == checks # if the objects pointed to have the same values. a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] b = a # Point b at what a is pointing to b is a # => True, a and b refer to the same object b == a # => True, a's and b's objects are equal -b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4] b is a # => False, a and b do not refer to the same object b == a # => True, a's and b's objects are equal -- cgit v1.2.3 From f94dea8379b5e7a28990eac371f9c9cca19ab472 Mon Sep 17 00:00:00 2001 From: Matteo Baglini Date: Tue, 12 Jan 2016 00:32:03 +0100 Subject: Use proper string comparison syntax --- bash.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 211d2944..bd2d5984 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -83,7 +83,7 @@ echo Hello, $Name! # We have the usual if structure: # use 'man test' for more info about conditionals -if [ $Name -ne $USER ] +if [ $Name != $USER ] then echo "Your name isn't your username" else @@ -91,12 +91,12 @@ else fi # NOTE: if $Name is empty, bash sees the above condition as: -if [ -ne $USER ] +if [ != $USER ] # which is invalid syntax # so the "safe" way to use potentially empty variables in bash is: -if [ "$Name" -ne $USER ] ... +if [ "$Name" != $USER ] ... # which, when $Name is empty, is seen by bash as: -if [ "" -ne $USER ] ... +if [ "" != $USER ] ... # which works as expected # There is also conditional execution -- cgit v1.2.3 From 8ecf73a086b41a33058211f7a415b771bb04f79d Mon Sep 17 00:00:00 2001 From: Paul Brewczynski Date: Wed, 13 Jan 2016 10:01:46 +0100 Subject: Updated documentation syntax As Xcode switched to Markdown syntax, I've updated it. --- swift.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index e6bf1621..c54f8e00 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -221,9 +221,9 @@ A greet operation - A bullet in docs - Another bullet in the docs -:param: name A name -:param: day A day -:returns: A string containing the name and day value. +- Parameter name : A name +- Parameter day : A day +- Returns : A string containing the name and day value. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." -- cgit v1.2.3 From e8c0c436c9aad0f3902a4e0826bf72de49bde12b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Thu, 14 Jan 2016 10:17:51 -0500 Subject: Added observer pattern, per barkthin's feedback --- solidity.html.markdown | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 71a44b92..3a5e8ff5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -506,7 +506,8 @@ function remove() { // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit -// call contract's reveal function showing bid plus secret that hashes to SHA3 +// call contract's reveal function in the future +// showing bid plus secret that hashes to SHA3 reveal(100, "mySecret"); // B. Storage optimization @@ -531,7 +532,45 @@ reveal(100, "mySecret"); // Contracts must be manually called to handle time-based scheduling; can create external // code to regularly ping, or provide incentives (ether) for others to -// E. State machines +// E. Observer Pattern +// An Observer Pattern lets you register as a subscriber and +// register a function which is called by the oracle (note, the oracle pays +// for this action to be run) +// Some similarities to subscription in Pub/sub + +// This is an abstract contract, both client and server classes import +// the client should implement +contract SomeOracleCallback { + function oracleCallback(int _value, uint _time, bytes32 info) external; +} + +contract SomeOracle { + SomeOracleCallback[] callbacks; // array of all subscribers + + // Register subscriber + function addSubscriber(SomeOracleCallback a) { + callbacks.push(a); + } + + function notify(value, time, info) private { + for(uint i = 0;i < callbacks.length; i++) { + // all called subscribers must implement the oracleCallback + callbacks[i].oracleCallback(value, time, info); + } + } + + function doSomething() public { + // Code to do something + + // Notify all subscribers + notify(_value, _time, _info); + } +} + +// Now, your client contract can addSubscriber by importing SampleOracleCallback +// and registering with Sample Oracle + +// F. State machines // see example below for State enum and inState modifier @@ -748,7 +787,7 @@ someContractAddress.callcode('function_name'); - Libraries ## Style -- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) +- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy ## Future To Dos - New keywords: protected, inheritable -- cgit v1.2.3 From 1c1944acb480d9c463c59136eba5ffa19f376fdc Mon Sep 17 00:00:00 2001 From: Paul Brewczynski Date: Thu, 14 Jan 2016 19:11:45 +0100 Subject: Updated comment on documentation of Swift functions Documentation syntax is no longer reStructuredText, It's "Swift-flavored version of Markdown" http://nshipster.com/swift-documentation/ --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index c54f8e00..46996526 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -213,7 +213,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift header docs (format as reStructedText) +// Function with Swift header docs (format as Swift-modified Markdown syntax) /** A greet operation -- cgit v1.2.3 From 810108ee73a6acc882155ec7ff1bc07983ced05e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Thu, 14 Jan 2016 14:01:45 -0500 Subject: Fixed error in name --- solidity.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 3a5e8ff5..a511bbb3 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -567,8 +567,8 @@ contract SomeOracle { } } -// Now, your client contract can addSubscriber by importing SampleOracleCallback -// and registering with Sample Oracle +// Now, your client contract can addSubscriber by importing SomeOracleCallback +// and registering with Some Oracle // F. State machines // see example below for State enum and inState modifier -- cgit v1.2.3 From 107356e627716b75cd79486dbacb1b5d119b4d82 Mon Sep 17 00:00:00 2001 From: Paul Brewczynski Date: Sat, 16 Jan 2016 19:30:25 +0100 Subject: [Swift/en] Deleted semicolon to be consistent - Small Fix this line let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon show off semicolon use. But after that semicolon is not used, so I removed inconsistency. --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 46996526..46768375 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -392,7 +392,7 @@ testTryStuff() public class Shape { public func getArea() -> Int { - return 0; + return 0 } } -- cgit v1.2.3 From e91cb98abedd979f67acdc08dd7cb81b75f317cc Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 19:38:14 +0100 Subject: Translated Wolfram tutorial to french --- fr-fr/wolfram-fr.html.markdown | 166 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 fr-fr/wolfram-fr.html.markdown diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown new file mode 100644 index 00000000..d297bd74 --- /dev/null +++ b/fr-fr/wolfram-fr.html.markdown @@ -0,0 +1,166 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] + - ["altaris", "http://github.com/altaris/"] +filename: learnwolfram.nb +--- + +Le langage Wolfram est utilisé dans les programmes suivants : +* La ligne de commandes interactive noyau du Raspberry Pi, mais elle ne peut pas +gérer des éléments graphiques. +* _Mathematica_, un éditeur de texte riche spécialisé pour les mathématiques : +appuyer sur `Shift + Entrée` dans une cellule de code crée un nouvelle cellule +contenant le résultat. +* _Wolfram Wokbench_, une variante d'Eclipse spécialisée pour le langage +Wolfram. + +Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant, le +copier-coller directement dans Mathematica peut causer des problèmes de +formatage, car il ne contient aucune information de mise en page. + +``` +(* Ceci est un commentaire *) + +(* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des + cellules de texte et insérer de jolies images *) + +(* Saisissez une opération et appuyez sur Shift + Entrée pour obtenir le + résultat *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Appels de fonction *) +(* Le langage Wolfram est sensible à la casse *) +Sin[Pi/2] (* 1 *) + +(* Syntaxe alternative pour les appels de fonction à 1 paramètre *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Dans le langage Wolfram, toutes les expressions sont en réalité des appels de + fonction *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Utiliser une variable pour la première fois la déclare globalement *) +x = 5 (* 5 *) +x == 5 (* True, l'assignation et le test d'égalité est écrit comme + dans le C *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *) +x (* 20 *) + +(* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des + variables non déclarées n'est pas illégal *) +cow + 5 (* 5 + cow, comme cow n'est pas déclarée, l'évaluation + s'arrête là *) +cow + 5 + 10 (* 15 + cow, on évalue ce qu'on peut... *) +% (* 15 + cow, % représente le dernier résultat *) +% - cow (* 15, les variables non déclarées peuvent quand même + s'annuler *) +moo = cow + 5 (* Attention : moo est ici une expression et non un nombre *) + +(* Déclaration d'une fonction *) +Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme + à droite *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets + fermants si moches *) +(Pi/2) // Sin // Double(* 2, Utiliser // permet d'écrire les fonctions dans + l'ordre d'appel *) + +(* Pour la programmation impérative, utiliser ; pour séparer les expressions *) +MyFirst[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires + car ; est prioritaire sur := *) +MyFirst[] (* Hello World *) + +(* Boucles For à la C *) +PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Crée une table associative *) +myHash[["Green"]] (* 2, l'utilise *) +myHash[["Green"]] := 5 (* 5, la modifie *) +myHash[["Puce"]] := 3.5 (* 3.5, l'étend *) +KeyDropFrom[myHash, "Green"] (* Supprime la clé "Green" *) +Keys[myHash] (* {Red} *) +Values[myHash] (* {1} *) + +(* Pour finir, toute bonne démonstration du langage Wolfram contient un + Manipulate ! *) +Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui + affiche y^2, permettant à l'utilisateur de + modifier la valeur de y grâce à un contrôle + allant de 0 à 20. Ne fonctionne que si le + logiciel utilisé gère les éléments graphique. *) +``` + +## Envie d'aller plus loin ? + +* [Documentation du langage Wolfram (en anglais)] +(http://reference.wolfram.com/language/) \ No newline at end of file -- cgit v1.2.3 From c70f53aabea745d4450aa51abdc33aa1ac51bdd2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 21:53:21 +0100 Subject: Translated make tutorial to french --- fr-fr/make-fr.html.markdown | 266 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 fr-fr/make-fr.html.markdown diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown new file mode 100644 index 00000000..8643ba45 --- /dev/null +++ b/fr-fr/make-fr.html.markdown @@ -0,0 +1,266 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["altaris", "https://github.com/altaris"] +filename: Makefile +--- + +Un makefile est un fichier qui définit un ensemble de règles liées entre elles +pour créer une ou plusieurs cibles. L'idée est d'effectuer le moins de travail +possible afin de mettre à jour la ou les cibles en fonction des dépendances. + +Écrit en un week-end par Stuart Feldman en 1976, le make et les +makefiles sont encore très utilisés (principalement dans les systèmes Unix), +malgré la concurrence et les critiques faites à son égard. + +Le programme make a plusieurs variantes. Dans ce tutoriel, nous utiliserons +l'implémentation standard : GNU make. + +```make + +# Ceci est un commentaire. + +# Un makefile devrait être nommé "Makefile" (avec ou sans la +# majuscule). Il peut alors être exécuté par `make `. +# Ce nommage n'est toutefois pas obligatoire : utiliser +# `make -f "fichier" `. + +# ATTENTION : l'indentation est quant à elle obligatoire, et se fait avec des +# tabulations, pas avec des espaces ! + +#----------------------------------------------------------------------- +# Les basiques +#----------------------------------------------------------------------- + +# Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. +file0.txt: + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. + +# Cette règle ne sera exécutée que si fichier0.txt est plus récent que +# fichier1.txt. +file1.txt: fichier0.txt + cat fichier0.txt > fichier1.txt + # Utiliser les même guillemets que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à être exécutée si cette + # commande échoue. + +# Un règle peut avoir plusieurs cibles et plusieurs dépendances. +file2.txt fichier3.txt: fichier0.txt fichier1.txt + touch fichier2.txt + touch fichier3.txt + +# Make affichera un avertissement si le makefile comporte plusieurs règles pour +# une même cible. Cependant les règles vides ne comptent pas, et peuvent être +# utilisées pour ajouter des dépendances plus facilement. + +#----------------------------------------------------------------------- +# Fausses règles +#----------------------------------------------------------------------- + +# Une fausse règle est un règle qui ne correspond pas à un fichier. +# Par définition, elle ne peut pas être à jour, et donc make l’exécutera à +# chaque demande. +all: maker process + +# La déclaration des règles peut être faite dans n'importe quel ordre. +maker: + touch ex0.txt ex1.txt + +# On peut transformer une règle en fausse règle grâce à la cible spéciale +# suivante : +.PHONY: all maker process + +# Un règle dépendante d'une fausse règle sera toujours exécutée. +ex0.txt ex1.txt: maker + +# Voici quelques exemples fréquents de fausses règles : all, make, clean, +# install... + +#----------------------------------------------------------------------- +# Variables automatiques et wildcards +#----------------------------------------------------------------------- + +# Utilise un wildcard pour des noms de fichier +process: fichier*.txt + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. + +# Même si la définition de la règle est scindée en plusieurs morceaux, $^ +# listera toutes les dépendances indiquées. +process: ex1.txt fichier0.txt +# Ici, fichier0.txt est un duplicata dans $+. + +#----------------------------------------------------------------------- +# Pattern matching +#----------------------------------------------------------------------- + +# En utilisant le pattern matching, on peut par exemple créer des règles pour +# convertir les fichiers d'un certain format dans un autre. +%.png: %.svg + inkscape --export-png $^ + +# Make exécute une règle même si le fichier correspondant est situé dans un sous +# dossier. En cas de conflit, la règle avec la meilleure correspondance est +# choisie. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# Dans ce type de conflit (même cible, même dépendances), make exécutera la +# dernière règle déclarée... +%.png: %.svg + @echo cette règle est choisie + +# Dans ce type de conflit (même cible mais pas les mêmes dépendances), make +# exécutera la première règle pouvant être exécutée. +%.png: %.ps + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + +# Make a des règles pré établies. Par exemple, il sait comment créer la cible +# *.o à partir de *.c. + +# Les makefiles plus vieux utilisent un matching par extension de fichier. +.png.ps: + @echo cette règle est similaire à une règle par pattern matching + +# Utiliser cette syntaxe pour déclarer une règle comme règle avec matching par +# extension de fichier. +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variables, ou macros +#----------------------------------------------------------------------- + +# Les variables sont des chaînes de caractères. + +variable = Ted +variable2="Sarah" + +echo: + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + +# Les variables sont déclarées de 4 manières, de la plus grande priorité à la +# plus faible : +# 1 : dans la ligne de commande qui invoque make, +# 2 : dans le makefile, +# 3 : dans les variables d’environnement du terminal qui invoque make, +# 4 : les variables prédéfinies. + +# Assigne la variable si une variable d’environnement du même nom n'existe pas +# déjà. +variable4 ?= Jean + +# Empêche cette variable d'être modifiée par la ligne de commande. +override variable5 = David + +# Concatène à une variable (avec un espace avant). +variable4 +=gris + +# Assignations de variable pour les règles correspondant à un pattern +# (spécifique à GNU make). +*.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous + # leurs descendants, la variable variable2 vaudra + # "Sara". +# Si le jeux des dépendances et descendances devient vraiment trop compliqué, +# des inconsistances peuvent survenir. + +# Certaines variables sont prédéfinies par make : +affiche_predefinies: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables : le retour +#----------------------------------------------------------------------- + +# Les variables sont évaluées à chaque instance, ce qui peut être coûteux en +# calculs. Pour parer à ce problème, il existe dans GNU make une seconde +# manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule +# fois seulement. + +var := wesh +var2 ::= $(var) mec # := et ::= sont équivalents. + +# Ces variables sont évaluées procéduralement (i.e. dans leur ordre +# d'apparition), contrairement au règles par exemple ! + +# Ceci ne fonctionne pas. +var3 ::= $(var4) et fais de beaux rêves +var4 ::= bonne nuit + +#----------------------------------------------------------------------- +# Fonctions +#----------------------------------------------------------------------- + +# Make a une multitude de fonctions. La syntaxe générale est +# $(fonction arg0,arg1,arg2...). + +# Quelques exemples : + +fichiers_source = $(wildcard *.c */*.c) +fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) + +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# Inclut d'autres makefiles. +include meuh.mk + +# Branchements conditionnels. +sport = tennis +report: +ifeq ($(sport),tennis) # Il y a aussi ifneq. + @echo 'jeu, set et match' +else + @echo "C'est pas ici Wimbledon ?" +endif + +truc = true +ifdef $(truc) # Il y a aussi ifndef. + machin = 'salut' +endif +``` + +## Quelques références + +### En français + ++ [Introduction à Makefile (developpez.com)] +(http://gl.developpez.com/tutoriel/outil/makefile/), ++ [Compilez sous GNU/Linux ! (openclassrooms)] +(https://openclassrooms.com/courses/compilez-sous-gnu-linux). + +### En anglais + ++ [Documentation de GNU make](https://www.gnu.org/software/make/manual/), ++ [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/), ++ Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) +[ex28](http://c.learncodethehardway.org/book/ex28.html). \ No newline at end of file -- cgit v1.2.3 From 5c4eba5ef34593a0c6425da64f6a0d7688fca3d2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 21:54:51 +0100 Subject: Removed tabs in header --- fr-fr/make-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 8643ba45..405c47cd 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -1,8 +1,8 @@ --- language: make contributors: - - ["Robert Steed", "https://github.com/robochat"] - - ["altaris", "https://github.com/altaris"] + - ["Robert Steed", "https://github.com/robochat"] + - ["altaris", "https://github.com/altaris"] filename: Makefile --- -- cgit v1.2.3 From a4e4b76afdb538fa577db8823bb7349ff7872722 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:07:20 +0100 Subject: Corrections to make-fr ... according to pull request comments: - completed header; - some typos; - finished translating target names. --- fr-fr/make-fr.html.markdown | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 405c47cd..b8255ce7 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -3,7 +3,8 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] - ["altaris", "https://github.com/altaris"] -filename: Makefile +filename: Makefile-fr +lang: fr-fr --- Un makefile est un fichier qui définit un ensemble de règles liées entre elles @@ -34,23 +35,23 @@ l'implémentation standard : GNU make. #----------------------------------------------------------------------- # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. -file0.txt: +fichier0.txt: echo "truc" > fichier0.txt # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. -file1.txt: fichier0.txt +fichier1.txt: fichier0.txt cat fichier0.txt > fichier1.txt - # Utiliser les même guillemets que dans un terminal. + # Utiliser la même syntaxe que dans un terminal. @cat fichier0.txt >> fichier1.txt # @ empêche l'affichage de la sortie texte d'une commande. -@echo 'hello' - # - signifie que la règle devrait continuer à être exécutée si cette - # commande échoue. + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. -# Un règle peut avoir plusieurs cibles et plusieurs dépendances. -file2.txt fichier3.txt: fichier0.txt fichier1.txt +# Une règle peut avoir plusieurs cibles et plusieurs dépendances. +fichier2.txt fichier3.txt: fichier0.txt fichier1.txt touch fichier2.txt touch fichier3.txt @@ -62,7 +63,7 @@ file2.txt fichier3.txt: fichier0.txt fichier1.txt # Fausses règles #----------------------------------------------------------------------- -# Une fausse règle est un règle qui ne correspond pas à un fichier. +# Une fausse règle est une règle qui ne correspond pas à un fichier. # Par définition, elle ne peut pas être à jour, et donc make l’exécutera à # chaque demande. all: maker process @@ -75,7 +76,7 @@ maker: # suivante : .PHONY: all maker process -# Un règle dépendante d'une fausse règle sera toujours exécutée. +# Une règle dépendante d'une fausse règle sera toujours exécutée. ex0.txt ex1.txt: maker # Voici quelques exemples fréquents de fausses règles : all, make, clean, -- cgit v1.2.3 From 8cff05396eeb7059904c52c3c2e62440d6c975b6 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:16:37 +0100 Subject: Corrected header Added myself as translator. --- fr-fr/make-fr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index b8255ce7..993eccba 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] +translators: - ["altaris", "https://github.com/altaris"] filename: Makefile-fr lang: fr-fr @@ -264,4 +265,4 @@ endif + [Documentation de GNU make](https://www.gnu.org/software/make/manual/), + [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/), + Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) -[ex28](http://c.learncodethehardway.org/book/ex28.html). \ No newline at end of file +[ex28](http://c.learncodethehardway.org/book/ex28.html). -- cgit v1.2.3 From db99c9966ce21789dfa4d6618998ea288756d0ae Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:17:50 +0100 Subject: Corrected header - Added muself as translator; - set lang field; - corrected filename field. --- fr-fr/wolfram-fr.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index d297bd74..3a69e1d8 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -2,8 +2,10 @@ language: wolfram contributors: - ["hyphz", "http://github.com/hyphz/"] +translators: - ["altaris", "http://github.com/altaris/"] -filename: learnwolfram.nb +filename: learnwolfram-fr.nb +lang: fr-fr --- Le langage Wolfram est utilisé dans les programmes suivants : @@ -163,4 +165,4 @@ Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui ## Envie d'aller plus loin ? * [Documentation du langage Wolfram (en anglais)] -(http://reference.wolfram.com/language/) \ No newline at end of file +(http://reference.wolfram.com/language/) -- cgit v1.2.3 From ee88bcd13cf4b89843dde2cf530b832d314d1da7 Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Tue, 19 Jan 2016 11:07:22 +0800 Subject: [xml/id-id] update changes --- id-id/xml-id.html.markdown | 79 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 75 insertions(+), 4 deletions(-) diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown index 8b8d72ae..fedba711 100644 --- a/id-id/xml-id.html.markdown +++ b/id-id/xml-id.html.markdown @@ -5,19 +5,76 @@ contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rizky Luthfianto", "https://github.com/rilut"] + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] lang: id-id --- -XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. +XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. XML mudah dibaca oleh manusia dan mesin. Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya. -* Sintaks XML +Terdapat perbedaan antara **konten** dan **markup**. Singkatnya, konten dapat berupa apapun dan markup adalah sebagai penentu. + +## Definisi dan Pendahuluan + +Dokumen XML pada dasarnya disusun oleh *elemen* yang dapat memiliki *atribut* untuk menjelaskan elemen tersebut dan dapat memiliki beberapa konten tekstual atau beberapa elemen sebagai anak-nya. Setiap dokumen XML hendaknya memiliki satu elemen akar, yang menjadi induk dari semua elemen dalam dokumen XML. + +Pengurai XML dirancang menjadi sangat ketat, dan akan berhenti melakukan penguraian terhadap dokumen yang cacat. Oleh karena itu semua dokumen XML harus mengikuti [Aturan Sintaks XML](http://www.w3schools.com/xml/xml_syntax.asp). ```xml - + + + + + + + +Konten + + + + + + + + + + + + + + + + + + + + + + + Teks + + + + + + + Teks + + +Teks +``` + + +## Dokumen XML +```xml + Everyday Italian @@ -65,7 +122,7 @@ Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, ``` -* Dokumen yang well-formated & Validasi +## Dokumen yang well-formated & Validasi Sebuah dokumen XML disebut well-formated jika sintaksisnya benar. Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen, @@ -128,3 +185,17 @@ Dengan alat ini, Anda dapat memeriksa data XML di luar logika aplikasi. ``` +## Kompatibilitas DTD dan Definisi Skema XML + +Dukungan untuk DTD dapat ditemukan dimana-mana karena sudah sangat lama. Namun sayangnya, fitur XML terkini seperti *namespaces* tidak didukung oleh DTD. XML Xchema Definitions (XSDs) bertujuan untuk mengganti DTD dalam mendefinisikan tatabahasa dokumen XML. + +## Sumber + +* [Validasi dokumen XML](http://www.xmlvalidation.com) + +## Bacaan lainnya + +* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/) +* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp) +* [XML Tutorial](http://www.w3schools.com/xml/default.asp) +* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp) -- cgit v1.2.3 From 0fe63187a9d61a0daa789ff59fc130b5dc678a34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric?= Date: Tue, 19 Jan 2016 11:53:13 +0100 Subject: Corrected typos in wolfram-fr --- fr-fr/wolfram-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index 3a69e1d8..b9fe986f 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -110,7 +110,7 @@ BetterPrintTo[x_] := Module[{y}, (For[y=0, y Date: Tue, 19 Jan 2016 12:36:33 +0100 Subject: More typos --- fr-fr/make-fr.html.markdown | 110 ++++++++++++++++++++++---------------------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 993eccba..b404e1a1 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -37,24 +37,24 @@ l'implémentation standard : GNU make. # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. fichier0.txt: - echo "truc" > fichier0.txt - # Même les commentaires sont transférés dans le terminal. + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. fichier1.txt: fichier0.txt - cat fichier0.txt > fichier1.txt - # Utiliser la même syntaxe que dans un terminal. - @cat fichier0.txt >> fichier1.txt - # @ empêche l'affichage de la sortie texte d'une commande. - -@echo 'hello' - # - signifie que la règle devrait continuer à s'exécuter si cette commande - # échoue. + cat fichier0.txt > fichier1.txt + # Utiliser la même syntaxe que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. # Une règle peut avoir plusieurs cibles et plusieurs dépendances. fichier2.txt fichier3.txt: fichier0.txt fichier1.txt - touch fichier2.txt - touch fichier3.txt + touch fichier2.txt + touch fichier3.txt # Make affichera un avertissement si le makefile comporte plusieurs règles pour # une même cible. Cependant les règles vides ne comptent pas, et peuvent être @@ -71,7 +71,7 @@ all: maker process # La déclaration des règles peut être faite dans n'importe quel ordre. maker: - touch ex0.txt ex1.txt + touch ex0.txt ex1.txt # On peut transformer une règle en fausse règle grâce à la cible spéciale # suivante : @@ -89,17 +89,17 @@ ex0.txt ex1.txt: maker # Utilise un wildcard pour des noms de fichier process: fichier*.txt - @echo $^ # $^ est une variable contenant la liste des dépendances de la - # cible actuelle. - @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles - # multiples, $@ est le nom de la cible ayant causé l'exécution - # de cette règle. - @echo $< # $< contient la première dépendance. - @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. - @echo $+ # $+ contient la liste des dépendances avec d'éventuels - # duplicatas, contrairement à $^. - @echo $| # $| contient la liste des cibles ayant préséance sur la cible - # actuelle. + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. # Même si la définition de la règle est scindée en plusieurs morceaux, $^ # listera toutes les dépendances indiquées. @@ -113,33 +113,33 @@ process: ex1.txt fichier0.txt # En utilisant le pattern matching, on peut par exemple créer des règles pour # convertir les fichiers d'un certain format dans un autre. %.png: %.svg - inkscape --export-png $^ + inkscape --export-png $^ # Make exécute une règle même si le fichier correspondant est situé dans un sous # dossier. En cas de conflit, la règle avec la meilleure correspondance est # choisie. small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ + inkscape --export-png --export-dpi 30 $^ # Dans ce type de conflit (même cible, même dépendances), make exécutera la # dernière règle déclarée... %.png: %.svg - @echo cette règle est choisie + @echo cette règle est choisie # Dans ce type de conflit (même cible mais pas les mêmes dépendances), make # exécutera la première règle pouvant être exécutée. %.png: %.ps - @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents # Make a des règles pré établies. Par exemple, il sait comment créer la cible # *.o à partir de *.c. # Les makefiles plus vieux utilisent un matching par extension de fichier. .png.ps: - @echo cette règle est similaire à une règle par pattern matching + @echo cette règle est similaire à une règle par pattern matching -# Utiliser cette syntaxe pour déclarer une règle comme règle avec matching par -# extension de fichier. +# Utiliser cette règle spéciale pour déclarer une règle comme ayant un +# matching par extension de fichier. .SUFFIXES: .png #----------------------------------------------------------------------- @@ -152,10 +152,10 @@ variable = Ted variable2="Sarah" echo: - @echo $(variable) - @echo ${variable2} - @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! - @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). # Les variables sont déclarées de 4 manières, de la plus grande priorité à la # plus faible : @@ -177,21 +177,21 @@ variable4 +=gris # Assignations de variable pour les règles correspondant à un pattern # (spécifique à GNU make). *.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous - # leurs descendants, la variable variable2 vaudra - # "Sara". + # leurs descendants, la variable variable2 vaudra + # "Sara". # Si le jeux des dépendances et descendances devient vraiment trop compliqué, -# des inconsistances peuvent survenir. +# des incohérences peuvent survenir. # Certaines variables sont prédéfinies par make : affiche_predefinies: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} #----------------------------------------------------------------------- # Variables : le retour @@ -202,11 +202,11 @@ affiche_predefinies: # manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule # fois seulement. -var := wesh -var2 ::= $(var) mec # := et ::= sont équivalents. +var := A B C +var2 ::= $(var) D E F # := et ::= sont équivalents. # Ces variables sont évaluées procéduralement (i.e. dans leur ordre -# d'apparition), contrairement au règles par exemple ! +# d'apparition), contrairement aux règles par exemple ! # Ceci ne fonctionne pas. var3 ::= $(var4) et fais de beaux rêves @@ -225,9 +225,9 @@ fichiers_source = $(wildcard *.c */*.c) fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) #----------------------------------------------------------------------- # Directives @@ -240,14 +240,14 @@ include meuh.mk sport = tennis report: ifeq ($(sport),tennis) # Il y a aussi ifneq. - @echo 'jeu, set et match' + @echo 'jeu, set et match' else - @echo "C'est pas ici Wimbledon ?" + @echo "C'est pas ici Wimbledon ?" endif truc = true -ifdef $(truc) # Il y a aussi ifndef. - machin = 'salut' +ifdef $(truc) # Il y a aussi ifndef. + machin = 'salut' endif ``` -- cgit v1.2.3 From 43c93e3449c2b82bf71529a901034b38077cbcc1 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Tue, 19 Jan 2016 12:38:39 +0100 Subject: Changed indentation to tabs They were converted to spaces by error in previous commit. oups. --- fr-fr/make-fr.html.markdown | 100 ++++++++++++++++++++++---------------------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index b404e1a1..5a1e03e7 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -1,9 +1,9 @@ --- language: make contributors: - - ["Robert Steed", "https://github.com/robochat"] + - ["Robert Steed", "https://github.com/robochat"] translators: - - ["altaris", "https://github.com/altaris"] + - ["altaris", "https://github.com/altaris"] filename: Makefile-fr lang: fr-fr --- @@ -37,24 +37,24 @@ l'implémentation standard : GNU make. # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. fichier0.txt: - echo "truc" > fichier0.txt - # Même les commentaires sont transférés dans le terminal. + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. fichier1.txt: fichier0.txt - cat fichier0.txt > fichier1.txt - # Utiliser la même syntaxe que dans un terminal. - @cat fichier0.txt >> fichier1.txt - # @ empêche l'affichage de la sortie texte d'une commande. - -@echo 'hello' - # - signifie que la règle devrait continuer à s'exécuter si cette commande - # échoue. + cat fichier0.txt > fichier1.txt + # Utiliser la même syntaxe que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. # Une règle peut avoir plusieurs cibles et plusieurs dépendances. fichier2.txt fichier3.txt: fichier0.txt fichier1.txt - touch fichier2.txt - touch fichier3.txt + touch fichier2.txt + touch fichier3.txt # Make affichera un avertissement si le makefile comporte plusieurs règles pour # une même cible. Cependant les règles vides ne comptent pas, et peuvent être @@ -71,7 +71,7 @@ all: maker process # La déclaration des règles peut être faite dans n'importe quel ordre. maker: - touch ex0.txt ex1.txt + touch ex0.txt ex1.txt # On peut transformer une règle en fausse règle grâce à la cible spéciale # suivante : @@ -89,17 +89,17 @@ ex0.txt ex1.txt: maker # Utilise un wildcard pour des noms de fichier process: fichier*.txt - @echo $^ # $^ est une variable contenant la liste des dépendances de la - # cible actuelle. - @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles - # multiples, $@ est le nom de la cible ayant causé l'exécution - # de cette règle. - @echo $< # $< contient la première dépendance. - @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. - @echo $+ # $+ contient la liste des dépendances avec d'éventuels - # duplicatas, contrairement à $^. - @echo $| # $| contient la liste des cibles ayant préséance sur la cible - # actuelle. + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. # Même si la définition de la règle est scindée en plusieurs morceaux, $^ # listera toutes les dépendances indiquées. @@ -113,30 +113,30 @@ process: ex1.txt fichier0.txt # En utilisant le pattern matching, on peut par exemple créer des règles pour # convertir les fichiers d'un certain format dans un autre. %.png: %.svg - inkscape --export-png $^ + inkscape --export-png $^ # Make exécute une règle même si le fichier correspondant est situé dans un sous # dossier. En cas de conflit, la règle avec la meilleure correspondance est # choisie. small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ + inkscape --export-png --export-dpi 30 $^ # Dans ce type de conflit (même cible, même dépendances), make exécutera la # dernière règle déclarée... %.png: %.svg - @echo cette règle est choisie + @echo cette règle est choisie # Dans ce type de conflit (même cible mais pas les mêmes dépendances), make # exécutera la première règle pouvant être exécutée. %.png: %.ps - @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents # Make a des règles pré établies. Par exemple, il sait comment créer la cible # *.o à partir de *.c. # Les makefiles plus vieux utilisent un matching par extension de fichier. .png.ps: - @echo cette règle est similaire à une règle par pattern matching + @echo cette règle est similaire à une règle par pattern matching # Utiliser cette règle spéciale pour déclarer une règle comme ayant un # matching par extension de fichier. @@ -152,10 +152,10 @@ variable = Ted variable2="Sarah" echo: - @echo $(variable) - @echo ${variable2} - @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! - @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). # Les variables sont déclarées de 4 manières, de la plus grande priorité à la # plus faible : @@ -177,21 +177,21 @@ variable4 +=gris # Assignations de variable pour les règles correspondant à un pattern # (spécifique à GNU make). *.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous - # leurs descendants, la variable variable2 vaudra - # "Sara". + # leurs descendants, la variable variable2 vaudra + # "Sara". # Si le jeux des dépendances et descendances devient vraiment trop compliqué, # des incohérences peuvent survenir. # Certaines variables sont prédéfinies par make : affiche_predefinies: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} #----------------------------------------------------------------------- # Variables : le retour @@ -225,9 +225,9 @@ fichiers_source = $(wildcard *.c */*.c) fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) #----------------------------------------------------------------------- # Directives @@ -240,14 +240,14 @@ include meuh.mk sport = tennis report: ifeq ($(sport),tennis) # Il y a aussi ifneq. - @echo 'jeu, set et match' + @echo 'jeu, set et match' else - @echo "C'est pas ici Wimbledon ?" + @echo "C'est pas ici Wimbledon ?" endif truc = true ifdef $(truc) # Il y a aussi ifndef. - machin = 'salut' + machin = 'salut' endif ``` -- cgit v1.2.3 From e3346920d211f19ac651fc6c1618db35f81067ff Mon Sep 17 00:00:00 2001 From: krikmo <616c6c@gmail.com> Date: Tue, 19 Jan 2016 20:54:37 -0200 Subject: [javascript pt-br]: Use articles translated to portuguese --- pt-br/javascript-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 6424214e..59c6890e 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -519,13 +519,13 @@ if (Object.create === undefined){ // Não o sobrescreve se já existir ## Leitura Adicional O [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) dispõe de uma +Network](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript) dispõe de uma excelente documentação sobre Javascript e seu uso nos browsers. E mais, é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando os outros compartilhando do seu conhecimento. [Uma re-introdução do JavaScript pela MDN] -(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +(https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala somente sobre a linguagem JavaScript em si; se você quiser aprender mais sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre @@ -542,5 +542,5 @@ profundo de todas as partes do JavaScript. / livro de referência. Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está -nesse site e do [Tutorial de JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +nesse site e do [Tutorial de JS](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) da Mozilla Developer Network. -- cgit v1.2.3 From 39825e459f11f8c59d0f39afa6418ad1332ec3a4 Mon Sep 17 00:00:00 2001 From: Hanlei Qin Date: Wed, 20 Jan 2016 22:59:48 +0800 Subject: Update lua-cn.html.markdown local variables will better. --- zh-cn/lua-cn.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 098d0ab5..fc0375f5 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -210,7 +210,7 @@ f2 = {a = 2, b = 3} metafraction = {} function metafraction.__add(f1, f2) - sum = {} + local sum = {} sum.b = f1.b * f2.b sum.a = f1.a * f2.b + f2.a * f1.b return sum @@ -273,7 +273,7 @@ eatenBy = myFavs.animal -- 可以工作!感谢元表 Dog = {} -- 1. function Dog:new() -- 2. - newObj = {sound = 'woof'} -- 3. + local newObj = {sound = 'woof'} -- 3. self.__index = self -- 4. return setmetatable(newObj, self) -- 5. end @@ -307,7 +307,7 @@ mrDog:makeSound() -- 'I say woof' -- 8. LoudDog = Dog:new() -- 1. function LoudDog:makeSound() - s = self.sound .. ' ' -- 2. + local s = self.sound .. ' ' -- 2. print(s .. s .. s) end -- cgit v1.2.3 From f39e2fcab76fa0d111195c3b4660b87a101f2032 Mon Sep 17 00:00:00 2001 From: qinhanlei Date: Thu, 21 Jan 2016 16:55:20 +0800 Subject: synchronized with EN version. --- zh-cn/lua-cn.html.markdown | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index fc0375f5..a0acce05 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -91,10 +91,10 @@ until num == 0 -- 2. 函数。 ---------------------------------------------------- -function fib(n) - if n < 2 then return 1 end - return fib(n - 2) + fib(n - 1) -end +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end -- 支持闭包及匿名函数: function adder(x) @@ -129,9 +129,11 @@ function f(x) return x * x end f = function (x) return x * x end -- 这些也是等价的: -local function g(x) return math.sin(x) end -local g; g = function (x) return math.sin(x) end --- 'local g'使得g可以自引用。 +local function g(x) return math.sin(x) end +local g; g = function (x) return math.sin(x) end +-- 以上均因'local g',使得g可以自引用。 +local g = function(x) return math.sin(x) end +-- 等价于 local function g(x)..., 但函数体中g不可自引用 -- 顺便提下,三角函数以弧度为单位。 @@ -328,7 +330,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- 如果有必要,子类也可以有new(),与基类相似: function LoudDog:new() - newObj = {} + local newObj = {} -- 初始化newObj self.__index = self return setmetatable(newObj, self) @@ -340,7 +342,9 @@ end --[[ 我把这部分给注释了,这样脚本剩下的部分可以运行 +``` +```lua -- 假设文件mod.lua的内容类似这样: local M = {} @@ -411,4 +415,9 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us * io library * os library +顺便说一下,整个文件是可运行的Lua; +保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! + +本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 github gist 版. + 使用Lua,欢乐常在! -- cgit v1.2.3 From def04721be506f1c7ff5ddf407f2333999570a89 Mon Sep 17 00:00:00 2001 From: Mark Green Date: Fri, 22 Jan 2016 00:54:44 +0000 Subject: Add a try at an Inform 7 tutorial. Obscure, but really interesting. --- inform7.html.markdown | 195 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 inform7.html.markdown diff --git a/inform7.html.markdown b/inform7.html.markdown new file mode 100644 index 00000000..7f1da0e0 --- /dev/null +++ b/inform7.html.markdown @@ -0,0 +1,195 @@ +--- +language: Inform7 +contributors: + - ["Hyphz", "http://github.com/hyphz/"] +filename: LearnInform.Inform +--- +Inform 7 is a natural language based language created by Graham Nelson and Emily Short for writing text adventures, but also potentially usable for other text based applications, especially data backed ones. + +``` +"LearnInform" by Hyphz + +[This is a comment.] + +[Inform 7 is a language designed for building text adventures. +It can be used for other purposes too, although the default +library builds a text adventure. Inform 7 is object oriented.] + +[This creates a class by subclassing. "Value" is the universal subclass, +but "object" is the most basic that behaves like an OO object.] +A datablock is a kind of object. + +[Classes can have properties.] +A datablock can be broken. [This creates a boolean property.] +A datablock is usually not broken. [This sets its default value.] +A datablock can be big or small. [This creates an enumerated property.] +A datablock is usually small. [This sets its default value.] +A datablock has a number called the sequence number. [This creates a typed property.] +A datablock has some text called the name. ["Some text" means a string.] +A datablock has a datablock called the chain. [Declared classes become types.] + +[This creates a global named instance.] +Block1 is a datablock. +The sequence number of Block1 is 1. +The name of Block1 is "Block One." + +[Functions and procedures are defined as "phrases".] +To do the thing everyone does with their first program: + say "Hello World.". [Full stop indicates the end, indent indicates the scope.] + +To dump (the block - a datablock): [That's how we create a parameter.] + say the sequence number of the block; + say the name of the block; + if the block is broken, say "(Broken)". + +To toggle (the block - a datablock): + if the block is broken: [Conditional.] + now the block is not broken; [Updating a property.] + else: + now the block is broken. + +[Multiple parameters.] +To fix (the broken block - a datablock) using (the repair block - a datablock): + if the broken block is not broken, stop; [Comma for a non indented single command.] + if the repair block is broken, stop; + now the sequence number of the broken block is the sequence number of the repair block; + now the broken block is not broken. + +[Because of its text adventure origins, Inform 7 doesn't generally allow objects +to be created dynamically, although there's a language extension that enables it.] +Block2 is a datablock. +Block2 is broken. +The sequence number of Block2 is 2. +The name of Block2 is "Block two." + +To demonstrate calling a phrase with two parameters: + Let the second block be block2; [Local pointer variable.] + fix the second block using Block1; + say the sequence number of the second block. [1.] + +[Lists.] +To show how to use list types: + let the list be a list of datablocks; + add Block1 to the list; + add Block2 to the list; + say the list; ["Block1 and Block2"] + [Membership.] + if Block1 is listed in the list: + say "Block1 is there."; + [Loop.] + repeat with the block running through the list: + dump the block; [1 Block One. 1 Block Two.] + [Remember block two's sequence number was changed above.] + let X be entry 2 of the list; [Counting starts at 1.] + dump X; ["1 Block two."] + remove X from the list; + say the list. [Block1] + +[Here's how we define a function and do arithmetic.] + +To decide which number is the sum of all numbers up to (X - a number) (this is summing up): + let the total so far be a number; + repeat with the current number running from 1 to X: + now the total so far is the total so far + the current number; + decide on the total so far. [This is the return statement.] + +[ We have higher order functions too. ] + +To demonstrate a higher order function: + say summing up applied to {1, 2, 3, 4}. + +To decide which number is the result of applying (phrase - phrase A -> A) twice to (B - a value of kind A): + let b1 be phrase applied to B; + let b2 be phrase applied to b1; + decide on b2. + +To demonstrate defining a higher order function: + let X be 5; + say the result of applying summing up twice to X. + +[ Rulebooks allow a number of functions which apply to the same type under different conditions to be stacked. ] + +Datablock validation rules is a datablock based rulebook. + +A datablock validation rule for a broken datablock: rule fails. +A datablock validation rule for a datablock (called the block): + dump the block; + rule succeeds. + +To demonstrate invoking a rulebook: + follow datablock validation rules for Block1; + follow datablock validation rules for Block2. + +[ Objects can also have relations, which resemble those in a relational database. ] +A dog is a kind of thing. +Rover is a dog. +The kennel is a container. [This is a built in base class.] +Rover is in the kennel. [This creates an inbuilt relation called "containment".] + +[We can create relations by declaring their type.] + +Guide dog ownership relates one dog to one person. [One-to-one.] +Property ownership relates various things to one person. [Many-to-one.] +Friendship relates various people to various people. [Many-to-many.] + +[To actually use them we must assign verbs or prepositions to them.] + +The verb to own means the property ownership relation. +The verb to be the guide dog of means the guide dog ownership relation. +The verb to be guided by means the reversed guide dog ownership relation. +The verb to be friends with means the friendship relation. + +Edward is a person. A person can be blind. Edward is blind. +Edward is guided by Rover. +Benny is a person. Edward is friends with Benny. + +To demonstrate looking something up with a relation: + repeat with the dog running through things that are the guide dog of Edward: + say the dog; + repeat with the friend running through things that are friends with Edward: + say the friend. + +[We can also define relations that exist procedurally.] + +Helpfulness relates a person (called the helper) to a person (called the helpee) when the helpee is blind and the helper is not blind. +The verb to be helpful to means the helpfulness relation. +To demonstrate using a procedural relation: + repeat with the helper running through people that are helpful to Edward: + say the helper. + + +[ Interface to the text adventure harness to allow the above code to be run. ] +Tutorial room is a room. +"A rather strange room full of buttons. Push them to run the exercises, or turn on the robot to run them all." +A button is a kind of thing. A button is fixed in place. + +The red button is a button in tutorial room. +Instead of pushing the red button, do the thing everyone does with their first program. +The green button is a button in tutorial room. +Instead of pushing the green button, demonstrate calling a phrase with two parameters. +The blue button is a button in tutorial room. +Instead of pushing the blue button, show how to use list types. +The cyan button is a button in tutorial room. +Instead of pushing the cyan button, say the sum of all numbers up to 5. +The purple button is a button in tutorial room. +Instead of pushing the purple button, demonstrate a higher order function. +The black button is a button in tutorial room. +Instead of pushing the black button, demonstrate defining a higher order function. +The white button is a button in tutorial room. +Instead of pushing the white button, demonstrate invoking a rulebook. +The puce button is a button in tutorial room. +Instead of pushing the puce button, demonstrate looking something up with a relation. +The orange button is a button in tutorial room. +Instead of pushing the orange button, demonstrate using a procedural relation. + +The robot is an object in tutorial room. +Instead of switching on the robot: + say "The robot begins to frantically flail its arms about."; + repeat with button running through buttons in the tutorial room: + say "The robot randomly hits [the button]."; + try pushing button. +``` + +##Ready For More? + +* [Inform 7](http://www.inform7.com/) -- cgit v1.2.3 From 4d1b90826f7625fc5fb438b3581866e2d33f7e99 Mon Sep 17 00:00:00 2001 From: Hanlei Qin Date: Fri, 22 Jan 2016 11:01:28 +0800 Subject: Update lua-cn.html.markdown change link to Markdown style. --- zh-cn/lua-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index a0acce05..f7065445 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -418,6 +418,6 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us 顺便说一下,整个文件是可运行的Lua; 保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! -本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 github gist 版. +本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [github gist](https://gist.github.com/tylerneylon/5853042) 版. 使用Lua,欢乐常在! -- cgit v1.2.3 From a3e68ea324716f1f018888782b357812be3865a2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:31:17 +0100 Subject: Transleted code variables and strings to french --- fr-fr/wolfram-fr.html.markdown | 116 ++++++++++++++++++++--------------------- 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index b9fe986f..ea07aae5 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -57,101 +57,101 @@ x (* 20 *) (* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des variables non déclarées n'est pas illégal *) -cow + 5 (* 5 + cow, comme cow n'est pas déclarée, l'évaluation +truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation s'arrête là *) -cow + 5 + 10 (* 15 + cow, on évalue ce qu'on peut... *) -% (* 15 + cow, % représente le dernier résultat *) -% - cow (* 15, les variables non déclarées peuvent quand même +truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *) +% (* 15 + truc, % représente le dernier résultat *) +% - truc (* 15, les variables non déclarées peuvent quand même s'annuler *) -moo = cow + 5 (* Attention : moo est ici une expression et non un nombre *) +chose = truc + 5 (* Attention : chose est ici une expression et non un nombre *) (* Déclaration d'une fonction *) -Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme - à droite *) -Double[10] (* 20 *) -Double[Sin[Pi/2]] (* 2 *) -Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets - fermants si moches *) -(Pi/2) // Sin // Double(* 2, Utiliser // permet d'écrire les fonctions dans - l'ordre d'appel *) +Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme + à droite *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets + fermants si moches *) +(Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans + l'ordre d'appel *) (* Pour la programmation impérative, utiliser ; pour séparer les expressions *) -MyFirst[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires - car ; est prioritaire sur := *) -MyFirst[] (* Hello World *) +Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires + car ; est prioritaire sur := *) +Salut[] (* Hello World *) (* Boucles For à la C *) -PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Crée une table associative *) -myHash[["Green"]] (* 2, l'utilise *) -myHash[["Green"]] := 5 (* 5, la modifie *) -myHash[["Puce"]] := 3.5 (* 3.5, l'étend *) -KeyDropFrom[myHash, "Green"] (* Supprime la clé "Green" *) -Keys[myHash] (* {Red} *) -Values[myHash] (* {1} *) +table = <|"Vert" -> 2, "Rouge" -> 1|> (* Crée une table associative *) +table[["Vert"]] (* 2, l'utilise *) +table[["Vert"]] := 5 (* 5, la modifie *) +table[["Bleu"]] := 3.5 (* 3.5, l'étend *) +KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *) +Keys[table] (* {Rouge} *) +Values[table] (* {1} *) (* Pour finir, toute bonne démonstration du langage Wolfram contient un Manipulate ! *) -- cgit v1.2.3 From 3ea060e936b4260ab57abfee6de9dabc3232d6fd Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:32:02 +0100 Subject: Corrected code results in comments In subsection on hash tables. --- fr-fr/wolfram-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index ea07aae5..9cdbabcc 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -150,8 +150,8 @@ table[["Vert"]] (* 2, l'utilise *) table[["Vert"]] := 5 (* 5, la modifie *) table[["Bleu"]] := 3.5 (* 3.5, l'étend *) KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *) -Keys[table] (* {Rouge} *) -Values[table] (* {1} *) +Keys[table] (* {Rouge, Bleu} *) +Values[table] (* {1, 3.5} *) (* Pour finir, toute bonne démonstration du langage Wolfram contient un Manipulate ! *) -- cgit v1.2.3 From 2b3d1e524d483e647fd6a193d6b17808d67af5ab Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:37:15 +0100 Subject: Some improvments in comments --- fr-fr/wolfram-fr.html.markdown | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index 9cdbabcc..7b446259 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -33,22 +33,21 @@ formatage, car il ne contient aucune information de mise en page. 5+8 (* 13 *) (* Appels de fonction *) -(* Le langage Wolfram est sensible à la casse *) Sin[Pi/2] (* 1 *) - (* Syntaxe alternative pour les appels de fonction à 1 paramètre *) Sin@(Pi/2) (* 1 *) (Pi/2) // Sin (* 1 *) -(* Dans le langage Wolfram, toutes les expressions sont en réalité des appels de - fonction *) +(* Attention : le langage est sensible à la casse ! *) + +(* Toutes les expressions sont en réalité des appels de fonction *) Times[2, 2] (* 4 *) Plus[5, 8] (* 13 *) (* Utiliser une variable pour la première fois la déclare globalement *) x = 5 (* 5 *) x == 5 (* True, l'assignation et le test d'égalité est écrit comme - dans le C *) + en C *) x (* 5 *) x = x + 5 (* 10 *) x (* 10 *) @@ -56,7 +55,7 @@ Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *) x (* 20 *) (* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des - variables non déclarées n'est pas illégal *) + variables non déclarées est légal *) truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation s'arrête là *) truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *) @@ -75,18 +74,18 @@ Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets (Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans l'ordre d'appel *) -(* Pour la programmation impérative, utiliser ; pour séparer les expressions *) +(* En programmation impérative, utiliser ; pour séparer les expressions *) Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires car ; est prioritaire sur := *) Salut[] (* Hello World *) (* Boucles For à la C *) Compter[x_] := For[y=0, y