Markdown02.docx <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown02.docx"
Research_map.docx <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Research_map and guide.docx"
Markdown01.docx <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown01.docx"
Notes <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/"
All_notes_draft.qmd <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/All_notes_draft.qmd"
All_notes.qmd <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/All_notes.qmd"
All.md <- "/Users/marcelorosales/Box Sync/Github/mkdocs/MBA03/docs/All.md"
quarto_All.xlsx <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/quarto_All.xlsx"
Excel_best_tricks.xlsx <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Excel best tricks.xlsx"
#open in mac OS
system(paste("open", shQuote(Markdown02.docx)))
system(paste("open", shQuote(Research_map.docx)))
system(paste("open", shQuote(Notes)))
system(paste("open", shQuote(All_notes_draft.qmd)))
system(paste("open", shQuote(All_notes.qmd)))
system(paste("open", shQuote(All.md)))
system(paste("open", shQuote(quarto_All.xlsx)))
system(paste("open", shQuote(Excel_best_tricks.xlsx)))All_notes
This file github
Relevant files
Mac:
Windows:
file_path <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown01.docx"
shell(paste("start", shQuote(file_path)))
# or
system(paste("start", shQuote(file_path)))It is possible to sync files with in sys with the rsync command (no external apps needed)
source <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/All_notes_draft.qmd"
destination <- ""
system(paste("rsync -avh --progress", shQuote(source), shQuote(destination)))sync try # 33
/Users/marcelorosales/Documents/GitHub/Quarto/quarto-trials/quarto_website/qt01.csvAll Notes
docx2md_test.docx
Does Decalcification speed.docx
GeneExpression analysis.docx
R Graph Notes.docx
R Graph Notes.docx
R Markdown notes.docx
R Markdown notes.docx
rmarkdown-brew.docx
rmarkdown-brew.docx
Untitled2.docx
Untitled03.docx
Untitled04.docx
reference-keys.txt
mkdocs.yml
deforges.pdf
Introductory R example chapters.pdf
Introductory R example chapters.pdf rmarkdown-2.0.pdf
rmarkdown-2.0.pdf
rmarkdown-cheatsheet.pdf
rmarkdown-cheatsheet.pdf
teachR.pdf
teachR.pdf
Untitled.pdf
Images:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean efficitur placerat arcu, sed feugiat ex ultrices vitae.
!\[My Image\](path/to/image.jpg){.float-left}
Duis sed fringilla purus. Mauris pellentesque ullamcorper justo id ullamcorper. Vestibulum finibus, mauris ac eleifend accumsan, tortor enim finibus nulla, sit amet rutrum ipsum nisl eu nunc.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus et posuere mi. Sed euismod nunc ut turpis fermentum bibendum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean efficitur placerat arcu, sed feugiat ex ultrices vitae.
Terminal, coding R&D
(code not shown??) html code: warning call out.
note: do not insert spaces between the div’s, it will break continuity and block will not be display or displayed incorrectly. MOVE THIS SECTION TO QUARTO CALL OUTS…
<div style= "border: 1px solid transparent;
border-color: transparent;
margin-bottom: 10px;
border-radius: 4px;
color: #000000;
background-color: #eeeee;
border-color: #ebccd1;">
<div style = "padding: 5px;
border: 1px solid transparent;
border-color: transparent;
border-radius: 4px;
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;">
warning
</div>
<div style="padding: 5px;">
The Bash_profile customization is obsolete now!!.
</div>
</div>
All the html div tags (above) is automatically converted to quarto blocks by render command and/or by changing from source to visual, as seen below.
warning
The Bash_profile customization is obsolete now!!.
Powerlevel9k/powerlevel9kPublic archive
Now Using the Powerlevel10k
https://youtu.be/zNg9Y1gentY
https://youtu.be/XVSZAwTXtAs
https://youtu.be/WoMiRHXzCfE
Set up for coding and development
(macOS 2022 edition)
Original post here > Customise .zsh with Powerlevel10K.
I was inspired by this guide, but I reconfigured my setup significantly with Powerlevel10k. In the previous version I used Powerlevel9k theme.
Powerlevel10k theme
Install for >_ & iTerm2 Updated version
requires git and Xcode.
Save a copy of original .zshrc!! Each machine has a different zshrc file ∵ user path is different in each manchine, just in case
MBP20: /Users/marcelorosales/Box Sync/Github/DotFiles/MBP20/Conda_shells/zshrcMBP15:Install iTerm2
brew install --cask iterm2echo $0 #(if >_ != -zsh {brew install zsh}, else {})
brew install zshInstall Oh My Zsh:
sh -c "$(curl -fsSL <https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh>)"or
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"or
sh -c "$(wget https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh -O -)"Icons/font not displaying correctly? https://github.com/romkatv/powerlevel10k/issues/671
- Download these four ttf files: MesloLGS NF Regular.ttf > ~/Box/Github/DotFiles/iTerm2/Fonts
- Double-click on each file and click “Install” (Fonts will be added to Font Book).
Then…
- Terminal fix.:
//Preferences > Profile > Text > Change > …[]… > Collection:© All fonts > Family: © > MesloLGF Regular - iTerm fix:
//Preferences > Profile > Text > Font > MesloLGF Regular - Visual Studio Code config Fonts
//settings (Cmd + ,) > find (Cmd +F): {Terminal font | Terminal integrated font family} > { MesloLGS NF }
- Change .zshrc theme to Agnoster (iterm default)
code ~/.zshrc || open ~/.zshrc- Change: ZSH_THEME=“~/.oh-my-zsh” => ZSH_THEME=“agnoster” > save > exit (>_ and iterm2)
- Costum iterm2 color scheme: download flat-colors: https://github.com/QuentinWatt/dark-flat-iterm-colors/blob/master/flat-colors.itermcolors -> ~/Box Sync/Github/DotFiles/iTerm2/flat-colors.intermcolors
- iterm > Preferences > Profiles > Colors > Color pressets > import : lat-colors.intermcolors
Install Powerlevel9k / Powerlevel10k: (auto to: ~/oh-my-zsh/custom/themes/powerlevel10k)
git clone <https://github.com/romkatv/powerlevel10k.git> $ZSH_CUSTOM/themes/powerlevel10kChange .zshrc theme to Powerlevel10k (iterm default)
code ~/.zshrc || open ~/.zshrcChange: ZSH_THEME=“agnoster” => ZSH_THEME=“powerlevel10k/powerlevel10k” > save > exit (>_ and iterm2)Re-start terminal or Start a new terminal session/re-configure prompt:
- p10k configure # 1st time = auto run
- y > y > y > Rainbow > unicode > 24-hour format > Angled > sharp > Flat > one line > compact > Many icons > Concise > Transient Prompt: No > Verbose > ! Overwrite ~/.p10k.zsh (only if powerlevel10k is already installed) > Apply changes to ~/.zshrc? Yes (close open ~/.zshrc) > end.
# New config:
~/.p10k.zsh.
# Backup of ~/.zshrc:
$TMPDIR/.zshrc.EM433MEB1C.
# See ~/.zshrc changes:
diff $TMPDIR/.zshrc.EM433MEB1C ~/.zshrc - For even more customization:
code ~/.p10k.zsh.
Other addons
- Auto suggestions (for Oh my zsh)
- Just follow these steps: https://github.com/zsh-users/zsh-autosuggestions/blob/master/INSTALL.md#oh-my-zsh
- Syntax highlighting
brew install zsh-syntax-highlightingActivate the plugin in
~/.zshrcfile:code ~/.zshrc> copy/paste:source /usr/local/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zshIf the message “highligthers directory not found” is displayed:
code ~/.zshenv> copy/paste:
export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=/usr/local/share/zsh-syntax-highlighting/highlighters
- if >_ or/and iTerm2 console output is produced during zsh initialization (see: instant prompt error) in terminal type:
compaudit | xargs chmod g-w,o-w
Install iTerm2
brew install --cask iterm2Install zsh
echo $0 #(if >_ != -zsh {brew install zsh}, else {})Install Oh My Zsh:
sh -c "$(curl -fsSL <https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh>)"Install Powerlevel9k / Powerlevel10k: (!! + x code tools)
git clone <https://github.com/romkatv/powerlevel10k.git> $ZSH_CUSTOM/themes/powerlevel10kChange: ZSH_THEME
code ~/.zshrc # open ~/.zshrcChange: ZSH_THEME=“~/.oh-my-zsh” |“agnoster” => ZSH_THEME=“powerlevel10k/powerlevel10k” > save > exit (>_ and iterm2)
p10k configure #auto run
Summary
Summary: from kevin-smets/iterm2-solarized.md
- Install iterm2
- Install Oh My Zsh
- Install Powerlevel9k / Powerlevel10k
- Install patched fonts
- Further tweaking
- auto suggestions
- word jumping with arrow keys / natural text editing
- syntax highlighting
- visual studio code config
- Paste Conda Initialize code at the head/End of .zshrc
1. Install iterm2
brew install --cask iterm2` iTerm2 has better color fidelity than the built in Terminal, so your themes will look better.
Get the iTerm color settings
- Solarized Dark theme (patched version to fix the bright black value)
- Solarized Light theme
- More themes @ iterm2colorschemes
Just save it somewhere and open the file(s). The color settings will be imported into iTerm2. Apply them in iTerm through iTerm → preferences → profiles → colors → load presets. You can create a different profile other than Default if you wish to do so.
Apply the color scheme in iTerm2
iTerm → Preferences → Profiles → Colors → Color presets → ImportThen again, Color presets → you-color-scheme-name
2. Install Oh My Zsh
Install with curl
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" When the installation is done, edit ~/.zshrc and set ZSH_THEME=“agnoster” for the default look. Or better yet, go for Powerlevel10k.
3. Install Powerlevel9k / Powerlevel10k
Why Powerlevel10k? faster to render your prompt.
Powerlevel10k look with added info such as exit codes and timestamps:
git clone https://github.com/romkatv/powerlevel10k.git $ZSH_CUSTOM/themes/powerlevel10k Cloning into ‘/Users/Marcelo-Rosales/.oh-my-zsh/custom/themes/powerlevel10k’…
Then edit your ~/.zshrc and set ZSH_THEME="powerlevel10k/powerlevel10k".
-> Terminal// code ~/.zshrc > find: { ZSH_THEME} > ZSH_THEME=“powerlevel10k/powerlevel10k”
Start a new terminal session, Powerlevel10 configure wizard will be launched to set your prompt, beware, there are many many options! check its project page.
To re-configure prompt:
To trigger the configuration wizard immediately, runp10k configure options are plentiful.
To customize even more edit your ~/.zshrc > open in vs code ~/.zshrc > go to bottom section: # To customize prompt, run p10k configure or edit ~/.p10k.zsh. code ~/.p10k.zsh.
4. Install a patched FONTS
The patched font is the font used by iTerm2 to display characters, and you’ll need a special one for special characters like arrows and git icons.
You’ll get this result at the end, keep calm and follow this doc
Download and install the font
- Meslo (recommanded, ie the one in the screenshot). Click “view raw” to download the font (usually .ttf file double click file in finder to install).
- Source Code Pro has better alignment for the glyphs @14px.
- Others powerline fonts
-> Open the downloaded font and press “Install Font” on your computer.
If you did not go with Powerlevel10k or you want another font, read on:
- Source Code Pro
- Source Code Pro + Font Awesome, this one is needed if you want the icons from Font Awesome as shown in the screenshot for Powerlevel10k.
- Others @ powerline fonts
Open the downloaded font and press “Install Font”.
Set this font in iTerm2 (iTerm → Preferences → Profiles → Text → Font), in the dropdown select the desired Font. You will see it change on the fly.
Restart iTerm2 for all changes to take effect.
5. Further tweaking
Things like
- auto suggestions
- word jumping with arrow keys / natural text editing
- syntax highlighting
- visual studio code config
can be found in the section below.
a. Auto suggestions (for Oh My Zsh)
Just follow these steps: https://github.com/zsh-users/zsh-autosuggestions/blob/master/INSTALL.md#oh-my-zsh
- Clone this repository into $ZSH_CUSTOM/plugins (by default ~/.oh-my-zsh/custom/plugins)
git clone <https://github.com/zsh-users/zsh-autosuggestions> ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions- Add the plugin to the list of plugins for Oh My Zsh to load (inside ~/.zshrc):
plugins=(
# other plugins...
zsh-autosuggestions
)If the auto suggestions do not appear to show, it could be a problem with your color scheme.
Under “iTerm → Preferences → Profiles → Colors tab”, check the value of Black Bright, that is the color your auto suggestions will have. It will be displayed on top of the Background color. If there is not enough contrast between the two, you won’t see the suggestions even if they’re actually there.
b. Enable word jumps and word deletion, aka natural text selection
By default, word jumps (option + → or ←) and word deletions (option + backspace) do not work. To enable these, go to “iTerm → Preferences → Profiles → Keys → Key mappings → Presets… → Natural Text Editing → Boom! Head explodes”
c. Syntax highlighting
Clone the repository:
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting Activate the plugin in ~/.zshrc:
plugins=( [plugins...] zsh-syntax-highlighting) Or brewinstall:
brew install zsh-syntax-highlighting When finish installing, read message. It will tell you to “add the following to the .zshrc”:
source /usr/local/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh If the message “highligthers directory not found message”, you may need to add the following to the .zshenv file:
export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=/usr/local/share/zsh-syntax-highlighting/highlighters Restart iTerm2 for all changes to take effect.
Troubleshooting
Terminal and VS code Terminal prompt issues
Icons and font not displaying correctly?
If icons don’t display in Terminal or VS code integrated terminal after setting terminal.integrated.fontFamily see : https://github.com/romkatv/powerlevel10k/issues/671
- Terminal fix:
//Preferences » Profile » Font » Change > …[]… > Collection:© All fonts > Family: © > MesloLGF Regular
- iTerm fix:
//Preferences > Profile > Text > Font > MesloLGF Regular
Visual Studio Code config Fonts
Installing a patched font will mess up the integrated terminal in VS Code unless you use the proper settings. You’ll need to go to settings (CMD + ,) and add or edit the following values: see 4. Install a patched font
- for Source Code Pro + Font Awesome: “terminal.integrated.fontFamily”: “‘SourceCodePro+Powerline+Awesome Regular’”. The single quotes are important!
- Restart VS Code after the config change.
- for Source Code Pro: “terminal.integrated.fontFamily”: “Source Code Pro for Powerline”
- for Meslo: “terminal.integrated.fontFamily”: “Meslo LG M for Powerline”
- -> settings (Cmd + ,) > find (Cmd +F): {Terminal font | Terminal integrated font family} > { MesloLGS NF }
- for other fonts you’ll need to check the font name in Font Book. You can right click on them on select “Show in Finder” to get the exact name.
You can also set the fontsize e.g.: “terminal.integrated.fontSize”: 14
- for Source Code Pro + Font Awesome: “terminal.integrated.fontFamily”: “‘SourceCodePro+Powerline+Awesome Regular’”. The single quotes are important!
6. Paste Conda Initialize code at the head of .zshrc
For MBP15:
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/Marcelo-Rosales/opt/anaconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/Users/Marcelo-Rosales/opt/anaconda3/etc/profile.d/conda.sh" ]; then
. "/Users/Marcelo-Rosales/opt/anaconda3/etc/profile.d/conda.sh"
else
export PATH="/Users/Marcelo-Rosales/opt/anaconda3/bin:$PATH"
fi
fi
unset __conda_setup
# <<< conda initialize <<<
# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATHFor MBP20
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/usr/local/Caskroom/miniconda/base/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/usr/local/Caskroom/miniconda/base/etc/profile.d/conda.sh" ]; then
. "/usr/local/Caskroom/miniconda/base/etc/profile.d/conda.sh"
else
export PATH="/usr/local/Caskroom/miniconda/base/bin:$PATH"
fi
fi
unset __conda_setup
# <<< conda initialize <<<Instant Prompt Message error.
Last login: Tue Jul 12 23:09:32 on ttys000
When using Powerlevel10k with instant prompt, console output during zsh initialization may indicate issues.
You can:
Recommended: Change ~/.zshrc so that it does not perform console I/O after the instant prompt preamble. See the link below for details.
- You will not see this error message again.
- Zsh will start quickly and prompt will update smoothly.
Suppress this warning either by running p10k configure or by manually defining the following parameter:
typeset -g POWERLEVEL9K_INSTANT_PROMPT=quiet- You will not see this error message again.
- Zsh will start quickly but prompt will jump down after initialization.
Disable instant prompt either by running p10k configure or by manually defining the following parameter:
typeset -g POWERLEVEL9K_INSTANT_PROMPT=off- You will not see this error message again.
- Zsh will start slowly.
Do nothing.
- You will see this error message every time you start zsh.
- Zsh will start quickly but prompt will jump down after initialization.
For details, see: https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt
– console output produced during zsh initialization follows –
[oh-my-zsh] Insecure completion-dependent directories detected: (This directories were found to be insecure.) drwxrwxr-x 3 marcelorosales admin 96 May 9 2021 /usr/local/share/zsh drwxrwxr-x 6 marcelorosales admin 192 Jun 26 16:05 /usr/local/share/zsh/site-functions
[oh-my-zsh] For safety, we will not load completions from these directories until you fix their permissions and ownership and restart zsh.
[oh-my-zsh] See the above list for directories with group or other writability.
[oh-my-zsh] To fix your permissions you can do so by disabling the write permission of “group” and “others” and making sure that the owner of these directories is either root or your current user.
[oh-my-zsh] The following command may help:
compaudit | xargs chmod g-w,o-w[oh-my-zsh] If the above didn’t help or you want to skip the verification of insecure directories you can set the variable ZSH_DISABLE_COMPFIX to “true” before oh-my-zsh is sourced in your zshrc file.
Solution: type
compaudit | xargs chmod g-w,o-wAll messages will disappear with this.
Old version 1: https://youtu.be/pTW02GMeI74
Configuration of a beautiful (efficient) terminal and prompt on OSX in 7minutes
Summary:
- Install Hombrew
- Install and configure iTerm2
- Install a patched font
- Install Zsh and Oh my Zsh
- Add Powerlevel9k Zsh Theme
- Final tweaking
- shorter prompt
- enable text editor navigation
- auto suggestions
- syntax highlighting
- new line after each prompt
- change color of warning git status
- change Iterm2 tabs color
1. Install and configure iTerm2
brew cask install iterm2Choose your Iterm2 color scheme
- you can use Clovis’ iTerm2 color scheme file 🎁 (the one in the screenshot)
- or scroll many opensource iTerm2 color schemes here
- … and download your desired preset’s file here
2. Install a patched font
The patched font is the font used by iTerm2 to display characters, and you’ll need a special one for special characters like arrows and git icons.
You’ll get this result at the end, keep calm and follow this doc
Download and install the font
- Meslo (recommanded, ie the one in the screenshot). Click “view raw” to download the font.
- Source Code Pro has better alignment for the glyphs @14px.
- Others powerline fonts
Open the downloaded font and press “Install Font” on your computer.
Add the font in iTerm2
(font size of 12pt is our personal preference)
iTerm2 → Preferences → Profiles → Text → Change Font
[img]
3. Install Zsh and Oh my Zsh
Zsh is a shell that provides many features, like better files and folders navigation. To install it :
brew install zsh zsh-completions Oh my Zsh is a Zsh configuration framework, you can read more here: github.com/robbyrussell/oh-my-zsh.
To install it :
sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" 💡In the next steps you’ll need to edit the ~/.zshrc configuration file which is run when the terminal starts. At any time you can compare it with Clovis .zshrc configuration file 🎁
4. Add Powerlevel9k Zsh Theme
The Powerlevel9k zsh theme adds many other features like a right promp with infos such as exit codes and timestamps. To install it run :
git clone https://github.com/bhilburn/powerlevel9k.git ~/.oh-my-zsh/custom/themes/powerlevel9k Then edit ~/.zshrc configuration file and set
ZSH_THEME="powerlevel9k/powerlevel9k" Boom. Powerlevel9k offers a whole lot more, best is to follow the next steps or check out these user made configs.
5. Final tweaking
- shorter prompt
- enable text editor navigation
- auto suggestions
- syntax highlighting
- new line after each prompt
- change color of warning git status
- change Iterm2 tabs color
Obsolete section!!.
Bash_profile Setup
Tip for this section:
The first and easiest method is using Mac Finder to show hidden files (like .bash_profile or .bashrc file):.
- Open the folder where you want to search hidden files.
- Press the “Command + Shift + .”…
- The hidden files will show up as translucent/shadow in the folder.
- If you want to obscure the files again, press the same “Command + Shift + .”
top
Customizing Your Terminal:
- How to: Install and use homebrew (why?: To automate program installation and programs settings. Install all programs in one go. Using dot files.
- Customize Terminal. Taken from the Linux/Mac Tutorials collection @ Corey Schafer
Customizing Your Terminal: .bash_profile and .bashrc files.
https://youtu.be/vDOVEDl2z84?list=PL-osiE80TeTvGhHkpvfmKWOiIPF8UVy6c
To customize our terminal, we are going to create several .bash files (whether with R or VS). If you have other customized bash file move them to another folder (ex. DotFile) and restart terminal (al customization will disappear).
- Bash_profile: This is a login shell. Usually mac uses longing shell when opening terminal. So normally open terminal and it will echo FROM BASH_PROFILE.
- Bashrc: Is a file for none login shells. For linux?. In “terminal” run bash to create a subshell. After running this line, mac terminal will echo FROM BASHRC. Having 2 files for logging and non-login shells is cumbersome since we will have to modify both each time when customizing.
A way around this problem is to a simple trick which will allow us to modify just a single file and it will be applied to all our shells.
To do this, call your bashrc file from the bash_profile file.
- Create bash files in terminal:
touch .bash_profile,touch .bashrc(mind the containing folder). Or create the files in Editor (Visual studio).
warning: shellscript language (.sh files) is the language for .bash files, but when saved, it saves as .sh, therefore is better to create them with terminal.
- Open the files in a text editor (VS, atom, R, etc).
- in the bash_profile file and type:
#To see from which file is teminal running the code, echo the file name.
echo "FROM BASH_PROFILE" and in the bashrc file:
echo "FROM BASHRC " Next in the profile_bash file, we call the .bashrc. as the “code source” into the bash_profile. So.. if a .bashrc exist, then run the code from that file (.bashrc) instead of this file (.bash_profile).
#to modify just a single file for all our shells, call your bashrc file from with in the bash_profile file.
if [ -f ~/.bashrc]; then
source ~/.bashrc
fi
#Now we can write all our code in the bashrc file and not really have to worry about modifying our bash_profile file anymore. Now we can do all our customizations on the bashrc file.
#Code for the bashrc file:
#To change the promt name for example:
PS1="custom-> ";If we reopen terminal it will show “FROM BASHRC” in the login shell. Type and run: bash to reopen as a none login shell and it will show again “FROM BASHRC” confirming that in both shells, the code from the bashrc file is been used and the promp name will also change.
So.. from now on will be modifying only the bashrc file….
Adding Color and Information to Your Prompt.
Customizing Your Terminal: Adding Color and Information to Your Prompt
Now, let’s customize our prompt name
#Code for the bashrc file:
#To change the promt name for example to just an arrow:
PS1="-> ";
export PS1;Save the file. To see the changes in the terminal, you can
- Close terminal and reopen. Or
- run the new code with
source .bashrcin Terminal.
Now let’s add some dynamic information using special characters:
Ex 1. To show the user name…. “username ->”
(In mac word the ¥ is the backslash) in Terminal it displays correctly).
#Code for the bashrc file:
#To change the promt name for example + dinamic information (user) ""
PS1="\u-> ";
export PS1;Then the prompt will show your username.
List of special characters:
u user name.
h the hostname up to the first .
s the name of the shell.
t the current time in 24hr format.
u the username of the current user.
w the current working directory.
W the basename of the current working directory.
Ex 2. If we would like a prompt like:
username@hostname directory ->“.
#Code for the bashrc file:
#To change the promt name for example + dinamic information (user) ""
PS1=" u@ h W -> ";
export PS1;
# In terminal reload using: source .bashrcTo add color to the text depending on the dynamic info:
Remember: in “my word” the ¥ is backslash in VS
#Code for the bashrc file:
#To change the promt name for example + dinamic information (user)
PS1=" u@ h W -> ";
export PS1;
#To change the promt name + dinamic information + color based on dinamic info.
# 1. Assing colors to tput and command substitution.
# $() # Command substitution ex.: echo "Your current directory is $(pwd)".
# setaf # Sets color of background. 166 is the color orange in the 256 color chart.
# Ex.: "$(tput setaf 166)This is orange".
PS1="$(tput setaf 166) u@ h W -> ";
export PS1; # This will change the color of prompt but also all the text diplayed in Terminal.
# 2. We need to specify whe color begins and ends.
# $(tput sgr0) # Resets the formating.
PS1="$(tput setaf 166) u@ h W -> $(tput sgr0)";
export PS1; # Change color of prompt and reset color at the end of prompt.
# 3. To add more colors, place a tput before each dinamic info.
PS1="$(tput setaf 166) u$(tput setaf 228)@ h$(tput setaf 71) W -> $(tput sgr0)";
export PS1; # Change color of for each dinamic info and reset color at the end of prompt.
# This way of coding makes lines long an difficult to see.
# To organize, add "PS1+=" at the beginning of each line and write the command.
PS1="$(tput setaf 166) u"; # Orange user.
PS1+="$(tput setaf 228)@ h"; # yellow Host.
PS1+="$(tput setaf 71) W"; # green working directory.
PS1+="$(tput sgr0)"; # reset color.
export PS1; # Save and reload. For some reason ? the promp and cursor position is miss placed.
# 4. To correct the prompt missplacement problem.
# Use the special escape? characters commad in every tput command: [ ]
PS1=" [$(tput setaf 166) ] u"; # Orange user.
PS1+=" [$(tput setaf 228) ]@ h"; # yellow Host.
PS1+=" [$(tput setaf 71) ] W"; # green working directory.
PS1+=" [$(tput sgr0) ]"; # reset color.
export PS1; # Save and reload. promp and cursor position is corrected.
# 5. To make it more easy to code, we can specify each tput command as a variable.
orange= $(tput setaf 166);
yellow= $(tput setaf 228);
green= $(tput setaf 71);
white= $(tput setaf 15);
bold= $(tput setaf bold);
reset= $(tput sgr0);
PS1=" [${bold} ] n";
PS1+=" [${orange}] u"; # Orange user.
PS1+=" [${white} ] at";
PS1+=" [${yellow} ] h"; # yellow Host.
PS1+=" [${white} ] in";
PS1+=" [${green} ] W"; # green working directory.
PS1+=" n"; # n is a new line
PS1+=" [${white} ]$ [${reset} ]"; # $ white and reset color.
export PS1;
# To reload in terminal: source .bashrc10 How To Use and Modify Dotfiles
Customizing Your Terminal: How To Use and Modify Dotfiles
Customizing Terminal takes a lot of time and effort. A better and reliable way to do it is by using files already done by other more capable developers that share their customization with the community. In this case we can use the GitHub does dotfiles page. In particular the Mathias Bynens’s dotfiles(MBs dotfiles), I download the repository zipfile to this folder unzip and open the .bashrc and the .bash_profile.
Previously we use the “.bashrc” file as the main file for modifying shell profile, but in this repository, they do the opposite and use the “.bash_profile” as main file and call-in the “.bashrc” file.
In the .bash_profile from MBs,
To understand the code commands and checks, in terminal use:
man testNow you can check all the files. Open at
We can also the CoreyMSchafer/dotfiles (CMSs dotfiles)
11 How I Setup a New Development Machine - Using Scripts to Automate Installs and Save Time.
How I Setup a New Development Machine - Using Scripts to Automate Installs and Save Time
To make a file executable in Terminal, whether is a .bash file or a .sh file. In Terminal type:
chmod +x scriptname.shHow to install dotfiles. Outdated
Dotfiles are outdated, bash files no longer used
All these procedures are for bash shell, obsolete for the new zsh shell. Use to customize RStudio Termina only ‼
Summary of the procedure.
- Find dotfile repo, check and modify code for custom prompt and brew installation files. Files:
- install.sh: Executable, where I modify installation procedures.
- bash_profile: Gather all custom .bash scripts and source them.
- bashrc.
- bash_server_prompt.
- bash_prompt: Custom prompt color.
- brew.sh or brewfile: May is better to use the dump command for auto brewfile.
From Github:
- Git clone dotfiles repo into home directory.
- Run install.sh
- For .bashfiles symlinks will be created in home dir and auto source.
- Restart †Terminal (bash shell) or RStudio terminal.
- Custom prompt will be displayed.
∵ changes and modifications are made on git > commit and pushed, will apply to all devices at once.
From Folder:
- Copy the dotfile directory to homedir.
- Run install.sh
- .bashfiles symlinks will be created in homedir and auto sourced.
- Restart †Terminal (bash shell) or RStudio terminal.
- Custom prompt will be displayed.
∵ changes and modifications will have to be made manually for each device every time. It is NOT an ideal way to it.
From Cloud Sync Service (Box Sync):
- Copy the dotfile directory to Box Sync directory.
- Run install.sh
- .bashfiles symlinks will be created in homedir and auto source.
- Restart †Terminal (bash shell) or RStudio terminal.
- Error in the installing.
- Symlinks path DO NOT point/target to Box Sync dir.
- Idea: Create folder in homedir. Create symlinks to Box Sync.
- Error: Too many levels of symbolic links.
- As of this posting, Box can’t handle symlinks.
- Path with spaces are problematic as string variable.
∵ installation was unsuccessful.
> Try on other Sync Services like Google or iCloud or OneDrive.
- Dotfiledir in iCloud > install.sh with symlinks to icloud folder (mod install.sh, !.bashfile to .bashfile slink)>
- Create alias dir of Dotfiledir (slink) > move alias dir to homedir > install.sh (carefull if .bashfile or !.bashfile).
Bash dotfiles install
Detail installation procedure of bash dotfiles:
Requirements: (See brew and git sections for detail information).
- Homebrew; download from https://brew.sh/
- Git must be installed.
- To make sure it is type in terminal:
git(git manual should display, if not install) or- `git –version’ (the version number will be display).
- If not installed install from https://git-scm.com/book/en/v2/Getting-Started-Installing-Git.
Download the “dotfile” directory from the git hub repository (if you have one. In general it is recommended).
This will create a folder in the home directory called ‘dotfiles’ with all the files required.
- If not: Create or copy/paste a directory ’dotfiles` containing all the files.
Go to terminal. > Go to dotfiles folder.
cd path/to/dotfile/folder/- Run the install file: through terminal. (you need to be in the same folder as the install.sh file).
./install.sh path/to/home/directoryThis will create the files (symlinks) into the home directory.
If the error:
-bash: ./file.name: Permission deniedIs ∵ you are trying to execute a file which you do not have permission to run.
To fix this issue, use the chmod u+x command to give yourself permissions. more info here
#| eval: false
chmod u+x example.shThen, run installation again
./install.sh path/to/home/directoryIt will create the symlinks and run and install the brew file programs. (may take a while).
However, If executing install.sh form other directory than ‘dotfiles’ created by git, the symlinks will do not directed to the right folder.
To check symlink path:
> //Finder > R© > Get Info > …[]… Original: /path/to/original/file <- if path is incorrect, change manually in terminal.
How to change where a symlink points [duplicate]
Can you change what a symlink points to after it is created?
ln -sfn source/file/or/directory/name softlink/name
Eg.
ln -sfn path/to/original/file/.bash_profile .bash_profile (∵ we are in home directory) or
ln -sfn path/to/original/file/MRR-bash_prompt .bash_prompt (target file is not a .bash file) *Ø source file, original file, targeted file are all synonyms in this case.
# create symlinks (will overwrite old dotfiles)
# Careful!! bash: /Users/marcelorosales/.bash_profile: Too many levels of symbolic links!!!! As of this posting, Box can’t handle symlinks.
for file in ${files}; do
echo "Creating symlink to $file in home directory."
# ln -sf ${dotfiledir}/.${file} ${homedir}/.${file} # Original Links will be created in the ${homedir}
ln -sf ${dotfiledir}/.${file} ${homedir}/.${file} # Original -> target
doneSymbolic Links
(aka Symlinks) on a Mac
To create a symbolic link on a Mac, you’ll need to use the Terminal app. Run the ln command in the following form. You can specify either a path to a directory or file:
#| eval: false
ln -s /path/to/original /path/to/link
ln -s /path/of/original/file /path/to/target/dir
ln -s "/path/of/original/file" "/path/to/target/dir/{filename}"The -s here tells the ln command to create a symbolic link. If you want to create a hard link, you’d omit the -s. Most of the time symbolic links are the better choice, so don’t create a hard link unless you have a specific reason for doing so.
Here’s an example. Let’s say you wanted to create a symbolic link in your Desktop folder that points to your Downloads folder. You’d run the following command:
#| eval: false
ln -s /Users/name/Downloads /Users/name/DesktopAfter creating the link, you’d see your Downloads folder appear on your desktop. It’s actually the symbolic link you created, but it will look like the real thing. This folder will appear to contain all the same files as your Downloads folder. That’s because it does—they’re just different views pointing to the same underlying directory on the file system.
If your file path contains spaces or other special characters, you’ll need to enclose it in quotation marks. So, if you wanted to create a link on your desktop to a folder named “My Files” inside your user directory, you’d need something like the following command:
#| eval: false
ln -s "/Users/name/My Files" "/Users/name/Desktop/My Link"To ease typing file and directory paths into the Terminal, you can drag-and-drop a folder from the Finder window into the Terminal and the Terminal will automatically fill in the path to that folder. It will enclose the path in quotation marks if necessary, too.
If you need to create a symbolic link in a system location your user account doesn’t have access to, you’ll need to prefix the ln command with the sudo command, like so:
#| eval: false
sudo ln -s /path/to/original /path/to/link !!! note
Bear in mind that, on modern versions of macOS, you won’t be allowed to write to certain system locations without changing a low-level firmware option due to the System Integrity Protection feature. You can disable that feature, but we recommend that you don’t.
RELATED: How to Disable System Integrity Protection on a Mac (and Why You Shouldn’t)
Update a symlink
Aliases vs. Symbolic links
Mac OS X has two types of aliases. The traditional aliases, and symbolic links (derived from UNIX).
Aliases are linked to the file or folder they point to. This means that if you move the original file to a new location, the alias follows it and is still linked to it.
Symbolic links refer to a specific pathway. Thus, a symbolic link to a file called Testing in your Documents folder will only work if the file remains in that folder location. Move it and the link is broken. On top of that, if you move the file and create a different one with the same name in the original location, the symbolic link will now point to that file (since it has the same pathway). Both methods have their advantages and disadvantages.
Aliases and symbolic links are both used to create shortcuts or references to files or folders, but they function differently and have different characteristics:
Aliases:
- Aliases are specific to the macOS operating system.
- They are created using the Finder interface by right-clicking on a file or folder and selecting “Make Alias.”
- Aliases are small files that contain references to the original file or folder.
- Aliases can be moved, renamed, or deleted without affecting the original file or folder.
- Aliases retain their functionality even if the original file or folder is moved or renamed.
- Aliases are resolved by the operating system and can be accessed by any application.
- Aliases can be recognized by their distinctive arrow icon.
Symbolic Links:
- Symbolic links (symlinks) are available on various operating systems, including macOS, Linux, and Windows (with limitations).
- They are created using the command-line interface or the file manager interface.
- Symlinks are special files that contain the path to the original file or folder.
- Symlinks can be moved, renamed, or deleted without affecting the original file or folder.
- If the original file or folder is moved or renamed, the symlink may break and become invalid.
- Symlinks are transparent to applications and appear as if they were the original file or folder.
- Symlinks can be recognized by the “shortcut arrow” icon on Windows or a “symlink” badge on macOS.
In summary, aliases are specific to macOS and are created using the Finder, while symbolic links are available on multiple operating systems and are typically created using the command-line interface. Aliases are small files that retain their functionality regardless of the original file or folder’s location, while symlinks are special files that may break if the original file or folder is moved or renamed.
how to crate symlinks in Box sync
Creating symbolic links (symlinks) within Box Sync is not directly supported by the Box Sync application. Box Sync is designed to synchronize files and folders between your local computer and your Box account, but it does not provide native functionality for creating symlinks.
However, you can manually create symlinks outside of the Box Sync folder and then place the symlinked files or folders inside the Box Sync folder. Here’s how you can do it:
- Identify the file or folder you want to symlink.
- Create the symlink using the appropriate method for your operating system:
- Windows: You can create symlinks using the
mklinkcommand in Command Prompt or PowerShell. - macOS/Linux: You can create symlinks using the
lncommand in the terminal.
- Windows: You can create symlinks using the
- Once the symlink is created, you can move it into the Box Sync folder.
- Box Sync will recognize the symlinked file or folder and synchronize it with your Box account as if it were a regular file or folder.
Keep in mind that the behavior of symlinks within Box Sync may vary depending on the operating system and Box Sync version. It’s recommended to test the setup and ensure that the symlinks are working as expected.
Note: Creating symlinks requires appropriate permissions on your system. Make sure you have the necessary privileges to create symlinks and manage files and folders in your operating system.
#| eval: false
ln -s "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/All_notes.qmd" "/Users/marcelorosales/Documents/GitHub/Quarto/quarto-trials/quarto_website/All_notes_smlk.qmd"Symlinks and synology
On a Synology NAS, you can create symbolic links (symlinks) using the command-line interface (CLI) or through the DSM (DiskStation Manager) web interface. Here’s how you can create symlinks on a Synology NAS:
- Using the CLI:
- Connect to your Synology NAS via SSH or use the built-in Terminal in the DSM web interface.
- Navigate to the location where you want to create the symlink.
- Use the
lncommand to create the symlink. For example, to create a symlink named “symlink_name” pointing to “target_path”, use the following command:
ln -s target_path symlink_name- The symlink will be created in the specified location.
- Using the DSM web interface:
- Open the File Station app in the DSM web interface.
- Navigate to the folder where you want to create the symlink.
- Right-click on an empty area and select “Create” > “Symbolic Link”.
- Enter the path to the target folder/file in the “Link to” field.
- Provide a name for the symlink in the “Link name” field.
- Click “Create” to create the symlink.
Please note that creating symlinks may require administrative privileges on the Synology NAS. Also, keep in mind that the behavior and support for symlinks may vary depending on the specific model and version of the Synology NAS and the DSM software you are using. It’s recommended to consult the Synology documentation or support resources for more specific information related to your NAS model.
Symlinks Results
As mention in From Cloud Sync Service (Box Sync):
- Symlinks path DO NOT point/target to Box Sync dir.
- Error: Too many levels of symbolic links.
- As of this posting, Box can’t handle symlinks.
- Path with spaces are problematic as string variable.
- Idea: Create folder in homedir. Create symlinks to Box Sync.
∵ installation was unsuccessful.
Sync files
How to Use the rsync Command | Linux Essentials Tutorial
Syntax: rsync -[options] source destination
rsync -av source destination rsync -av –dry-run source destination #Sync simulation, not actual syncing
rsync -av var/log root@139.177.195.158:/mnt/backup # sync data for local server to another server. (you need rsync installed in the destination server) root@139.177.195.158’s password: #will ask the password for the server.
Linux/Mac Terminal Tutorial: How To Use The rsync Command - Sync Files Locally and Remotely
rsync Original/* Backup/ # does not sync sub folders rsync -r Original/ Backup/ # sync all data including sub dir into destination. rsync -r Original Backup/ # sync the folder including sub dir into destination. rsync -av –dry-run Original/ Backup/ # simulation of the file and folders to be sync.
If you add more files to the Original folder and re-run command, it will copy only the new/modify files/folders. If you add more files to the Backup folder and re-run command, it will copy only the new/modify data and add files in destination.
rsync -av –delete –dry-run Original/ Backup/ # Will delete added files in destination. rsync -zaP ~/path/to/source name@192.168.56.100:~/path/to/destination # sync data to a server (will ask for password)
Sync two files in mac OS
On macOS, you can sync two files using various methods, depending on your specific needs and preferences. Here are a few common approaches:
- Using the Finder:
- Open a Finder window and locate the source file you want to sync.
- Select the source file and press
Command+Cto copy it. - Navigate to the destination location where you want to sync the file.
- Press
Command+Vto paste the file. If the file already exists at the destination, you will be prompted to replace it or merge the contents.
- Using the Terminal and
rsync:Open Terminal (Applications -> Utilities -> Terminal).
Use the
rsynccommand to sync files. For example, to syncfile1.txtfrom the source folder to the destination folder, use the following command:rsync -avh --progress /path/to/source/file1.txt /path/to/destination/The
-avhoptions preserve file attributes and enable verbose mode, while--progressdisplays the progress of the sync process.
- Using third-party synchronization software:
- There are various third-party applications available for file synchronization on macOS, such as Dropbox, Google Drive, or Resilio Sync. These tools provide more advanced syncing capabilities and often include features like automatic syncing, real-time collaboration, and cloud storage integration.
Choose the method that suits your specific requirements, whether you prefer a manual approach through the Finder, utilizing the command-line power of rsync, or using dedicated syncing software.
Schedule rsync on mac
To schedule an rsync command to run at specific times or intervals on macOS, you can use the built-in cron or launchd utilities. Here’s a step-by-step guide on how to set up a scheduled rsync task:
Using cron: 1. Open Terminal on your macOS (Applications -> Utilities -> Terminal). 2. Type crontab -e to open the cron file for editing. 3. If prompted to select an editor, choose your preferred text editor (e.g., nano, vim). 4. In the cron file, add a new line specifying the schedule and the rsync command. For example, to run rsync every day at 10:00 AM:
0 10 * * * rsync -avh --progress /path/to/source/ /path/to/destination/Adjust the rsync options, source path, and destination path as needed. 5. Save the file and exit the editor. 6. cron will now execute the rsync command at the scheduled time.
Using launchd: 1. Open a text editor (e.g., TextEdit) on your macOS. 2. Create a new XML file with the following content, replacing the placeholders with your specific information:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.example.rsyncsync</string>
<key>ProgramArguments</key>
<array>
<string>rsync</string>
<string>-avh</string>
<string>--progress</string>
<string>/path/to/source/</string>
<string>/path/to/destination/</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer>10</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
</dict>
</plist>Adjust the rsync options, source path, destination path, and the Hour and Minute values in <StartCalendarInterval> as needed. 1. Save the file with a .plist extension, such as rsyncsync.plist. 2. Open Terminal on your macOS (Applications -> Utilities -> Terminal). 3. Type sudo mv /path/to/rsyncsync.plist /Library/LaunchDaemons/ to move the .plist file to the appropriate directory. 4. Type sudo chown root:wheel /Library/LaunchDaemons/rsyncsync.plist to set the correct ownership and permissions for the file. 5. Type sudo launchctl load /Library/LaunchDaemons/rsyncsync.plist to load the launchd job. 6. launchd will now execute the rsync command at the scheduled time.
Note: When using cron or launchd, ensure that the paths to the rsync executable and the source/destination files/folders are correctly specified. Also, make sure you have the necessary permissions to access the files/folders and run the rsync command.
Please exercise caution when scheduling tasks and ensure that the rsync command is tested and functioning correctly before setting it up for automatic execution.
how to trigger sync with rsync as soon as original file is modify?
To trigger a sync with rsync as soon as the original file is modified, you can use the --update option along with the --delete option to keep the destination in sync with the source. Here’s an example command:
rsync -avh --progress --update --delete /path/to/source/ /path/to/destination/Explanation of options: - -avh: Enables archive mode (preserves file attributes), displays verbose output, and shows the progress of the sync. - --update: Skips files that are newer in the destination, effectively syncing only modified or new files. - --delete: Deletes files in the destination that don’t exist in the source, ensuring an exact match between the source and destination.
When you run this command, rsync will compare the timestamps of the files in the source and destination. It will only transfer files that have been modified or are new since the last sync. The --delete option ensures that any files in the destination that no longer exist in the source will be removed.
You can include this command in a script or a scheduled task (such as using cron or launchd) to run it periodically or at specific intervals. This way, the sync will be triggered automatically whenever there are modifications to the original file.
Schedule commands with crontabs
Linux/Mac Tutorial: Cron Jobs - How to Schedule Commands with crontab
Function to make symlinks.
See R ans Rstudio section.
ln -s /path/to/original /path/to/link
# upadate:
ln -s "/Users/name/My Files" "/Users/name/Desktop/My Link"- Choose a file
- choose a folder
- create symlink <In r there is a command already.>
- paste name of original file
In Terminal
pwd
cd /Users/rosalesrocabadomarcelo/Documents/GitHub/tests
pwd
touch test.txt
ls
#rm test.txt
#lstheSelectedFile="$(osascript -l JavaScript -e 'a=Application.currentApplication();a.includeStandardAdditions=true;a.chooseFile({withPrompt:"Please select a file to process:"}).toString()')"
echo "Selected file: $theSelectedFile"Terminal Commands
| Comand » | Action |
|---|---|
| ls » | list of all files in a folder |
| ls -al » | list of files + all attributes (.files) + long form |
| touch » | Creates new file. |
| chmod -x » | Makes a file executable eg. .bash_profile, install.sh. |
| ./ » | Execute a file. Eg. ./ install.sh |
| mkdir » | Make directory. |
| cd | Change directory. |
| q » | To quit man commands |
| cont+c » | To stop running commands. |
Html table
Note: § Make Sure that content text is in the correct indentation. $ Must be not spaces between the html code, otherwise it will break code continuity and html will be not be display correctly.
html code can be written (copy/paste) directly into the code sheet without the need of code block, this is because md file can read html natively, however, in quarto there are still many conflicts and bugs that disrupt correct display. In the following section, tabe goes over the margin constraing set in quarto and over expands in webpage. Therefore, the html code will be confined to a code block so it wont be display as table but as code only.
<table>
<caption>Author Details</caption>
<col width=50%>
<col width=50%>
<tr> <!-- table row 1 Start-->
<th>Col 1</th> <!-- table head 1 -->
<th>Col2</th> <!-- table head 2 -->
</tr><!-- table row 1 End -->
<tr>
<td> <!-- Data cell element -->
<pre> <!-- The Preformatted Text element Start (Makes text appear exactly as written in html, eg. shape or drawing with letters)-->
**Shortcuts for Terminal/Unix**
Tab » Auto-complete file and folder names.
Ctrl + A » Go to the beginning of the line you're currently typing on.
Ctrl + E » Go to the end of the line you're currently typing on.
Ctrl + U » Clear the line before the cursor.
Ctrl + K » Clear the line after the cursor.
Ctrl + W » Delete the word before the cursor.
Ctrl + T » Swap the last two characters before the cursor.
Esc + T » Swap the last two words before the cursor.
Ctrl + L » Clear the screen.
Ctrl + C » Kill whatever you're running.
Ctrl + D » Exit the current shell.
Option + → » Move cursor one word forward.
Option + ← » Move cursor one word backward.
Ctrl + F » Move cursor one character forward.
Ctrl + B » Move cursor one character backward
Ctrl + Y » Paste whatever was cut by the last command
Ctrl + Z » Puts whatever you're running into a suspended background process
Ctrl + _ » Undo the last command
Option + Shift + Cmd + C » Copy plain text
Shift + Cmd + V » Paste the selection
exit » End a shell session
</pre>
</td>
<td>
<pre> <!-- The Preformatted Text element Start (Makes text appear exactly as written in html, eg. shape or drawing with letters)-->
**Basics**
/ (Forward Slash) » Top level directory
. (Single Period) » Current directory
.. (Double Period) » Parent directory
~ (Tilde) » Home directory
sudo [command] » Run command with the security privileges of the super user
nano [file] » Opens the Terminal editor
open [file] » Opens a file
[command] -h » Get help about a command
man [command] » Show the help manual of the command
**Change Directory**
cd » Home directory
cd [folder] » Change directory, e.g. cd Documents
cd ~ » Home directory
cd/ » Root of the drive
cd - » Previous directory or folder you last browsed
pwd » Show your working directory
cd.. » Move up to the parent directory
cd../.. » Move up two levels
</pre>
</td>
</tr>
</table>In case it can not be displayed in html
Shortcuts for Terminal/Unix
Tab » Auto-complete file and folder names.
Ctrl + A » Go to the beginning of the line you’re currently typing on.
Ctrl + E » Go to the end of the line you’re currently typing on.
Ctrl + U » Clear the line before the cursor.
Ctrl + K » Clear the line after the cursor.
Ctrl + W » Delete the word before the cursor.
Ctrl + T » Swap the last two characters before the cursor.
Esc + T » Swap the last two words before the cursor.
Ctrl + L » Clear the screen.
Ctrl + C » Kill whatever you’re running.
Ctrl + D » Exit the current shell.
Option + → » Move cursor one word forward.
Option + ← » Move cursor one word backward.
Ctrl + F » Move cursor one character forward.
Ctrl + B » Move cursor one character backward Ctrl + Y » Paste whatever was cut by the last command Ctrl + Z » Puts whatever you’re running into a suspended background process Ctrl + _ » Undo the last command Option + Shift + Cmd + C » Copy plain text Shift + Cmd + V » Paste the selection exit » End a shell session
Basics
/ (Forward Slash) » Top level directory
. (Single Period) » Current directory
.. (Double Period) » Parent directory
~ (Tilde) » Home directory
sudo [command] » Run command with the security privileges of the super user
nano [file] » Opens the Terminal editor open [file] » Opens a file
[command] -h » Get help about a command
man [command] » Show the help manual of the command
Change Directory
cd » Home directory
cd [folder] » Change directory, e.g. cd Documents
cd ~ » Home directory
cd/ » Root of the drive
cd - » Previous directory or folder you last browsed
pwd » Show your working directory
cd.. » Move up to the parent directory
cd../.. » Move up two levels
Commands Cheat sheet
Terminal/Unix Commands Cheat Sheet. Plain List
Shortcuts
Tab » Auto-complete file and folder names.
Ctrl + A » Go to the beginning of the line you’re currently typing on.
Ctrl + E » Go to the end of the line you’re currently typing on.
Ctrl + U » Clear the line before the cursor.
Ctrl + K » Clear the line after the cursor.
Ctrl + W » Delete the word before the cursor.
Ctrl + T » Swap the last two characters before the cursor.
Esc + T » Swap the last two words before the cursor.
Ctrl + L » Clear the screen.
Ctrl + C » Kill whatever you’re running.
Ctrl + D » Exit the current shell.
Option + → » Move cursor one word forward.
Option + ← » Move cursor one word backward.
Ctrl + F » Move cursor one character forward.
Ctrl + B » Move cursor one character backward Ctrl + Y » Paste whatever was cut by the last command Ctrl + Z » Puts whatever you’re running into a suspended background process Ctrl + _ » Undo the last command Option + Shift + Cmd + C » Copy plain text Shift + Cmd + V » Paste the selection exit » End a shell session Basics
/ (Forward Slash) » Top level directory . (Single Period) » Current directory .. (Double Period) » Parent directory ~ (Tilde) » Home directory sudo [command] » Run command with the security privileges of the super user nano [file] » Opens the Terminal editor open [file] » Opens a file [command] -h » Get help about a command man [command] » Show the help manual of the command
Change Directory
cd » Home directory
cd [folder] » Change directory, e.g. cd Documents
cd ~ » Home directory
cd/ » Root of the drive
cd - » Previous directory or folder you last browsed
pwd » Show your working directory
cd.. » Move up to the parent directory
cd../.. » Move up two levels
List Directory Contents
ls » Display the name of files and subdirectories in the directory
ls -C » Force multi-column output of the listing
ls -a » List all entries including those with .(period) and ..(double period)
ls -1 » Output the list of files in one entry per line format
ls -F » Display a / (slash) immediately after each path that is a directory, * (asterisk) after executable programs or scripts, and @ after a symbolic link
ls -S » Sort files or entries by size
ls -l » List in a long format. Includes file mode, owner and group name, date and time file was modified, pathname, and more
ls -l / » List of the file system from root with symbolic links
ls -lt » List the files sorted by time modified (most recent first)
ls -lh » Long listing with human readable file sizes in KB, MB, or GB
ls -lo » List the file names with size, owner, and flags
ls -la » List detailed directory contents, including hidden files
File Size and Disk Space
du » List usage for each subdirectory and its contents
du -sh [folder] » Human readable output of all files in a directory
du -s » Display an entry for each specified file
du -sk* | sort -nr » List files and folders, totaling the size including the subfolders. Replace sk* with sm* to list directories in MB
df -h » Calculate your system’s free disk space
df -H » Calculate free disk space in powers of 1,000 (as opposed to 1,024).
File and Directory Management
mkdir
mkdir -p
mkdir
mkdir “
rmdir
rm -R
touch
cp
cp
cp
cp -R
cp -i
cp
ditto -V [folder path][new folder] » Copy the contents of a folder to new folder. In here “-V” print a line of status for every file copied
rm
rm -i
rm -f
rm
mv
mv
mv -i
mv *.png ~/
Command History
Ctrl + R » Search through previously used commands
history n » Shows the previous commands you’ve typed. Add a number to limit to the last n items
[value] » Execute the last command typed that starts with a value
!! » Execute the last command typed
Permissions
ls -ld » Display the default permission for a home directory
ls -ld/
chmod 755
chmod -R 600
chown
Processes
ps -ax » Output currently running processes. Here, a shows processes from all users and x shows processes that are not connected with the Terminal
ps -aux » Shows all the processes with %cpu, %mem, page in, PID, and command
top » Display live information about currently running processes
top -ocpu -s 5 » Display processes sorted by CPU usage, updating every 5 seconds
top -o rsize » Sort top by memory usage
kill PID » Quit process with ID
ps -ax | grep
Network
ping
whois
curl -O
ssh
scp
arp -a » View a list of all devices on your local network. It will show you the IP and MAC address of all the devices
ifconfig en0 » View your device IP and MAC address
traceroute [hostname] » Identify the path and the hops traversed by the packets from your device to the destination address
Homebrew
brew doctor » Check brew for potential problems
brew help » List of useful homebrew formula and cask commands
brew install
brew uninstall
brew list –formula » List only installed formulas
brew list –cask » List only installed cask
brew deps
brew search text|/regex/ » Search formula or cask through regex
brew upgrade
brew outdated
brew outdated –formula » Search for outdated formula
brew outdated –cask » Search for outdated cask
brew pin [installed_formula] » Pin a formula from getting upgraded
brew unpin [installed_formula] » Unpin to upgrade a package
brew cleanup » Remove stale lock files and outdated packages for all formula and casks.
Environment Variable or Path
printenv » Display a list of currently set environment variables. Also tells you which shell you’re using
$echo » Tells the terminal to print something and show it to you
echo $PATH » Check the value of the PATH variable which storea a list of directories with executable files
echo $PATH >path.txt » Export the path directory to a text file
export PATH=$PATH:absolute/path to/program/ » Execute a program via terminal only in your current session. If you use a program regularly, add the path to shell configuration file.
Search
find
grep “
grep -rl “
Output
cat
less
head
Command Line Help in the Mac OS X Terminal.
man (command) » Manual page for (command). eg: man ls whatis (command) »One line brief summary of specified command. eg: whatis ls
(command) –help » Display command usage information including available flags and proper syntax. eg: ls –help
apropos (string) » Searches the whatis database for (string), helpful in finding commands. eg: apropos ssh
(command)+tab key » Autocomplete, or to list available commands that start with the typed prefix.
q » exit help.
List2.
Handy word keyboard shortcuts for windows and Mac
Bash scripting.
Bash key commands:
All code in terminal. cd, ls, clear or cnt+L, cat,
- To show all shells available in system:
cat /etc/shells - To Tell What Shell Your Mac is Using: (2 ways)
echo $0
which bashMBP20:
/bin/bash; /bin/csh; /bin/dash; /bin/ksh; /bin/sh; /bin/tcsh; /bin/zsh.
- How to switch between shells in macOS? : Simply type the shell name on the prompt. Ex.
#| eval: false
(username@~ % bash) The default interactive shell is now zsh. If not….
- To update your account to use zsh, run
chsh -s /bin/zsh For more details, on how to change via system preferences see here.
- To create a file. Use the command
touchand the name of the file. Ex.
touch scriptname.sh
touch .bash_profile- To make a file executable (-x)
chmod +x filename.~- To execute file “./” file name and enter.
./ filename.~ Redirect to file.
- To make an executable file create a new file.
# In the -x file (filename.~).
echo "Hello bash in terminal" > newfilename.~
# echo prints the mensage
# > creates a file (filename.~) with the message echoed. Execute filename.~ and a new file will be created in the pwd (present/print working directory).
- Create file from -x file and use terminal as editor.
cat > newfilename.~ # Use terminal as editor. * over writes old newfilename.~
cat > newfilename.~ # Use terminal as editor. * This appends (adds to the end) into newfilename.~Comments.
- To add comments.
# Single line comment.
:'
Multi
line
comment'- To show comments in the output. Use the heredoc delimiter. Any text can be used as delimiter.
cat << AnyTextDelimiter
Text to be display,
even if it is
multy line.
AnyTextDelimiter Complete this later…
Table 1: Built-in shell variables.
Variable Use.
#| eval: flase
$# Stores the number of command-line arguments that were passed to the shell program.
$? Stores the exit value of the last command that was executed.
$0 Stores the first word of the entered command (the name of the shell program).
$* Stores all the arguments that were entered on the command line ($1 $2 ...).
"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...). Batch Cask Installer
How to Create A Batch Cask Installer for Homebrew (Using a Simple Bash Script).
# Create bash file in the Home directory.
pwd
ls
#Create the file "caskinstall.sh" or just "caskinstall".
touch caskinstall.sh
# Open the new file created with a text editor. vim, nano, atom, VS, etc.
# At the top type a "shebang": "#!/usr/bin/env bash" or "#!/bin/env bash"
#!/usr/bin/env bash
echo "Updating Casks..."
# Save the file.
# Make the file executable with chmod in Terminal (not in text editor).
# In Terminal
chmod +x caskinstall.sh
# Execute/Run the file, if run correctly prompt will display "updating Cask..."
./ caskinstall.sh
# In Editor (file) create a variable.
# Create a variable "CASK=()" Basically all the code is as follows Note: the #!/usr/bin/env bash is called a shrap bang (or shebang?), is not a comment, it is a declaration of the language we are using.
To se where is the bash type in terminal:
which bashusually the answer is /bin/bash.
Full code.
#!/usr/bin/env bash
echo "Updating Casks..."
CASK=(
appName1
appName2
etc
)
brew cask install ${CASK[@]}
echo "Updating Complete!" # Place the name of all the app to be install, run the file and all the programs will be automatically install or updated.
# In terminal.
brew cask list
# List will be displayed. copy/paste the list into the variable brackets in editor.
# Run the file. It will install the apps.
./ caskinstall.sh To make the created file (caskinstall.sh) executable.
- Delete the extension: caskistall.sh > caskinstall.
- make the file executable with the chmod.
Chmod +x caskinstall - To run file. 2x© caskinstall in finder or ./caskinstall in terminal.
Table 1: Built-in shell variables.
link.
Variable Use
$# Stores the number of command-line arguments that were passed to the shell program.
$? Stores the exit value of the last command that was executed.
$0 Stores the first word of the entered command (the name of the shell program).
$* Stores all the arguments that were entered on the command line ($1 $2 ...).
"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).
Resize Multiple Images (Mac >_ )
Easily Resize Multiple Images Using the Mac Terminal
# Search for the folder/dir containing the images
ls
cd ~/ImageDir/OrigSizeDir/
# The following command will erase/modify the original images, and save them in the same folder.
sips -Z 640 *.jpg
# -Z Manteins the aspect ratio, 640 pixel is the size of pics wanted, *.jpg= all jpg files,
# The following command will copy, modify and paste the resulting images in a new folder.
sips -Z 300 *.jpg --out ~/path/to/new/folder
# To rename the new img created.
# 1. Got to the dir where the images are located.
# 2. type the followin command.
find . -type f -exec bash -x 'mv "$0" "${0% .jpg}-300.jpg"' {} ;
# Find all the files, .= in this folder, ${0% .jpg}= disregard the extension of the file, -300.jpg= add 300.jpg to the file name. Resize multiple images (resize img batch) in >_:
- Create new folder, copy/paste all img to be changed.
- In >_ use the sis¥ps command
sips -Z 600 *.jpg!!! danger
Original files will be changed, NO undo option available.
sips: sips command is used to query or modify raster image files (JPG/GIF/PNG) and ColorSync ICC profiles. Image processing options include flip, rotate, change image format/width/height. Its functionality can also be used through the “Image Events” AppleScript suite.
-Z: Maintain aspect ratio.
600: output width? size in pixels.
*.jpg: files to modify, in this case, all .jpg files in the current directory.
sips -Z 600 *.jpg --out ~/new/dir/path/and/nameThis will create a new directory, make a copy of the files, modify size and save in the new directory.
Rename all the files (rename batch) in >_: 1. Go to the directory containing files. 2. run command:
find . -type f -exec bash -c `mv “$0” “${0% .jpg}-300.jpg”` {} ;find all the files in the current directory of this type of files
then, execute this command ? ? disregard the extension .jpg and add the suffix: -300.jpg
Small Script to auto resize
#| eval: false
#!/bin/bash
# Change format, and change max size. 20181231 DM
oldFormat=HEIC
newFormat=png
newSize=800
for i in *.$oldFormat
do
sips --setProperty format $newFormat --resampleHeightWidthMax $newSize "$i" --out "${i%$oldFormat}"$newFormat
done
exit 0Rename batch files.
Step By Step: Using The Mac Batch Rename Tool
- Select all files you want to rename.
- Finder// File> Rename..Items > …[]… Rename Finder items: Find= text_to_find Replace with= Text_to_replace
**Rename all the files (rename batch) in >_: (not working, permission error)**
- Go to the directory containing files.
- run command:
find . -type f -exec bash -c `mv “$0” “${0% .jpg}-300.jpg”` {} ;find all the files
. in the current directory
-type of this type of files
-exec bash then, execute this command in bash?
-c ?
mv ?
“\(0” “\){0% .jpg} disregard the extension .jpg
-300.jpg”` {} ; and add the suffix: -300.jpg
!!! failure bash: ./03-Molar-1000x684.jpg: Permission denied
//[Layout] > ˇMargins > Custom margins >..[].. > Grid >
Brew (Terminal)
Homebrew Tutorial: Simplify Software Installation on Mac Using This Package Manager
- 1st install command line tools. (Do this through Xcode).
xcode-select --installIf already installed an error message will be displayed.
bash xcode-select: error: command line tools are already installed, use "Software Update" to install updates
- Install home brew.
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"- Test if brew install correctly by displaying the help menu.
Brew help- To see all the packages we can install:
brew search # This does no longer show all the programs, needs to add name of the program.
brew search | -l # Retired/Discontinued.
brew search >programmname>
# Now use.
brew list # To see all packages already intalled. (see `brew help’)
brew info >programname< # Gives all the info of program. - To search a program in brew
brew search >programname< # This does no longer show all the programs, needs to add name of the program. - To display the pathway to a program in brew
which >programname< # Path to programs folder.
/usr/local/bin/tree. # Answer. But it is only a symlink to the real folder
ls -la /usr/local/bin/tree # Display long attributes of folder and the real location of the folder. /usr/local/bin/tree -> ../cellar/tree/1.8.0/bin/tree Other Brew commands.
- brew update
- brew outdated
- brew upgrade
- brew cleanup
- brew doctor
brew update –auto-update : Use this to see outdated formulas and casks installed. After running this message will appear.
You have 32 outdated formulae and 12 outdated casks installed.
You can “upgrade them” with **brew upgrade**
or “list them” with **brew outdated**. WARNING!: brew upgrade will reinstall all brew applications/programs, resetting all of them to factory settings. For R and RStudio, perform a package file backup BEFORE upgrade. Visual code does not require? ∵ Sync is on with github?.
Install the command “brew bundle”: With this package you can dump all the programs and applications that you installed with brew over time in a “brew file.” https://twit.tv/shows/hands-on-mac/episodes/9.
brew bundleIf bundle already downloaded or saved. Output will display:
Running `brew update --auto-update`...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
You have 32 outdated formulae and 11 outdated casks installed.
You can upgrade them with brew upgrade
or list them with brew outdated.
Error: No Brewfile found # This means that the Brewfile has not been yet created.
or
brew bundle install To check all programs installed with brew.
brew list masTerminal will show this:
(base) marcelorosales@MR-MBP20 ~ % brew list mas
/usr/local/Cellar/mas/1.8.6/bin/mas
/usr/local/Cellar/mas/1.8.6/etc/bash_completion.d/mas
/usr/local/Cellar/mas/1.8.6/share/fish/vendor_completions.d/mas.fish
If other reply, then… check list mas if not present install mas command:
brew list mas || brew install mas Creating a brewfile
- In terminal:
(Brew bundle install required).
brew bundle dump --describe- To check the “packages installed” with brew in the brewfile created:
cat brewfile This file will be created in the home directory. (Home directory » Cmd+shift+H; Macintosh HD > Users > (user name)).
# To create brewfile
brew update
clear
brew bundle dump --describe
clear
brew list mas
brew list
clear
cat brewfile - To install the brewfile in a new mac or new installation:
sudo softwareupdate -ia --verbose; # Updates MacOs (mac command)
brew bundle -v; # Install the brewfile created
brew cleanup; # To delete unused brew libraries.
brew doctor --verbose # To check if there are any other issues in system.Make a command script or command shell if your using “fish”, it’s easy to make a fish function that runs these lines with just one word ex. “update”, and then saving a lot of time.
Setting permisions.
Fun With Mac Terminal Commands - Hands-On Mac 5. .
Fun With Mac Terminal Commands - Hands-On Mac 5
chmod u-x <file/folder~>
# u – x user cant execute file/folder.
chmod u+x >file/folder~<
# u + x user was added access to execute file/folder.
chmod 777 >file/folder~<
# 777 user has been granted full access (hexadecimal 1 bit 2 bits 4 bits -> 4+2+1=7 for each level). 12:40 min.
man >cmdname<
# Manual.
brew install tldr
# install tldr
tldr >cmdname<
# Like manual, too long didn’t read? Summary of command functions.
sudo >cmdname<
# sudo= super user do, gives you admin privileges (will ask for password).
sudo softwareupdate -i -a
# Update apple computer command.
rm -rf *
# delete all HDD. DANGER!!
sudo nvram StartupMute=%00 # Mutes Mac’s startup chime.
sudo nvram StartupMute=%01 # Turns on Mac’s startup chime. Other useful terminal commands
- pwd
- cd ~
- cd » home
- ls » list
- ls -l
- ls -a
R and RStudio
Rpackages
Rpackages_MBP15_20221220
Rpackages_MBP20_20221220
Rpackages_MBP20_20221220_2159
Rpackages20220812
Rpackages20220812-2
RpackagesMBP20_220812
RpackagesMBP20_221219
Rpackages_20210108
Rpackages_20220812
Rpackages_20220812-2
Rpackages_MBP15_20221220
Rpackages_MBP20_20220812
Rpackages_MBP20_20221219
Rpackages_MBP20_20221220
Rpackages_MBP20_20221220_2159
Rpackages_20210108
Rpackages_20220812
Rpackages_20220812-2
Rpackages_MBP15_20221220
Rpackages_MBP20_20220812
Rpackages_MBP20_20221219
Rpackages_MBP20_20221220
Rpackages_MBP20_20221220_2159
Rpackages_MBP20_20221221_900
Rpackages_MBP20_20221221_1000
Rpackages_MBP20_20221221_900
Rpackages_MBP20_20221221_1000
Rpackages_MBP20_20221221_1100
load("Rpackages_20210108") # packages, 1:291
load("Rpackages_20220812") # packages2, 1:553
load("Rpackages_20220812-2") # packages2, 1:553
load("Rpackages_MBP15_20221220") # packages, 1:557
load("Rpackages_MBP20_20220812") # packagesMBP20_220812, 1:352
load("Rpackages_MBP20_20221219") # packages, 1:383
load("Rpackages_MBP20_20221220") # packages, 1:384
load("Rpackages_MBP20_20221220_2159") # packages, 1:386
load("Rpackages_MBP20_20221221_900") # Rpackages_MBP20_20221221_900, 1:32
load("Rpackages_MBP20_20221221_1000") # Rpackages_MBP20_20221221_1000, 1:512, **table R packages
install.packages("memoiR")
install.packages("distill")
install.packages("rmdformats")
install.packages("rmarkdown")
install.packages("markdown")
install.packages("markdownInput")
install.packages("rmdformats")
install.packages("htmlwidgets")
install.packages("officedown")
library(memoiR)
library(distill)
library(rmdformats)
library(rmarkdown)brew install --cask xquartzTerminal command to open RStudio
open -na Rstudio
open myproject.RprojRstudio commands.
press SHIFT + CMD + C (macOS), SHIFT + CTRL + C (Windows).
Table: ++Opt+cmd+T++ <Opt+cmd+T >
Code Chunk: ++Opt+cmd+I++ <Opt+cmd+I >
Citation: ++shift+cmd+F7++ <shift+cmd+F7>
Footnote: ++shift+cmd+F8++ <shift+cmd+F8>
Comment block: ++Shift+cmd+C++ <Shift+cmd+C >
Increase Indentation: Select block + ++Tab++
Decrease Indentation: Select block + ++Shift+Tab++
To make a file executable in Terminal, whether is a .bash file or a .sh file.
In Terminal type:
chmod +x scriptname.shInstalling/Upgarading R and RStudio
References Pages to visit first:
- Painless way to install a new version of R?
- How to migrate Rstudio files and installed packages ( by version to a new computer )
- An efficient way to install and load R packages
- Loading packages: the difference between R’s library() and require() functions
- Bioconductor
- Install/Update R and R packages
- restore all R packages after installing a new version of R?
- How to Upgrade R Without Losing Your Packages
- Upgrade R Without Losing Your Packages
- Update and migrate R
- Profiles package
- Rprofile.site file example for Startup customization
- Managing R with .Rprofile, .Renviron, Rprofile.site, Renviron.site, rsession.conf, and repos.conf
- How to Create Directory and File If It doesn’t Exist in R
Trick for doing the upgrade, from installing the software to copying all the settings/packages over?First you install the new version, then run this in the old version:
Stack Overflow
Run in the old version of R
setwd("C:/Temp/")
packages <- installed.packages()[,"Package"]
save(packages, file="Rpackages")Followed by this in the new version:
Run in the new version
setwd("C:/Temp/")
load("Rpackages")
for (p in setdiff(packages, installed.packages()[,"Package"]))
install.packages(p)For windows
Using Installr
#From https://stackoverflow.com/questions/1401904/painless-way-to-install-a-new-version-of-r
# Run in the old version of R (or via RStudio)
setwd("C:/Temp/")
packages <- installed.packages()[,"Package"]
save(packages, file="Rpackages")
# INSTALL NEW R VERSION
if(!require(installr)) { install.packages("installr"); require(installr)} #load / install+load installr
# See here for more on installr: https://www.r-statistics.com/2013/03/updating-r-from-r-on-windows-using-the-installr-package/
# step by step functions:
check.for.updates.R() # tells you if there is a new version of R or not.
install.R() # download and run the latest R installer... This install.R seems to be a windows only command.
# Install library - run in the new version of R. This calls package names and installs them from repos, thus all packages should be correct to the most recent version
setwd("C:/Temp/")
load("Rpackages")
for (p in setdiff(packages, installed.packages()[,"Package"]))
install.packages(p)
# Installr includes a package migration tool but this simply copies packages, it does not update them
copy.packages.between.libraries() # copy your packages to the newest R installation from the one version before it (if ask=T, it will ask you between which two versions to perform the copying)R-bloglers
How to Upgrade R Without Losing Your Packages
- Before you upgrade, build a temp file with all of your old packages. Files saved as .rda files.
tmp <- installed.packages()
installedpkgs <- as.vector(tmp[is.na(tmp[,"Priority"]), 1])
save(installedpkgs, file="installed_old.rda")Install the new version of R and let it do it’s thing.
Once you’ve got the new version up and running, reload the saved packages and re-install them from CRAN.
load("installed_old.rda")
tmp <- installed.packages()
installedpkgs.new <- as.vector(tmp[is.na(tmp[,"Priority"]), 1])
missing <- setdiff(installedpkgs, installedpkgs.new)
install.packages(missing)
update.packages()Note: If you had any packages from BioConductor, you can update those too!
#Update: 'biocLite' is not available for new versions of R
source("http://bioconductor.org/biocLite.R")
chooseBioCmirror()
biocLite()
load("installed_old.rda")
tmp <- installed.packages()
installedpkgs.new <- as.vector(tmp[is.na(tmp[,"Priority"]), 1])
missing <- setdiff(installedpkgs, installedpkgs.new)
for (i in 1:length(missing)) biocLite(missing[i])bioLite package
Update: ‘biocLite’ is not available for new versions of R
install.packages("biocLite") # Warning in install.packages : package ‘biocLite’ is not available for this version of RBiocLite is not a thing anymore, it was used in the old versions of Bioconductor to install packages, now you can directly use BiocManager::install().
For example:
BiocManager::install("limma")Save files as csv or excel .xlsx
csv files
write.csv(data_frame, 'path/to/forder/and/file_name.csv') # or set wd and just type file_name.csvexcel files
Convert first to a data frame.
install.packages("writexl")
library("writexl")
the_dataframe_name <- as.data.frame(data)
write_xlsx(the_dataframe_name,"path/to/folder/and/file_name.xlsx")Upgrading R on Windows and Mac
https://www.r-statistics.com/tag/installr/
Windows
If you are using Windows you can easily upgrade to the latest version of R using the installr package. Simply run the following code in Rgui:
install.packages("installr") # install
setInternet2(TRUE) # only for R versions older than 3.3.0
installr::updateR() # updating R.
# If you wish it to go faster, run: installr::updateR(T)Running “updateR()” will detect if there is a new R version available, and if so it will download+install it (etc.). There is also a step by step tutorial (with screenshots) on how to upgrade R on Windows, using the installr package. If you only see the option to upgrade to an older version of R, then change your mirror or try again in a few hours (it usually take around 24 hours for all CRAN mirrors to get the latest version of R).
Also chekck the video:
Mac
If you are using Mac you can easily upgrade to the latest version of R using Andrea Cirillo’s updateR package. The package is not on CRAN, so you’ll need to run the following code in Rgui:
UpdateR package: update R version with a function (on MAC OSX)
install.packages("devtools")
devtools::install_github("AndreaCirilloAC/updateR")
updateR(admin_password = "PASSWORD") # Where "PASSWORD" stands for your system passwordMBP15 The downloaded source packages are in “/private/var/folders/xc/rxn5vywj3lvd_qt78ss92cc80000gn/T/Rtmp8TJvA5/downloaded_packages” MBP20 The downloaded binary packages are in /var/folders/1v/nbx_5tgn553dq8s639lyln5c0000gn/T//Rtmp8AkWwy/downloaded_packages /private/var/folders/1v/nbx_5tgn553dq8s639lyln5c0000gn/T/RtmpP5nIXV/downloaded_packages
Option 1
Painless way to install a new version of R?
Files are .rda
#--run in the old version of R
setwd("C:/Temp/")
packages <- installed.packages()[,"Package"]
save(packages, file="Rpackages")
#--run in the new version
setwd("C:/Temp/")
load("Rpackages")
for (p in setdiff(packages, installed.packages()[,"Package"]))
install.packages(p)
#-----
# Just for completeness, you can save your packages in another directory on your computer.
install.packages("thepackage",lib="/path/to/directory/with/libraries")
#You can change the default .Library value using the function .libPaths too
.libPaths("/path/to/directory/with/libraries")
# -----
#Finally, You can also include a small code in my Rprofile.site allowing to reinstall all packages when installing a new R version. You just have to list them up before you update to the new R version by using an .RData file containing an updated list with all packages.
library(utils)
## Check necessary packages
load("G:\Setinfo\R\packagelist.RData") # includes a vector "pkgs"
installed <- pkgs %in% installed.packages()[, 'Package']
if (length(pkgs[!installed]) >=1){
install.packages(pkgs[!installed])
}
# I make the packagelist.RData by specifying .Last() in my Rprofile.site. This updates the package list if I installed some :
.Last <- function(){
pkgs <- installed.packages()[,1]
if (length(pkgs) > length(installed)){
save(pkgs,file="G:\Setinfo\R\packagelist.RData")
}
}Option 2:
How to migrate Rstudio files and installed packages ( by version to a new computer )
Save as .csv files.
Or .xlsx files.
getwd()
setwd()
# /Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/file_name.csv
installed <- as.data.frame(installed.packages())
write.csv(installed, 'installed_previously.csv') # Path/to/folder/installed_previously.csv
installedPreviously <- read.csv('installed_previously.csv') # Path/to/folder/installed_previously.csv
baseR <- as.data.frame(installed.packages())
toInstall <- setdiff(installedPreviously, baseR)
# the first thing to do would be to make sure that the set of currently installed packages is up-to-date.
update.packages(checkBuilt=TRUE, ask=FALSE) #check spelling of arguments
new_pacs <- paste( setdiff( installedPreviously$Package, baseR$Package),
collapse=",")
install.packages( new_pacs, dependencies=TRUE)
# For excel files, requires:
install.packages("writexl")
library("writexl")
write_xlsx(the_dataframe_name,"path/to/folder/file_name.xlsx")An efficient way to istall and load R packages
An efficient way to install and load R packages
Inefficient way to install and load R packages:
# Installation of required packages
install.packages("tidyverse")
install.packages("ggplot2")
install.packages("readxl")
install.packages("dplyr")
# Load packages
library("tidyverse")
library("ggplot2")
library("readxl")
library("dplyr")More efficient way
# Package names
packages <- c("ggplot2", "readxl", "dplyr", "tidyr", ...)
# Install packages not yet installed
installed_packages <- packages %in% rownames(installed.packages())
if (any(installed_packages == FALSE)) {
install.packages(packages[!installed_packages])
}
# Packages loading
invisible(lapply(packages, library, character.only = TRUE))Most efficient way
{pacman} package
After this article was published, a reader informed me about the {pacman} package. After having read the documentation and try it out myself, I learned that the function p_load() from {pacman} checks to see if a package is installed, if not it attempts to install the package and then loads it. It can also be applied to several packages at once, all this in a very condensed way:
install.packages("pacman")
pacman::p_load(ggplot2, tidyr, dplyr)
## Make sure your current packages are up to date
update.packages()
## devtools is required
library(devtools)
install_github("trinker/pacman")Find more about this package on CRAN. Introduction to the pacman Package in R (3 Examples)
{librarian} package
Like {pacman}, the shelf() function from the {librarian} package automatically installs, updates, and loads R packages that are not yet installed in a single function. The function accepts packages from CRAN, GitHub, and Bioconductor (only if Bioconductor’s Biobase package is installed). The function also accepts multiple package entries, provided as a comma-separated list of unquoted names (so no “” around package names).
Biobase: Base functions for Bioconductor DOI: 10.18129/B9.bioc.Biobase
Installation:
To install this package, start R (version “4.2”) and enter:
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("Biobase")Last but not least, the {librarian} package allows to load packages automatically at the start of every R session (thanks to the lib_startup() function) and search for new packages on CRAN by keywords or regular expressions (thanks to the browse_cran() function).
Here is an example of how to install missing packages and load them with the shelf() function:
# From CRAN:
install.packages("librarian")
librarian::shelf(ggplot2, DesiQuintans / desiderata, pander)For CRAN packages, provide the package name as normal without “” and for GitHub packages, provide the username and package name separated by / (i.e., UserName/RepoName as shown for the desiderata package).
Find more about this package on CRAN.
Stack Overflow 2
Every time I upgrade R using homebrew I need to install most packages again
Before install:
1. Update all R packages
Ref: https://www.neonscience.org/resources/learning-hub/tutorials/packages-r
# list all packages where an update is available
old.packages()
# update all available packages
update.packages()
# update, without prompts for permission/clarification
update.packages(ask = FALSE)
# update only a specific package use install.packages()
install.packages("plotly")2. Backup current package list.
tmp <- installed.packages()
installedpkgs <- as.vector(tmp[is.na(tmp[,"Priority"]), 1])
save(installedpkgs, file="installed_old.rda")3. Backup your preferences file
# Copy a file
source_path <- "/Users/marcelorosales/.config/rstudio/rstudio-prefs.json"
destination_path <- "/Users/marcelorosales/Box Sync/Github/RStudio_shared/RS_preferences/"
file.copy(source_path, destination_path, overwrite = FALSE)
# If: [1] TRUE, file was copied
# If: [1] FALSE, file was not copied, error might be that the file already exists (change overwrite = TRUE, or paths not correct.)
# Check if the copy was successful. This does not really work.
if (file.exists(destination_path)) {
print("File copied successfully!")
} else {
print("File copy failed.")
}Another way to do it:
# identify the folders
source_path <- "/Users/marcelorosales/.config/rstudio/"
destination_path <- "/Users/marcelorosales/Box Sync/Github/RStudio_shared/RS_preferences/"
file <- "rstudio-prefs.json"
# find the files that you want
list.files(source_path)
list.of.files <- list.files(source_path, file)
list.of.files
# copy the files to the new folder
file.copy(list.of.files, destination_path)Ref:
- https://fs.r-lib.org/reference/copy.html
- https://www.r-bloggers.com/2014/11/copying-files-with-r/
- https://r-lang.com/how-to-copy-a-file-in-r/***
- https://stat.ethz.ch/R-manual/R-devel/library/base/html/files.html
Install new version of R
#| eval: false
brew upgrade r
brew upgrade rstudioReload packages from CRAN
load("installed_old.rda")
tmp <- installed.packages()
installedpkgs.new <- as.vector(tmp[is.na(tmp[,"Priority"]), 1])
missing <- setdiff(installedpkgs, installedpkgs.new)
install.packages(missing)
update.packages()Reload packages from BioConductor
# Update2022: 'biocLite' is not available for new versions of R
chooseBioCmirror()
biocLite()
load("installed_old.rda")
tmp <- installed.packages()
installedpkgs.new <- as.vector(tmp[is.na(tmp[,"Priority"]), 1])
missing <- setdiff(installedpkgs, installedpkgs.new)
for (i in 1:length(missing)) biocLite(missing[i])Location of the R packages
terminal
#| eval: false
# MBP15: The downloaded source packages are in:
open /private/var/folders/xc/rxn5vywj3lvd_qt78ss92cc80000gn/T/Rtmp8TJvA5/downloaded_packages
# MBP20: The downloaded binary packages are in:
# old: open /private/var/folders/1v/nbx_5tgn553dq8s639lyln5c0000gn/T/Rtmp8AkWwy/downloaded_packages
open /private/var/folders/1v/nbx_5tgn553dq8s639lyln5c0000gn/T/RtmpP5nIXV/downloaded_packagesComparing files
To compare and find whether two files differ and where, there are a few packages.
library(tools)
md5sum("path/to/file1") == md5sum("path/to/file2")
library(diffobj)
diffFile("path/to/file1", "path/to/file2") # or `diffChr` if you data is in R already
library(diffr)
diffr("path/to/file1", "path/to/file2")
ses(readLines("path/to/file1"), readLines("path/to/file1"))
packages <- installed.packages()
structure(packages)Summary
recap
core
shell
outline
synopsis
Update 20230522
Saved installed packages
# Run in the old version of R
# ------
# 1. Before you upgrade, update all old packages.
# ------
# A. Update current packages.
update.packages(checkBuilt=TRUE, ask=FALSE) #check spelling of arguments
# B. Upgrade packages of Bioconductor
# Install packages from a newer version of Bioconductor.
# https://www.bioconductor.org/install/
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install(version = "3.16") # Or the newest version
# ------
# 2. Before you upgrade: 1. build and save a file with all current packages (old packages) and 2. Backup your rstudio preferences files.
# ------
# MBP15: setwd("/Users/Marcelo-Rosales/Box Sync/Github/RStudio_shared/R_packages/")
# MBP20: setwd("~/Box Sync/Github/RStudio_shared/R_packages/")
getwd()
# Variables for generic code:
## Create a new folder for packages files
new_folder <- "Rpkgs230522/" # <----------------change folder name here, don't forget the "/".
folder <- "/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/"
dir.create(paste0(folder,new_folder)) #use paste0(), paste() inserts a space between obj.
## Create the packages list files
file_name <- "Rpkgs_MBP20_230522" # <------------change file name here.
rda <- ".rda"
csv <- ".csv"
df <- "_df"
xlsx <- ".xlsx"
file1 <- paste0(folder,new_folder,file_name)
file2 <- paste0(folder,new_folder,file_name,rda)
file3 <- paste0(folder,new_folder,file_name,csv)
file4 <- paste0(folder,new_folder,file_name,df,csv)
file5 <- paste0(folder,new_folder,file_name,xlsx)
file1
file2
file3
file4
file5
# Generic code: I use this method because it is easy to change the names of the variables in one place once.
## No extension
Rpkgs <- installed.packages()[,"Package"] # This is a temp file.
save(Rpkgs, file= file1)
load(file1) # load as values (vector?)
## As .rda file
tmp <- installed.packages() # save in environment as data (dataframe?)
Rpkgs_rda<- as.vector(tmp[is.na(tmp[,"Priority"]), 1]) # save as vector package names.
save(Rpkgs_rda, file= file2)
load(file2)
## As .csv file requires a dataframe.
### 1. Only the Package column variable (as vector?), or 2. as full csv data frame.
Rpkgs_csv <- installed.packages()[,"Package"]
Rpkgs_df <- as.data.frame(installed.packages())
write.csv(Rpkgs_csv, file= file3)
write.csv(Rpkgs_df, file= file4)
## As as excel files also requires a dataframe (df)
### install.packages("writexl")
library("writexl")
Rpkgs_df <- as.data.frame(installed.packages()) # same as in df_csv
write_xlsx(Rpkgs_df, file5)
# Specific code: I do not use this method because requires changing the name of the folder and file in each instance, and paths are also troublesome.
Rpkgs_MBP20_230329 <- installed.packages()[,"Package"] # save as vector values?
save(Rpkgs_MBP20_230329, file="/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230329/Rpkgs_MBP20_230329") # Or Rpkgs_MBP20_230329.rda
load("/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230329/Rpkgs_MBP20_230329.rda") # load as values (vector?)
## As .rda file
Rpkgs_MBP20_230329 <- as.vector(tmp[is.na(tmp[,"Priority"]), 1]) # save as vector package names.
save(Rpkgs_MBP20_230329, file="/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230329/Rpkgs_MBP20_230329.rda") # save as vector .rda; names... environment: installedpkgs, file: installed_old.rda, but when loaded in environment is back to installedpkgs.
load("/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230329/installed_old.rda") # In environment is back to installedpkgs.
## Save as csv requires a dataframe (df)
Rpkgs_MBP20_230329 <- installed.packages()[,"Package"] # save only the Package (name) variable as vector values?, still can be save as csv
write.csv(Rpkgs_MBP20_230329, '/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230329/Rpkgs_MBP20_230329.csv')
## Or df with all the info of packages
Rpkgs_MBP20_230329df1 <- as.data.frame(installed.packages())
write.csv(Rpkgs_MBP20_230329df1, '/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230329/Rpkgs_MBP20_230329df1.csv')
# As excel file also requires a dataframe (df)
# install.packages("writexl")
library("writexl")
write_xlsx(Rpkgs_MBP20_230329df1,"/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230329/Rpkgs_MBP20_230329df1.xlsx")
# Copy/Paste Rstudio global settings and preferences (~/.config/rstudio/rstudio-prefs.json)
## Open folder
folder_path <- "~/.config/rstudio/" # seems like "~/path" does not work on rstudio.
folder_path <- "/Users/marcelorosales/.config/rstudio/"
system(paste("open", shQuote(folder_path)))
## Copy a file (direct).
source_path <- "/Users/marcelorosales/.config/rstudio/rstudio-prefs.json"
destination_path <- "/Users/marcelorosales/Box Sync/Github/RStudio_shared/RS_preferences/"
file.copy(source_path, destination_path, overwrite = FALSE)
## Copy a file (indirect). Find the file(s) first.
file <- "rstudio-prefs.json"
list.files(folder_path) # list all files in folder
find.files <- list.files(folder_path, file) # select a specific file
find.files
## copy the files to the new folder
file.copy(find.files, destination_path, overwrite = FALSE)
# If: [1] TRUE, file was copied
# If: [1] FALSE, file was not copied, error might be that the file already exists (change overwrite = TRUE, or paths not correct.)
# Another way to do it, see Stack overflow 2 section.
# Check if the copy was successful (THis code does not work properly, is )
if (file.exists(paste0(destination_path, file))) {
print("File copied successfully!")
} else {
print("File copy failed.")
}
# ------
# 3. Install the new version of R (use homebrew). See Brew cask upgrade below.
# ------
# 4. Once the new version up and running, reload the saved packages and re-install them from CRAN.
# run in the new version
# MBP20: setwd("/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/")
load("/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230329/Rpkgs_MBP20_230329.rda")
for (p in setdiff(RSpacks230324MBP15, installed.packages()[,"Package"]))
install.packages(p)Copy/Paste Rstudio global settings and preferences if necessary.
Terminal
#| eval:false
# Copy/Paste Rstudio global settings and preferences..
open ~/.config/rstudio
# Search and Copy file to same place as packages files.
rstudio-prefs.json#| eval: false
open ~/.config/rstudio# Open folder
folder_path <- "~/.config/rstudio/" # seems like "~/path" does not work on rstudio.
folder_path <- "/Users/marcelorosales/.config/rstudio/"
system(paste("open", shQuote(folder_path)))
# Copy a file
source_path <- "/Users/marcelorosales/.config/rstudio/rstudio-prefs.json"
destination_path <- "/Users/marcelorosales/Box Sync/Github/RStudio_shared/RS_preferences/"
file.copy(source_path, destination_path)
# Check if the copy was successful
if (file.exists(destination_path)) {
print("File copied successfully!")
} else {
print("File copy failed.")
}Brew cask upgrade R and Rstudio.
Terminal
# Upgrade R and rstudio
brew update
brew upgrade --cask r
# password
#`brew cleanup` has not been run in the last 30 days, running now...
# Upgrade RStudio
brew upgrade --cask rstudio
# Copy paste the `rstudio-prefs.json` if needed, usually it still remains after upgrade.
rstudio-prefs.jsonErrors and trouble shooting.
non-UTF8 locale error in R
WARNING: You’re using a non-UTF8 locale
When opening R new version… an error message is displayed.
error message
During startup - Warning messages:
1: Setting LC_CTYPE failed, using "C"
2: Setting LC_COLLATE failed, using "C"
3: Setting LC_TIME failed, using "C"
4: Setting LC_MESSAGES failed, using "C"
5: Setting LC_MONETARY failed, using "C"
[R.app GUI 1.79 (8198) x86_64-apple-darwin17.0]
WARNING: You're using a non-UTF8 locale, therefore only ASCII characters will work.
Please read R for Mac OS X FAQ (see Help) section 9 and adjust your system preferences accordingly.A solution: For english:
- Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using “C”
- For Japanese:.
Terminal
defaults write org.R-project.R force.LANG en_US.UTF-8 # 英語表示
defaults write org.R-project.R force.LANG ja_JP.UTF-8 # 日本語表示How to change language settings in R.
How to change language settings in R
You can set this using the Sys.setenv() function. My R session defaults to English, so I’ll set it to French and then back again:
> Sys.setenv(LANG = "fr")
> 2 + x
# Erreur : objet 'x' introuvable
> Sys.setenv(LANG = "en")
> 2 + x
# Error: object 'x' not foundThere is already an App… (legacy)
Error: It seems there is already an App at ‘/Applications/Rstudio’
is it possible to override the legacy app when install using brew
Some times is not possible to install, re-intall or upgrade a program via brew because first installation was made manually (downloaded zip or tar files).
This leaves a “legacy” app. To fix it use the --force attribute while installing
#| eval: false
brew install --cask rstudio --forceOther relevant files
How to’s:
Find out R library location in Mac OSX?
With .Library you get your default library location With .libPaths(“your/path”) you can also get/set you library trees (see ?.libPaths) and with getwd() resp. setwd(“your/path”) you get/set your working-directory.
.Library
.libPaths()Loading packages: the difference between R’s library() and require() functions{target= “_blank”}
Create Directory and File If It doesn’t Exist in R
How to Create Directory and File If It doesn’t Exist in R
# Syntax
# dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = "0777")
# file.create(…, file1, file2)
# Ex. New folder
folder <- "mortalkombat"
if (file.exists(folder)) {
cat("The folder already exists")
} else {
dir.create(folder)
}
# Ex. New file
file <- "dataframe.R"
if (file.exists(file)) {
cat("The file already exists")
} else {
file.create(file)
}
# Output
[1] TRUE # file created
[1] FALSE # file not createdConcatenate Strings in R programming language
# Syntax:
# paste(…, sep="", collapse=NULL)
# Sep = a character that would be appended between two adjacent strings and acts as a separator
# collapse = is an optional character to separate the results
# Concatenate two strings
str1 = 'Hello'
str2 = 'World!'
result = paste(str1,str2)
print (result)
# concatenate with No Separator
result = paste(str1,str2,sep="")
result = paste0(str1,str2)
print (result)
# concatenate with "some separator"
result = paste(str1,str2,str3,str4,sep="-")
print (result)R code to open a file or folder with OS system / finder
To open a file in Finder using R, you can use the shell.exec() function in Windows or the system() function in macOS. Here’s an example of how you can achieve this:
# Windows
file_path <- "C:/path/to/file.txt"
shell.exec(file_path)
# macOS
file_path <- "/path/to/file.txt"
system(paste("open", shQuote(file_path)))In the code snippet above, replace "C:/path/to/file.txt" or "/path/to/file.txt" with the actual path to the file you want to open in Finder.
On Windows, shell.exec() launches the default program associated with the file type, which will typically open the file in the default application for that file type.
On macOS, system() is used with the open command to open the file in Finder. The shQuote() function is used to properly handle file paths that contain spaces or special characters.
Make sure to adjust the file path accordingly to match the location of the file you want to open.
Tables in Rstudio
- A new RStudio addin to facilitate inserting tables in Rmarkdown documents
- Copy Table in Excel and Paste as a Markdown Table
- Tables Generator
- The function knitr::kable()
- Other packages for creating tables
/Users/marcelorosales/Documents/GitHub/Quarto/quarto-trials/quarto_website/xls2wb.htmExample:
data <- read.csv("/Users/marcelorosales/Documents/GitHub/Quarto/quarto-trials/quarto_website/qt01.csv")
data Programm VS_code VS_code.1 VS_code.2 Rstudio Rstudio.1 Rstudio.2 Rstudio.3
1 type md Rmd qmd md Rmd Rmd visual qmd
2 r o o o o
3 .r
4 {r} o o o o
5 {.r} o o o
6 rev r o
Rstudio.4
1 qmd visual
2 o
3 o
4
5 o
6 o
knitr::kable(data, "pipe", align = "c")| Programm | VS_code | VS_code.1 | VS_code.2 | Rstudio | Rstudio.1 | Rstudio.2 | Rstudio.3 | Rstudio.4 |
|---|---|---|---|---|---|---|---|---|
| type | md | Rmd | qmd | md | Rmd | Rmd visual | qmd | qmd visual |
| r | o | o | o | o | o | |||
| .r | o | |||||||
| {r} | o | o | o | o | ||||
| {.r} | o | o | o | o | ||||
| rev r | o | o |
knitr::kable(data, "simple", align = "c")| Programm | VS_code | VS_code.1 | VS_code.2 | Rstudio | Rstudio.1 | Rstudio.2 | Rstudio.3 | Rstudio.4 |
|---|---|---|---|---|---|---|---|---|
| type | md | Rmd | qmd | md | Rmd | Rmd visual | qmd | qmd visual |
| r | o | o | o | o | o | |||
| .r | o | |||||||
| {r} | o | o | o | o | ||||
| {.r} | o | o | o | o | ||||
| rev r | o | o |
knitr::kable(data, "html", align = "c")| Programm | VS_code | VS_code.1 | VS_code.2 | Rstudio | Rstudio.1 | Rstudio.2 | Rstudio.3 | Rstudio.4 |
|---|---|---|---|---|---|---|---|---|
| type | md | Rmd | qmd | md | Rmd | Rmd visual | qmd | qmd visual |
| r | o | o | o | o | o | |||
| .r | o | |||||||
| {r} | o | o | o | o | ||||
| {.r} | o | o | o | o | ||||
| rev r | o | o |
knitr::kable(data, "latex", align = "c")knitr::kable(data, "rst", align = "c")======== ======= ========= ========= ======= ========= ========== ========= ========== Programm VS_code VS_code.1 VS_code.2 Rstudio Rstudio.1 Rstudio.2 Rstudio.3 Rstudio.4 ======== ======= ========= ========= ======= ========= ========== ========= ========== type md Rmd qmd md Rmd Rmd visual qmd qmd visual r o o o o o
.r o
{r} o o o o
{.r} o o o o
rev r o o
======== ======= ========= ========= ======= ========= ========== ========= ==========
str(data)'data.frame': 6 obs. of 9 variables:
$ Programm : chr "type" "r" " .r" " {r}" ...
$ VS_code : chr "md" "o" "" "" ...
$ VS_code.1: chr "Rmd" "o" "" "" ...
$ VS_code.2: chr "qmd" "o" "" "o" ...
$ Rstudio : chr "md" "" "" "o" ...
$ Rstudio.1: chr "Rmd" "" "" "o" ...
$ Rstudio.2: chr "Rmd visual" "o" "" "" ...
$ Rstudio.3: chr "qmd" "" "" "o" ...
$ Rstudio.4: chr "qmd visual" "o" "o" "" ...
# Error: Values are not numeric.
# ! Can't subset columns with `data`.
# ✖ `data` must be numeric or character, not a <data.frame> object.
# ! Arguments in `...` must be used.
library(tidyverse)
data_long <- data %>%
pivot_longer(
data,
2:9,
names_to = "Programm",
values_to = "values"
)Convert wide data frame to long data frame
library(tidyverse)
# Example wide data frame
wide_df <- data.frame(
id = c(1, 2, 3),
var1 = c(10, 20, 30),
var2 = c(40, 50, 60),
var3 = c(70, 80, 90)
)
wide_df id var1 var2 var3
1 1 10 40 70
2 2 20 50 80
3 3 30 60 90
# Convert wide data frame to long
long_df <- wide_df %>%
pivot_longer(
cols = starts_with("var"), # Specify the columns to pivot
names_to = "variable", # Name of the new variable column
values_to = "value" # Name of the new value column
)
# View the resulting long data frame
print(long_df)# A tibble: 9 × 3
id variable value
<dbl> <chr> <dbl>
1 1 var1 10
2 1 var2 40
3 1 var3 70
4 2 var1 20
5 2 var2 50
6 2 var3 80
7 3 var1 30
8 3 var2 60
9 3 var3 90
knitr::kable(wide_df, "pipe", align = "c")| id | var1 | var2 | var3 |
|---|---|---|---|
| 1 | 10 | 40 | 70 |
| 2 | 20 | 50 | 80 |
| 3 | 30 | 60 | 90 |
knitr::kable(long_df, "pipe", align = "c")| id | variable | value |
|---|---|---|
| 1 | var1 | 10 |
| 1 | var2 | 40 |
| 1 | var3 | 70 |
| 2 | var1 | 20 |
| 2 | var2 | 50 |
| 2 | var3 | 80 |
| 3 | var1 | 30 |
| 3 | var2 | 60 |
| 3 | var3 | 90 |
Change language of R and Rstudio
Requires re-start app.
# Set r environment to english
Sys.setenv(LANG = "en")defaults write org.R-project.R force.LANG en_US.UTF-8 # 英語表示Shell_Core
# Run in the old version of
# ===== Before upgrade =====
# ------1. Update all old packages ----------
# Check R version or session info.
R.Version()
sessionInfo()
# A. Update current packages.
update.packages(checkBuilt=TRUE, ask=FALSE) #check spelling of arguments
## 20230608: The downloaded binary packages are in: /var/folders/1v/nbx_5tgn553dq8s639lyln5c0000gn/T//Rtmpt7WwKz/downloaded_packages
# B. Upgrade packages of Bioconductor
# Install packages from a newer version of Bioconductor https://www.bioconductor.org/install/
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
# BiocManager::install(version = "3.17") # Or the newest version
BiocManager::install("Biobase")
BiocManager::install("BiocGenerics")
# if error, re-install: 'Biobase'Old packages: 'learnr'
install.packages("learnr")
# ------ 2. Save backup of old packages and preferences ----
# 2. Before you upgrade: 1. build and save a file with all current packages (old packages) and 2. Backup your rstudio preferences files.
# ---- 2.1 Variables / info ----
# Run paths and pc`s info
# ~/path/to/folder "~" doesn't work?
pdir <- "/Box Sync/Github/RStudio_shared/R_packages/" # Path to directory
pth15 <- "/Users/Marcelo-Rosales" # MBP15
pth20 <- "/Users/marcelorosales" # MBP20
pc15 <- "MBP15"
pc20 <- "MBP20"
p15 <- paste0(pth15,pdir) # MBP15 destination folder
p20 <- paste0(pth20,pdir) # MBP20 destination folder
rpref <- "/.config/rstudio/rstudio-prefs.json" # ~ Location of preferences.json
# rprefd <- "/Box Sync/Github/RStudio_shared/RS_preferences/" # destination folder
pref15 <- paste0(pth15,rpref)
pref20 <- paste0(pth20,rpref)
# Run paths and pc`s info
#--- 2.2 Variables manual imput ----
library(stringr)
Sys.Date()
Sys.time()
gsub("-","",Sys.Date())
str_sub(gsub("-","",Sys.Date()), 3, -1) # https://youtu.be/343VCX3ynOA
date <- "230608" # <--------------------- change date (file name) here (manual).
date <- str_sub(gsub("-","",Sys.Date()), 3, -1) # date auto.
folder <- p20 # <--------------------- change destination folder (path) here.
pc <- pc20 # <--------------------- change PC (device name) here.
rs_pref <- pref20 # <--------------------- change r prefs location here.
new_folder <- paste0("Rpkgs",date,"/")
file_name <- paste0("Rpkgs_",pc,"_",date)
rda <- ".rda"
csv <- ".csv"
df <- "_df"
xlsx <- ".xlsx"
rpref.json <- paste0("rstudio-prefs_", pc,"_", date, ".json") # .json file name
source_path <- paste0(rs_pref)
destination_path <- paste0(folder,new_folder,rpref.json) # Place after the creation of the folder var.
system(paste("open", shQuote(folder)))
## Check Destination folder
date
folder
new_folder
file_name
pc
rs_pref
## Create a new folder for packages files... use paste0(), paste() inserts a space between obj.
dir.create(paste0(folder,new_folder))
## Create file names (only), extensions and path to folder.
file1 <- paste0(folder,new_folder,file_name)
file.rda <- paste0(folder,new_folder,file_name,rda)
file.csv <- paste0(folder,new_folder,file_name,csv)
file.csv2 <- paste0(folder,new_folder,file_name,df,csv)
file.xlsx <- paste0(folder,new_folder,file_name,xlsx)
file1
file.rda
file.csv
file.csv2
file.xlsx
#--------- 2.3 Create files ----------
# Ways to create and save Packages (old Rpkgs)
tmp <- installed.packages() # <--- Matrix
temp2 <- installed.packages()[,"Package"] # <--- Vector
temp3 <- as.vector(tmp[is.na(tmp[,"Priority"]), 1]) # <--- Vector
temp4 <- as.data.frame(installed.packages()) # <--- Dataframe
temp5 <- as.data.frame(installed.packages()[,"Package"])
# Which script to use?...
# 1.
as.vector(tmp[is.na(tmp[,"Priority"]), 1]) # Is currently the most common script.
# a) is.na(tmp[,"Priority"]) checks for missing or NA (Not Available) values in the "Priority" column. Returns a logical "vector" where TRUE = NA values and FALSE = non-NA values.
# b) It will return only NA rows.
# b) Non-NA rows are the default installed packages at clean/new start of program.
# c) Is NOT very good for comparing files good.
# 2.
as.data.frame(installed.packages()[,"Package"]) # Vector of only the packages column
# a) It will return a df of only the packages column, but will include all packages
# b) DF can be saved as csv files, very easy to compare with VS code "File: Compare..."
#=====2.3.1 PASTE FILE NAME!!! to each file type.====
print(file_name)
# [1] "Rpkgs_MBP15_230612" <-----------------------------Copy/Paste from console.
## No extension
Rpkgs_MBP20_230612 <- installed.packages()[,"Package"] # This is a temp file.
save(Rpkgs_MBP20_230612, file= file1)
## As .rda file
tmp <- installed.packages() # save in environment as data (dataframe?)
Rpkgs_MBP20_230612_rda<- as.vector(tmp[is.na(tmp[,"Priority"]), 1]) # save as vector package names.
save(Rpkgs_MBP20_230612_rda, file= file.rda)
tmp2 <- as.vector(installed.packages()[,"Package"])
tmp3 <- as.data.frame(installed.packages()[,"Package"])
## As .csv file requires a dataframe.
### 1. Only the Package column variable (as vector?), or 2. as full csv data frame.
Rpkgs_MBP20_230612_csv <- installed.packages()[,"Package"]
Rpkgs_MBP20_230612_df <- as.data.frame(installed.packages())
write.csv(Rpkgs_MBP20_230612_csv, file= file.csv)
write.csv(Rpkgs_MBP20_230612_df, file= file.csv2)
## As as excel files also requires a dataframe (df)
### install.packages("writexl")
library("writexl")
Rpkgs_MBP20_230612_df <- as.data.frame(installed.packages()) # same as in df_csv
write_xlsx(Rpkgs_MBP20_230612_df, file.xlsx)
# Copy/Paste Rstudio global settings and preferences (~/.config/rstudio/rstudio-prefs.json)
## Open folder
folder
new_folder
system(paste("open", shQuote(folder))) # seems like "~/path" does not work on rstudio.
system(paste("open", shQuote(paste0(folder, new_folder))))
## Copy a file (direct).
file.copy(source_path, destination_path, overwrite = FALSE) # overwrites old file.
# If: [1] TRUE, file was copied
# If: [1] FALSE, file was not copied, error might be that the file already exists (change overwrite = TRUE, or paths not correct.)
# Another way to do it, see Stack overflow 2 section.
# ------ 3. Install the new version of R (use homebrew).------
# Close R and Rstudio!! RUN in terminal better.
# {bash filename="Terminal"}
#| eval: false
# Upgrade R and rstudio
brew update
brew upgrade --cask r
brew reinstall --cask r
system("brew update")
system("brew update", intern = TRUE) # Setting intern = TRUE captures the output of the command and returns it as a character vector in R.
# password
#`brew cleanup` has not been run in the last 30 days, running now...
# Upgrade RStudio
brew upgrade --cask rstudio
# ------ After upgrade -----
# 4. Once the new version up and running, reload the saved packages and re-install them from CRAN
# run in the new version/device
#--- 4. Reload Variables and files ------
pdir <- "/Box Sync/Github/RStudio_shared/R_packages/" # Path to directory
pth15 <- "/Users/Marcelo-Rosales" # MBP15
pth20 <- "/Users/marcelorosales" # MBP20
pc15 <- "MBP15"
pc20 <- "MBP20"
p15 <- paste0(pth15,pdir) # MBP15 destination folder
p20 <- paste0(pth20,pdir) # MBP20 destination folder
rpref <- "/.config/rstudio/rstudio-prefs.json" # ~ Location of preferences.json
# rprefd <- "/Box Sync/Github/RStudio_shared/RS_preferences/" # destination folder
pref15 <- paste0(pth15,rpref)
pref20 <- paste0(pth20,rpref)
# Run paths and pc`s info
## Variables:
date <- "230609" # <--------------------- change date (file name) here.
date <- str_sub(gsub("-","",Sys.Date()), 3, -1) # date auto.
folder <- p20 # <--------------------- change destination folder (path) here.
pc <- pc20 # <--------------------- change PC (device name) here.
rs_pref <- pref20 # <--------------------- change r prefs location here.
new_folder <- paste0("Rpkgs",date,"/")
file_name <- paste0("Rpkgs_",pc,"_",date)
rda <- ".rda"
csv <- ".csv"
df <- "_df"
xlsx <- ".xlsx"
rpref.json <- paste0("rstudio-prefs_", pc,"_", date, ".json") # .json file name
source_path <- paste0(rs_pref)
destination_path <- paste0(folder,new_folder,rpref.json) # Place after the creation of the folder var.
# file1 <- paste0(folder,new_folder,file_name)
file.rda <- paste0(folder,new_folder,file_name,rda)
# file.csv <- paste0(folder,new_folder,file_name,csv)
# file.csv2 <- paste0(folder,new_folder,file_name,df,csv)
# file.xlsx <- paste0(folder,new_folder,file_name,xlsx)
# file1
file.rda
# file.csv
# file.csv2
# file.xlsx
#---- 5. Load old packages list ------
system(paste("open", shQuote(folder)))
#---- 5.1 "new" (base) vs "old" (backup) pkgs differences installation----
#load(installedpkgs_old)
file.rda
file_name_rda <- paste0(file_name,"_rda")
file_name_rda
load(file.rda) # will load as Rpkgs_MBP20_230612_rda
installedpkgs_old <- Rpkgs_MBP20_230612_rda # .rda
tmp <- installed.packages()
installedpkgs_new <- as.vector(tmp[is.na(tmp[,"Priority"]), 1])
missing <- setdiff(installedpkgs_old, installedpkgs_new)
missing
install.packages(missing)
update.packages()
#------ 5.2 "pc1" vs "pc2" pkgs differences install ----
file.rda # pc1.
load(file.rda) # will load as Rpkgs_MBP20_230612_rda
pc2 <- "/Users/marcelorosales/Box Sync/Github/RStudio_shared/R_packages/Rpkgs230612/Rpkgs_MBP15_230612.rda"
load(pc2) # will load as Rpkgs_MBP15_230612_rda
missing2 <- setdiff(Rpkgs_MBP20_230612_rda, Rpkgs_MBP15_230612_rda)
missing2
# [1] "Biobase" "BiocGenerics"
rm(Rpkgs_MBP15_230612_rda)
rm(Rpkgs_MBP20_230612_rda)
#----- 5.3 Install "Bioconductor" packages -----
## Packages from Bioconductor (before or after Rpackages install?)
## Install packages from a newer version of Bioconductor https://www.bioconductor.org/install/
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
# BiocManager::install(version = "3.17") # Or the newest version
BiocManager::install("Biobase")
BiocManager::install("BiocGenerics")
# if error, re-install: 'Biobase'Old packages: 'learnr'
install.packages("learnr")
#----- 5.4 Install packages short code
# for (p in setdiff(installedpkgs_old, installed.packages()[,"Package"]))
# install.packages(p)
#-----6. Compare csv files -----
# 6.1 Open csv files in VS code
path_csv <- paste0(p20, new_folder)
system(paste("open", shQuote(path_csv)))
# Select csv for pc1 and pc2 > drag to VS code icon > ....[]... will open in VS code
# In VS code: Select pc1 > cmd + p ...[]... > File: Compare Active File With...
# ------ 7. copy paste preferences. -------220830
Create Files&Dirs in R
How to Create Files and Directories in R - R-Lang
How to Create a directory in R To create a directory in R, use the dir.create() method. The dir.create() method accepts a folder generated in the current working directory or specifies a path. Before working with files, it’s a better idea to know what directory you’re working in. In R, you can figure out which directory you are working on the getwd() function.
Syntax
dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = "0777")Arguments
path: It is a character vector containing a single path name.
paths: They are character vectors containing file or directory paths.
showWarnings: It is a logical argument; should the warnings on failure be shown?
recursive: It is a logical argument. Should elements of the path other than the last be created? If true, like the Unix command mkdir -p.
mode: It will be used on Unix-alikes: it will be coerced by as.octmode. For Sys.chmod, it is recycled along paths.
Return Value
The dir.create() function returns an invisibly logical vector indicating if the operation succeeded for each of the files attempted.
Example Before creating a folder in R, you need to check if the same-named folder exists. To check if the folder exists, use the file.exists() method. Then if it does not exist, you can create a folder.
folder <- "mortalkombat"
if (file.exists(folder)) {
cat("The folder already exists")
} else {
dir.create(folder)
}If the folder does not exist, then it will create a new directory for you.
Trailing path separators are discarded. On Windows, drives are allowed in the path specification, and unless the path is rooted, it will be interpreted relative to the current directory on that drive. The mode is ignored on Windows.
Create a file in R
To create a file in R programmatically, use the file.create() method. The file.create() function creates files with the given names if they do not already exist and truncates them if they do.
Syntax
file.create(x, showWarnings = TRUE)Parameters …, file1, file2: They are character vectors containing file names or paths.
Example
file <- "dataframe.R"
if (file.exists(file)) {
cat("The file already exists")
} else {
file.create(file)
}Output [1] TRUE
install.packages("rChoiceDialogs")
install.packages("rJava")
library(rChoiceDialogs)
tk_choose.dir()works only on linux/mac not windows.
tk_choose.dir {tcltk}
Function to make symlinks.
ln -s /path/to/original /path/to/link
# upadate:
ln -s "/Users/name/My Files" "/Users/name/Desktop/My Link"- Choose a file
- choose a folder
- create symlink <In r there is a command already.>
- paste name of original file
- In >_?
pwd
cd /Users/rosalesrocabadomarcelo/Documents/GitHub/tests
pwd
touch test.txt
ls
#rm test.txt
#lstheSelectedFile="$(osascript -l JavaScript -e 'a=Application.currentApplication();a.includeStandardAdditions=true;a.chooseFile({withPrompt:"Please select a file to process:"}).toString()')"
echo "Selected file: $theSelectedFile"- With in R and Rstudio.
file.choose()file.choose() is a {base} function, it works by itself, does not need a package to work.
However, for choosing directories:
The choose.dir, from the utils package Choose a Folder Interactively on MS Windows only. Not mac.
For mac an Unix, use tk_choose.dir() form {tcltk} package.
library(tcltk)
tk_choose.dir()For multiplataform usage, create a custom function in the global environment
choose_directory = function(caption = 'Select data directory') {
if (exists('utils::choose.dir')) {
choose.dir(caption = caption)
} else {
tk_choose.dir(caption = caption)
}
}Then use it as a function:
choose_directory()How to Create Files and Directories in R - R-Lang
Windows
getwd()
setwd(choose.dir)
folder <- "test"
if (file.exists(folder)) {
cat("The folder already exists")
} else {
dir.create(folder)
}Mac
getwd()
setwd(tk_choose.dir())
folder <- "test"
if (file.exists(folder)) {
cat("The folder already exists")
} else {
dir.create(folder)
}Mac&Windows
getwd()
setwd(choose_directory())
folder <- "test"
if (file.exists(folder)) {
cat("The folder already exists")
} else {
dir.create(folder)
}Interactively, choose a folder.
if (interactive()) tk_choose.dir(getwd(), "Choose a suitable folder")- Create symlink
file.symlink(tk_choose.files(), tk_choose.dir())See files {base}
R Documentation File Manipulation
Install python
Install python with brew
#| eval: false
brew install python@3.8
brew install python3
brew install pyenv
brew install jupyter
# Check ojs
which ojs
# To run python in r install packages require, ex.
pip install numpy
pip install matplotlibAndrea Cirillo’s updateR package. T
install.packages("devtools")
devtools::install_github("AndreaCirilloAC/updateR")
updateR(admin_password = "PASSWORD") # Where "PASSWORD" stands for your system passwordVS code
25 VS Code Productivity Tips and Speed Hacks
VS Code key shortcuts
Shft+Cmd+P » show all commands, search key shortcuts.
Cmd+P » Go to file (open).
Cmd+W » close file.
Cont+Tab » Switch between Tabs/Pages.
Shift+Cmd+F » Find in File.
F5 » Start debugging.
Cont+` » Toggle Terminal.
shift+Cmd+X » Extensions.
VS Indentation
I had a problem with intending. The default Command+] is set to 4 and I wanted it to be 2. Installed “Indent 4-to-2” but it changed the entire file and not the selected text. I changed the tab spacing in settings and it was simple.
Go to Settings -> Text Editor -> Tab Size
Don’t Use the Sidebar in VS Code!! vid
Extensions Recomended:
- Advanced-new-file by patbenatar.
- File Utils by Steffen Leistner.
Setting Sync on: Account -> Github.
Extensions installed
How to install extension: -> Open VS code > Extensions (shift+Cmd+X) > search: extension name > ©Install button.
Top 40+ VSCode Extensions for Developers in 2022 Link
Top 10 VSCode extensions to use in 2022
- Markdown-preview-enhanced by Yiyi Wang.
- Live Preview by Microsoft vid
- Markdown All in One by Yu Zhang, link
+Markdown AutoTOC by Jim Paton link Not working.
+Auto Markdown TOC by Hunter Tran link [ü] √
- R by REditorSupport
- GitLens — Git supercharged by GitKraken
- YAML by Red hat.
- Auto Rename Tag by TabNine.
- Peacock by John Papa.
- Colorize by kamikillerto.
- Code Runner by Jun Han. To run only a small snippet of code.
- Auto rename tag by Jun Han.
- Excel Viewer by GrapeCity
Vim by vscodevim (need this emulator? Probably not, it just gives you some special shortcuts do not install).
Warning. This extension will Override Rich Text Copy/Paste of VS. Copy and Paste code into Word, Ignores Syntax Highlighting (When copy code and paste in Word, code colors will no longer be applied).
- Make sure that // Code > Preferences> Settings > Text Editor > √ Editor: Copy With Syntax Highlighting (is checked). Controls whether syntax highlighting should be copied into the clipboard.
- To solve: shift+Cmd+P > type: copy > in: Vim: !© Override Copy (uncheck vim override copy). Override VS Code’s copy command with our own copy command, which works better with VSCodeVim. Turn this off if copying is not working.
VS Setting tips
- Indentation settings and the indentation status bar entry
Footer: right // Tab Sizeˇ (Spaces:~) > Indent using tabs > © 2. (or Cmd+Shift+p > indent using spaces) Convert indentation to tab/spaces:
Footer: right // Tab Sizeˇ > Convert indentation to Spaces || Convert indentation to Tabs.
or
VS code panel > R© > Format document >
-
- Live Server by Ritwick Dey (Opens in Web browser only).
- HTML Preview by Thomas Haakon Townsend (Deprecated).
- Markdown preview enhanced. Check out shd101wyy/markdown-preview-enhanced (Public).
- Live Server by Ritwick Dey (Opens in Web browser only).
Unsplit an editor, go back from 2 code views to 1, same with terminal. Link
To “unsplit” editor groups without closing any open files, use the menu-bars:
View > Editor Layout > Single (or, while in the editor, press and release ALT and then type vls).
Editor groups are also closed by default when they become empty.Wrap code
Settings » Cmd+, //Code > Preferences > Settings > Editor: Word Wrap Controls how lines should wrap.Enable minimap
To enable VS Code’s Minimap, set “editor.minimap.enabled”: true to turn on the rendering of a Minimap for the current file.
You can also tune the appearance with the Size (editor.minimap.size), Scale (editor.minimap.scale), and Slider (editor.minimap.showSlider) settings. If the minimap is hidden, you can still display the context menu by right-clicking the side gutter.
Command Center
++cmd+“,”++
The Command Center has been polished and is now ready to be tried. Enable it via window.commandCenter setting.
Terminal Shell integration
Shell integration for PowerShell, bash, and zsh that has been in preview since the January release is now out of preview! We’re planning on enabling it by default in the 1.70 release.
To enable the shell integration feature, check Terminal > Integrated > Shell Integration : Enabled in the Settings editor or set the value in your settings.json:
terminal.integrated.shellIntegration.enabled: true
Updates:
June 2022 (version 1.69)
Welcome to the June 2022 release of Visual Studio Code. There are many updates in this version that we hope you’ll like, some of the key highlights include:
- 3-way merge editor - Resolve merge conflicts within VS Code.
- Command Center - New UI to search files, run commands, and navigate cursor history.
- Do Not Disturb mode - Silence non-critical notification popups.
- Toggle Light/Dark themes - Quickly switch between preferred light and dark themes.
- Terminal shell integration - Display command status, run recent commands, and more.†
- Task output decorations - Highlights task success or failure exit codes.
- Git Commit action button - Configure your default Git Commit action.
- Debug Step Into Target support - Allows you to step directly into functions when paused.
- JavaScript sourcemap toggling - Switch to debugging compiled rather than source code.
- Color theme tester - Use vscode.dev to preview color themes.
- VS Code Server preview - Run the same server used for Remote Development.
Types of comments:
1. Single-line comment.\
Syntax
# This is a single line comment- Multi-line comment?.
Syntax:
#| eval: false
: '
This is a
Multi-line comments'
Example:
echo "multiline comments"
: '
Print some word'Types of codes?
Markdown and Visual Studio Code
Markdown Basic Syntax
Markdown Cheatsheet
VS md Extensions & Syntax
Markdown and Visual Studio Code
- markdownlint : Checks md code errors {== uninstalled==}{>> too many corrections clutter <<}
- Markdown Shortcuts: Usefull key shortcuts {==available with right click==}
- Markdown Theme Kit: {== uninstalled==}
- Print: {== Not installed ==}
!!! info inline {++ addition ++}
{>> visible comment <<}
{– deletion –}
{== highlight==}{>> comment <<}
{~~ substitution ~> by ~~}
Code Without the {>> <<} at the beginning and end
{>>{++ addition ++}<<}
{>>{>> visible comment <<}<<}
{>>{-- deletion --}<<}
{>>{== highlight==}{>> visible comment <<}<<}
{>>{~~ substitution ~> by ~~}<<}
!!! info inline ++ addition ++
-- deletion --
== highlight ==
~~ substitution ~> by ~~
Code does not work without the {}
++ addition ++
>> visible comment <<
-- deletion --
== highlight ==
~~ substitution ~> by ~~
!!! note inline ++addition++
--deletion--
==highlight==
~~substitution~~
Spaces also place a roll in results
++addition++
>>visible comment<<
--deletion--
==highlight==
~~substitution~~
Add images and links in Markdown by dragging a dropping
https://www.youtube.com/watch?v=jpeh1WorrWM
- find image file with the VSC explorer.
- Drag image and take it over the current editor file or section
- Hold down shift (while dragging) and drop to the editor
Same procedure to add links to specific files.
To reload a single file:
- ⇧⌘P.
- type “Refresh”
- click on “CSV: Refresh”
You can also add a key shortcut.
VS Outline view (Headings toc)
The Outline view is a separate ==section in the bottom of the File Explorer==. When expanded, it will show the symbol tree of the currently active editor. For Markdown files, the symbol tree is the Markdown file’s header hierarchy.
VS Code tips — Rename markdown headers and updating all links to them
Collapse/Expand All items in Outline (Sidebar panel)
Hold ++alt++ while pressing the expand/collapse arrow and it does that.
Trouble shooting
Enter and Backspace do not work or are very slow to respond
Look for reasons why this could happen:, I found this comment in vs code markdown:
Enter and Backspace do not work or are very slow to respond #855
Hi there, I might be able to add a bit of context. I’m seeing the same performance issues (on backspace and enter) that **get resolved when I turn off Markdown: All in One’s onBackspace and onEnter functional
Solution https://github.com/yzhang-gh/vscode-markdown/issues/423
Code > Settings > keyboard Shortcuts > Type: markdown > delete: onEnterKey, onBackspaceKey.
If you do not need the “list continuation” feature, you can delete some key bindings (e.g. onEnterKey, onBackspaceKey). See instructions at #88 (comment).
If you want to investigate more, you can check1 these extensions first, which are reported (probably) conflicting with Markdown-All-in-One:
- Spell Right
- Bracket Pair Colorizer 2
- disable it and see whether the issue is gone
Mac Word
How to`s
Type =rand() and press enter.
Custom keyboard shortcut
Custom keyboard shortcut for Word for Mac.
You can create custom keyboard shortcuts in Word for Mac within the application itself.
Create a keyboard shortcut
Creation of my shortcut for FontColorPicker » Cmd+Opt+Shft+F.
- On the Tools > Customize Keyboard > …[]….
- In the Categories list, select a tab name.
- Alternatively, Type the command you are looking for in the commands search field. Then search by categories or in All commands to show that command from all categories.
- In the Commands list, select the command that you want to assign a keyboard shortcut to.
- Any keyboard shortcuts that are currently assigned to the selected command will appear in the Current keys box.
- Tip: If you prefer to use a different keyboard shortcut, add another shortcut to the list, and then use it instead.
- In the Press new keyboard shortcut box, type a key combination that includes at least one modifier key (CMD , CONTROL , OPTION , SHIFT ) and an additional key, such as CMD+ F11 .
- If you type a keyboard shortcut that is already assigned, the action assigned to that key combination appears next to Currently assigned to.
- Select Add.
- Note: Keyboard shortcut descriptions refer to the U.S. keyboard layout. Keys on other keyboard layouts might not correspond to the keys on a U.S. keyboard. Keyboard shortcuts for laptop computers might also differ.
Delete a custom keyboard shortcut
- // Tools > Customize Keyboard.
- In the Categories list, select a tab name.
- In the Commands list, select the command that you want to delete a keyboard shortcut from.
- In the Current keys box, select the keyboard shortcut that you want to delete, and then select Remove.
- Note: If the Remove button appears grayed out, then the selected keyboard shortcut is a default keyboard shortcut, thus it cannot be deleted.
Reset all keyboard shortcuts
- // Tools > Customize Keyboard.
- To restore keyboard shortcuts to their original state, select Reset All.
Replace as you type
!© Bold (bold) and italic (italic) [or italic?] with real formatting.
!© Hyphens (–) with a dash ( ).
!© set left-and first-indent with tabs and backspaces
Math symbols.
//Preferences > Autocorect > Math AutoCorrect.
© Use math autocorrect rules outside of math regions.
> ∵ to coz ∵
Math Symbols List:
Ref: Math notation
Symbol Key Meaning/original ∵ coz ∴ ∃ ∀ For all, for everyl ∆ Delta, change, triangle λ Eigenvalues, Wavelength, percent variance, μ micro ∇ Vector? ∋ under the condition that, contain ‖ Parallel, norm value or length of vector ∌ ν ν ∉ ν , ν ν ν ν ω Ω last ⊖ symmetric difference ∂ \partial ⟡ Diamond? ϕ \phi π ⒨ \pmatrix ∑ \sum × \times ⊤ \top
| Symbol | Key | Meaning/original |
|---|---|---|
| ∵ | coz | |
| ∴ | ||
| ∃ | ||
| ∀ | For all, for everyl | |
| ∆ | Delta, change, triangle | |
| λ | Eigenvalues, Wavelength, percent variance, | |
| μ | micro | |
| ∇ | Vector? | |
| ∋ | under the condition that, contain | |
| ‖ | Parallel, norm value or length of vector | |
| ∌ | ν | ν |
| ∉ | ν | , ν |
| ν | ν | ν |
| ω Ω | last | |
| ⊖ | symmetric difference | |
| ∂ | ||
| ⟡ | Diamond? | |
| ϕ | ||
| π | ||
| ⒨ | ||
| ∑ | ||
| × | ||
| ⊤ |
2 Spaces After Period
//Preferences > Spelling and Grammar > Writing style > Settings > Space between Sentences ˇ > two spaces.
!!! warning Be careful to place the cursor on line with the correct doc language as the window option will be different according to the language.
Does not change auto correct, only check as spelling. Reverted to don’t check.
Finally, Here: Disabling automatic periods after hitting double space bar:
Mac//System Preferences > Keyboard >Text > !© Add period with double-space.
Disabling automatic bullet list and number:
Word// Preferences > Auto Correct >Autoformat as you type > !© Automatic bulleted list.
Word// Preferences > Auto Correct >Autoformat as you type > !© Automatic number list.
Assigning key shortcuts to Symbols:.
Word//Insert > Advances Symbols > Search for symbol: Eg. Fonts > Windings > Check > Keyboard Shortcut > Press new keyboard shortcut > Assign >OK ü ++cont+shift+v++
Custom Keyboard shortcuts (KS) list:
FontColor: the KS will change the color font to red (only).
FontColorPicker: the KS will change the color font to the one selected in the pallet.
| Categories: | Commands: | New Keyboard shortcut: KS |
|---|---|---|
| All Commands | FontColorPicker | Cmd+Opt+Sht+F |
Key Shortcuts List
For Word and Command line.
232 Shortcuts for Microsoft Word.
| Command | Key Shortcut |
|---|---|
| Font | Cmd+Shift+F |
| Formatfont | Cmd+D |
| GrowFont | Cmd+Shift+> |
| GrowFontOnePoint | Cmd+] |
| ShrinkFont | Cmd+Shift+< |
| ShringkFontOnePoint | Cmd+ [ |
| . | . |
| ApplyHeading1 | Cmd+Opt+1 |
| ApplyHeading2 | Cmd+Opt+2 |
| ApplyHeading3 | Cmd+Opt+3 |
| ApplyListBullet | Cmd+Shift+L |
| . | . |
| Bold | Cmd+b ; Cmd+Shift+b ; Cont+B ; Cont+Shift+B |
| BrowseNext | Cmd+PgDwn |
| BrowsePrev | Cmd+PggUp |
| . | |
| Cancel | Cmd+. ; Esc |
| CenterPara | Cmd+E |
| ChangeCase | Shift+F3 ; Cmd+Opt+C |
| CharLeft | Left Arrow |
| CharLeftExtend | Shift+LeftArrow |
| CharRight | Right Arrow |
| CharRightExtend | Shift+Right Arrow |
| ClosePane | Cont+Shift+C |
| ColumnSelect | Cmd+Shift+F8 |
| CopyFormat | Cmd+Shift+C |
| CopyText | Shift+F2 |
| CreateAutoText | Opt+F3 |
| DeleteBackWord | Cmd+Del ; Opt+Del |
Key Shortcuts cwh8gsb19.
keys » Command.
Opt+Cmd+Spc » New Find …[]….
Opt+Cmd+M » Paragraph settings (For VS code).
Shift+Opt+Cmd+V » Paste and match the formatting. (Not VS code) Cont+H » Find and replace, Thumb, Nav-Map, Rev.
Cmd+[ or ] » Font size by one point.
Cmd+Opt+1 « Heading 1.
Cnt+Shft+Arws » Move Up/Down Line or Paragraph.
Cnt+Tab » Code block in .md (word).
Custom keys Cmd+Opt+Sht+F » FontColorPicker (Custom).
Cont+Shift+V » Check mark ü in Markdown Opt+¥sqrt » √ (Math AutoC)
coz ∵ Because (Math AutoC)
Input Sources. 1. ABC Extended
2. Japanese: ©Kana, ©Half Kana
3. Handwriting » Cnt+Shift+Spc
Rotate Keyboards » Cnt+Opt+Spc
Character Viewer » Cnt+Cmd+Spc or fn+E
vid ratio: 16:9 -> 560 x 315 fx(16/9*315=560) > 426x240 > 355x200 > 266x150
Finder.
Cmd+Shift+H » Home directory. (home icon in Finder favorites).
Opt+Cmd+W » Close all Finder windows.
Terminal Keyboard shortcuts (vid):
Cnt+a » Jump to the beginning of the line.
Cnt+e » Jump to the end of the line.
Opt+Arrows LR » To Jump one word at the time.
Opt+Mouse © » To place cursor in any place in the line.†cursor.
Cnt+u » Delete everything before cursor.
Cnt+k » Delete everything after the cursor.
Tab » Autocomplete.
Drag and drop folder » To autofill path of the folder. Ex. Cd (drag and drop folder).
Up and Down errors » Cycle through previously runed commands.
!+starting word of the command » To find previously runed commands.
History » Type history in terminal will show all runed commands in a number list.
!+history# » To find and paste that specific command.
Cnt+r » Resarch reverse. Auto filled type of find.
Cnt+L » Clear screen but not history scroll.
Cmd+K Clear screen and history scroll.
Command + Shift + . » Show/Hide hidden files.
System keys Opt+Cmd+P+R » Reset Parameter Ram To reset Non-volatile storage, storage that persist form boot to boot called NVRAM or P-RAM.
- Turn off mac, turn on and immediately press Opt+Cmd+P+R until you hear a sound. Cmd+R on reboot » Recovery mode. (to download macOS form net or Use time machine)
H on reboot » Safe mode in top right corner.
D on reboot » Apple Diagnostics; Opt+D on reboot » Apple Diagnostics over internet.
T on reboot » Target Disk Mode, makes mac in to a HDD. To copy data off a mac malfunctioning.
Opt/Alt on reboot » Start Up Manager, to choose bootcamp (Windows system) or form USB.
line space after c/p
To reduce the line space after c/p:
- Set doc to “No grid”, and then, each c/p section must be set to “Single [Paragraph]”. See 1 and 2 below.
Grid/snap
Snap charts, pictures, and objects to a grid to align them in Word.
- //[layout] > [page setup > Margins] > Custom margins > …[]… > [Document Grid] > ©No grid.
- ++opt+cmd+m++ -> Paragraph > Single > OK
- //[layout] > {page setup > Margins} > Custom margins > …[]… > [Document Grid] > ©No grid > … © Drawing Grid > …[]… >
- //[layout] > {page setup > Margins} > Custom margins > …[]… > [Document Grid] > ©No grid > … Set Font.
- //[layout] > {Arrange > ˇAlign} > Grid Settings > …[]… > Horizontal Spacing = 0.5 cm ; Vertical Spacing = 0.5 cm > ©OK changes automatically to Horizontal Spacing = 1.78 ch; Vertical Spacing = 1.18 line.
Tip: Grid spacing will define the movement length of an object, ex. If you create an square, and move it with the mouse, the movement is not smooth (linear pixel by pixel) but it will jump(snap) to the next grid line, so if the grid spacing is 0.5 cm, the square will move 0.5 cm each time, whether the grid is displayed or not. Set H and V spacing at 0.1 cm.
Snap to grid when document grid is defined -> KS possible?.
Set Grid Spacing
- //[layout] > {page setup > Margins} > Custom margins > …[Grid options]… > [Document Grid] > ©No grid; > Drawing Grid > ..[Grid options].. > Horizontal spacing = 0.1 cm; Vertical Spacing= 0.1 cm > Ok => ..[]> Grid options > grid settings: auto changed to, Horizontal spacing= 0.36 ch, Vertical spacing= 0.24 line > OK => ..{document grid] > OK.
- Lines are 1mm x 1mm, in whole page cannot be seen, zoom in until lines appear.
- If not seen, // View > © grid lines.
Another option, Shorter Path:
- //[layout] > {Arrange > ˇAlign} > Grid Settings > …[Grid options]… > Grid Settings: Horizontal Spacing = 0.5 cm ; Vertical Spacing = 0.5 cm > ©OK changes automatically to Horizontal Spacing = 1.78 ch; Vertical Spacing = 1.18 line.
->
Make default in all MRR1template.
Insert and Customize Gridlines in Word | Microsoft Word Tutorials.
Word: grid units change.
Windows: My default units are set to millimeters, under File->Options->Advanced->Display->Show measurements in units of: Millimeters.
Mac: // Word > Preferences > Authoring and proofing Tools > General > Show measurements in units of: Millimeters.
> ?* Preferences > Authoring and proofing Tools > General > !© Use character units. What does this does? Is not available in other versions of word….
When go back to the Grid and Guides dialog, and see that my spacing is no longer 1mm, it is .ch and .line.
Set Tab spacing
// Format > Tab > …[]… > Default stops: 1.5 ch. (in cm?)
Autoformat as you type:
++cmd+“,”++ > AutoCorrect >
Edit templates and Format Styles
Word for Microsoft 365 Word 2021 Word 2019 Word 2016 Word 2013 Whether you’re starting from a built-in template or updating one of your own, Word’s built-in tools help you update templates to suit your needs. To update your template, open the file, make the changes you want, and then save the template.
Click File > Open. Double-click This PC. (In Word 2013, double-click Computer). Browse to the Custom Office Templates folder that’s under My Documents. Click your template, and click Open. Make the changes you want, then save and close the template. PC word file.dotx
Default Word styles file:s
Normal.dotm: /Users/marcelorosales/Library/Group Containers/UBF8T346G9.Office/User Content.localized/Templates.localized/Normal.dotm
Created personal templates:
Folders: MBP15: /Users/Marcelo-Rosales/Library/Group Containers/UBF8T346G9.Office/User Content.localized/Templates.localized/MRdraft-01.dotx
MBP20: /Users/marcelorosales/Library/Group Containers/UBF8T346G9.Office/User Content.localized/Templates.localized/ TemplateMR21.dotx
MR22 Same folder.
To change styles use: - Style pane (change style on the open document only) or
- // Format > style… > …[]… > organizer > (here you can copy styles form the Normal.dotm to other document template with the [<- Copy] button)
- Tip: For formats, use the Home>Styles Pane > ..[].. > List all styles > Select Heading… > Modify Styles.. > …[]… > style based on: choose the Heading style immediately before.
Word Add-ins
//Insert > Add-ins > Get Add-ins
Easy Code Formatter
To fast and easy highlight code.
Preferences > Line Numbering> Render line numbers: Off
Preferences > Font: Calibry; size: 10
file_path <- "path/to/your/file.docx"
system(sprintf("open %s", file_path)) Example:
file_path <- "path/to/your/file.docx"
system(sprintf("open %s", file_path)) Highlight
file_path <- "path/to/your/file.docx"
system(sprintf("open %s", file_path)) Word and Rstudio
rstudio code to open a word file in word
(windows) To open a Word file in Microsoft Word from RStudio, you can use the shell() function in R to execute a command that opens the file with the default application associated with .docx files on your system.
Here’s an example of how you can open a Word file in Microsoft Word using RStudio:
file_path <- "path/to/your/file.docx"
shell(paste("start", shQuote(file_path)))Replace "path/to/your/file.docx" with the actual file path of your Word document.
The shell() function executes a system command, and the start command in Windows opens a file with the default associated application, which in this case is Microsoft Word for .docx files. The shQuote() function is used to properly quote the file path in case it contains spaces or special characters.
When you run this code in RStudio, it will open the specified Word file in Microsoft Word or the default application associated with .docx files on your system.
Please note that this approach relies on the default behavior of the operating system and the file associations. If the default application for .docx files is set to a different program or if you’re using a non-Windows operating system, the command may need to be adjusted accordingly.
in which package is the shell() function ? The shell() function is not part of any package in R. It is a base R function that allows you to execute system commands.
rstudio code to open a word file in word update:
(mac)
To open a Word file using RStudio, you can use the system() function instead. Here’s an updated example:
file_path <- "path/to/your/file.docx"
system(paste("open", shQuote(file_path)))Replace "path/to/your/file.docx" with the actual file path of your Word document.
In this example, the system() function is used to execute the system command open (on macOS) or start (on Windows) with the specified file path. The shQuote() function is used to properly quote the file path.
When you run this code in RStudio, it should open the Word file in the default application associated with .docx files on your system.
Please note that the specific command to open files may vary depending on your operating system. The open command is used on macOS, while the start command is used on Windows. You may need to adjust the command accordingly if you’re using a different operating system.
Open word file w/i Rstudio
To open a Word file in RStudio, you can use the read_docx() function from the officer package. Here’s an example of how you can open a Word file in RStudio:
- Install the
officerpackage by running the following command in RStudio:
install.packages("officer")- Load the
officerpackage:
library(officer)- Use the
read_docx()function to read the Word file:
doc <- read_docx("path/to/your/file.docx")Replace "path/to/your/file.docx" with the actual file path of your Word document.
After running this code, the Word file will be loaded into RStudio and stored in the doc object, which you can then manipulate or extract information from using functions provided by the officer package.
Please note that the officer package provides functionality for manipulating Word documents in R, but it is not a full-featured word processing application. If you need to perform complex editing or formatting tasks on Word files, it is recommended to use Microsoft Word or other dedicated word processing software.
Summary
(See Markdown02.docx > Word and Rstudio for detail info on the code)
files:
Mac:
Markdown02 <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown02.docx"
Research_map <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Research_map and guide.docx"
Markdown01 <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown01.docx"
Notes <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/"
excel <- "/Users/marcelorosales/Documents/GitHub/Quarto/quarto-trials/quarto_website/test.xlsx"
#open in mac OS
system(paste("open", shQuote(Markdown02)))
system(paste("open", shQuote(Research_map)))
system(paste("open", shQuote(Notes)))
system(paste("open", shQuote(excel)))Windows:
file_path <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown01.docx"
shell(paste("start", shQuote(file_path)))
# or
system(paste("start", shQuote(file_path)))Markdown
Intro and Tutorials
See complete video collection Markdown: Academic writing in plain text
Two column layout with markdown html
2 Column layout code:
| Column 1 | Column 2 |
|---|---|
|
Column 2 Text |
Not working in .Rmd,
Markdown TOC: table of contents?
How to link to part of the same document in Markdown?
Code example 1
# Table of Contents
1. [Example](#example)
2. [Example2](#example2)
3. [Third Example](#third-example)
4. [Fourth Example](#fourth-examplehttpwwwfourthexamplecom)
## Example
## Example2
## Third Example
## [Fourth Example](http://www.fourthexample.com)
Code example 2
# Table of contents
1. [Introduction](#introduction)
2. [Some paragraph](#paragraph1)
1. [Sub paragraph](#subparagraph1)
3. [Another paragraph](#paragraph2)
## This is the introduction <a name="introduction"></a>
Some introduction text, formatted in heading 2 style
## Some paragraph <a name="paragraph1"></a>
The first paragraph text
### Sub paragraph <a name="subparagraph1"></a>
This is a sub paragraph, formatted in heading 3 style
## Another paragraph <a name="paragraph2"></a>
The second paragraph text
There might also be the one or the other library, who can generate TOCs: see Python Markdown TOC Extension.
Toc Word <=> VS
How to create a table of content in markdown and vs code.
How to create a table of content in markdown and vs code
Require: Installation of Add on: Markdown All in One by Yu Zhang required, see Table of contents.
Or Auto Markdown TOC by Hunter Tran, (use: in md file, right click > Auto Markdown TOC: Insert/Update (++cont+m+t++).
:
- In Word, Create the toc []// References > Table of contents > Custom Table of contents > !© show page numbers | Show levels =5 > OK.
- Copy/paste table from word into vs and create mkd toc.
- In VS press Shift+Cmd+P to bring Command Palette.
- Run command Create Table of Contents.
- TOC is automatically created/updated on file save by default.
- The indentation type (tab or spaces) of TOC can be configured per file.
- Find the setting in the right bottom corner of VS Code’s status bar.
Note: Be sure to also check the list.indentationSize option. To make TOC compatible with GitHub or GitLab, set option slugifyMode accordingly Three ways to control which headings are present in the TOC: Easily add/update/remove section numbering.
- Shft+Cmp+P ..[].. type section… search… > Markdown All in One Add/Update section numbers.
- Cnt+Shit+] or “[]” » to increase / decrease Indentation level. (Make sure cursor is in pasted toc and not in the VS created toc).
!!! tip “toc tip” Each md file can have only one # (title). If other section is mark as main title (#~), table of content.
Table of Contents Generator for Markdown | Productivity | Tech Primers
<iframe width=“560” height=“315” src=“https://www.youtube.com/embed/xdNIia7Z2RE” title=“YouTube video player” frameborder=“0” allow=“accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture” allowfullscreen>
Table of Contents Generator for Markdown | Productivity | Tech Primers
Making your R Markdown Pretty
Rmarkdown into Word - change a title in toc
In the yaml set:
# yaml code:
title: "Mixture distributions"
output:
word_document:
toc: yes
toc-title: Article OutlineMarkdown symbols
Tip: Generate Images path with “issues” (in github).
code:
# heading 1
###### heading 6
*Italics*
**bold**
***bold and italics***
> Block quote
- Unordered list
1 ordered list
{size, position}
[Link Text](link url)
\ escape (¥ = to back slash in japanese keyboards)
outcome:
# heading 1
###### heading 6
Italics
bold
bold and italics
> Block quote
- Unordered list
1. ordered list
{ width="100"; align=righ }
Link Text
escape (¥ = to back slash in japanese keyboards)
(See 32:39 cross talk document? Section?).
top How to draw checkbox or tick mark in GitHub Markdown table?.
- (for unchecked checkbox)
- (for checked checkbox)
[] , [x] , ✗ , ✓ , ☐ , ☑ , , .
| # | Unchecked | Checked |
|---|---|---|
| 1 | [] | [x] |
| 2 | ✗ | ✓ |
| 3 | ☐ | ☑ |
| 4 | works | works here too |
| 5 | Cont+Sht+V | in Word, ü in .md |
| 6 | √ |
Go to top
Can I add a “go to top” button to an HTML document rendered in R Markdown? In word
- Create a bookmark: //insert/bookmark…/…[]…/{top}/©Add
- Create a hyperlink to the bookmark: {top} or any {name} > select {top} > R© > Hyperlink (or ++cont+k++) > This Document > Bookmarks > ©top (bookmark name) > OK
- c/p created link and place where back to top button/link is required: every heading better H2 and H3.
In word markdown
This code will make it quick and simple.
[top](#) In md preview it will automatically provide a link to top.
Just add the bookmark anchor and it will work for both, word and word-markdown but not with vs-markdown
top
In vs-markdown
- Create an anchor at the top of page:
###### top
- Create or c/p link wherever you need
[top](#top)
!!! check “better option” 1. In vs code raw md data and preview the [top](#) will not work, it is better to work with the vs outline panel.
2. Place the TOC at the end and use the foot anchor in outline panel to jump to toc.
In mkdocs
The code for word markdown will work in mkdocs.
[top](#)
html code will work for word-md extension.
<a href="#top">Back to top</a>
[top](#) Back to top
top // any text here would work unless you want to point to a particular id in the html
Link anchor
How to link to part of the same document in Markdown? Github automatically parses anchor tags out of your headers. So you can do the following:
[Custom foo description](#foo)
© in the link above and you will jump to the ankor (# Foo) below.
# Foo.
Warnings boxes
Code:
<div style="padding: 15px; border: 1px solid transparent; border-color: transparent; margin-bottom: 20px; border-radius: 4px; color: #3c763d; background-color: #dff0d8; border-color: #d6e9c6;">
I am a success message
</div>
<div style="padding: 15px; border: 1px solid transparent; border-color: transparent; margin-bottom: 20px; border-radius: 4px; color: #a94442; background-color: #f2dede; border-color: #ebccd1;">
I am an error message
</div>
<div style="padding: 15px; border: 1px solid transparent; border-color: transparent; margin-bottom: 20px; border-radius: 4px; color: #31708f; background-color: #d9edf7; border-color: #bce8f1;">
I am a info message
</div>
<div style="padding: 15px; border: 1px solid transparent; border-color: transparent; margin-bottom: 20px; border-radius: 4px; color: #8a6d3b;; background-color: #fcf8e3; border-color: #faebcc;">
I am a warning message
</div>
<div class="alert alert-success"><i class="icon-ok"></i> **SUCCESS:** Markdown formatting _is_ supported here.
</div>
<div class="alert alert-info"><i class="icon-lightbulb"></i><strong>INFO:</strong> Markdown formatting _is_ supported here.
</div>
<div class="alert alert-warning"><i class="icon-right-hand"></i> **WARNING:** Markdown formatting _is_ supported here.
</div>
<div class="alert alert-danger"></i><i class="icon-attention-alt"></i>**DANGER:** Markdown formatting _is_ supported here.
</div>
<div style= "border: 1px solid transparent;
border-color: transparent;
margin-bottom: 10px;
border-radius: 4px;
color: #000000;
background-color: #eeeee;
border-color: #ebccd1;">
<div style = "padding: 5px;
border: 1px solid transparent;
border-color: transparent;
border-radius: 4px;
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;">
warning
</div>
<div style="padding: 5px;">
Message!!.
</div>
</div>Output:
I am a success message
I am an error message
I am a info message
I am a warning message
SUCCESS: Markdown formatting is supported here.
INFO: Markdown formatting is supported here.
WARNING: Markdown formatting is supported here.
DANGER: Markdown formatting is supported here.
The secret to creativity is knowing how to hide your sources. – [Albert Einstein][1]
warning
Message!!.
Comments in Markdown
If you want a comment that is strictly for yourself (readers of the converted document should not be able to see it, even with “view source”) you could (ab)use the link labels (for use with reference style links) that are available in the core Markdown specification:
http://daringfireball.net/projects/markdown/syntax#link
That is:
[comment]: <> (This is a comment, it will not be included)
[comment]: <> (in the output file unless you use it in)
[comment]: <> (a reference style link.)
(works in: VS) Ex: (A line space is needed between text and comment).
Or you could go further:
[//]: <> (This is also a comment.)
Ex. (A line space is needed between text and comment).
To improve platform compatibility (and to save one keystroke) it is also possible to use # (which is a legitimate hyperlink target) instead of <>:
[//]: # (This may be the most platform independent comment)
Ex. (A line space is needed between text and comment).
For maximum portability it is important to insert a blank line before and after this type of comments, because some Markdown parsers do not work correctly when definitions brush up against regular text. The most recent research with Babelmark shows that blank lines before and after are both important. Some parsers will output the comment if there is no blank line before, and some parsers will exclude the following line if there is no blank line after.
In general, this approach should work with most Markdown parsers, since it’s part of the core specification. (even if the behavior when multiple links are defined, or when a link is defined but never used, is not strictly specified).
Placing a comment between <> will make it a comment and invisible in a markdown document. Ex.
Other type of comments:
This is an example 1
This is an example 2 //: <comment here only text no numbers nor punctuation other than. Hover over comment dash lines and text will appear. unfortunatelly is not from this comment but from previous one. > (This is also a comment.)
This is an example 3 //: # (This may be the most platform independent comment)
Comments Examples: (3):
comment:
//: #This is the comment (This may be the most platform independent comment) this type of comment does not seems to be working)
Warning: Try to avoid using the above comment code since it requires for each one to be labeled different, and error messages may be displayed.
Markdown Shortcuts
Handy {++shortcuts++} for ==editing== Markdown (.md, .markdown) files by ==right clicking==. You can also use markdown formats in any other file (see configuration settings).
- Quickly toggle bullet points
- Easily generate URLs
- Convert tabular data to tables
- Context and title menu integration
- You can show and hide icons in the title bar with the markdownShortcuts.icons.* config settings.
| Name | Description | Default key binding |
|---|---|---|
| md-shortcut.showCommandPalette | Display all commands | ctrl+M ctrl+M |
| md-shortcut.toggleBold | Make bold | ctrl+B |
| md-shortcut.toggleItalic | Make italic or italic | ctrl+I |
| md-shortcut.toggleStrikethrough | Make |
|
| md-shortcut.toggleLink | Make a hyperlink | ctrl+L |
| md-shortcut.toggleImage | Make an image |
ctrl+shift+L |
| md-shortcut.toggleCodeBlock | Make a code block |
ctrl+M ctrl+C |
| md-shortcut.toggleInlineCode | Make inline code |
ctrl+M ctrl+I |
| md-shortcut.toggleBullets | Make * bullet point | ctrl+M ctrl+B |
| md-shortcut.toggleNumbers | Make 1. numbered list | ctrl+M ctrl+1 |
Preview Markdown files with Quick Look in Finder on Mac
Command to install with Homebrew Cask in ~/Library/QuickLookIt will be installed when you run Install cask has changed (added on 2021-02-02) to
brew install --cask qlmarkdownUninstall cask seems changed (added on 2021-02-02)
brew uninstall --cask qlmarkdownMkDocs
MkDocs is a fast, simple and downright gorgeous static site generator that’s geared towards building project documentation.
Documentation source files are written in Markdown, and configured with a single YAML configuration file.
Start by reading the introductory tutorial, then check the User Guide for more information.
Mkdocs Python - How to Create & Publish Documentations For Your Packages
Alexys Jacob - Create beautiful and localized documentations and websites using MkDocs + Github
Crear páginas web con Rmarkdown, MkDocs y GitHub pages: una alternativa para documentación.
Githubpage: https://github.com/ronnyhdez/docmaker
MkDocs Materials official github account:
Documentation that simply works. Write your documentation in Markdown and create a professional static site in minutes – searchable, customizable, for all devices.
MkDocs Install
User Guide
Building Documentation with MkDocs
The MkDocs Developer Guide provides documentation for users of MkDocs. See Getting Started for an introductory tutorial. You can jump directly to a page listed below, or use the next and previous buttons in the navigation bar at the top of the page to move through the documentation in order.
- Installation
- Writing Your Docs
- Choosing Your Theme
- Customizing Your Theme
- Configuration
- Deploying Your Docs
HOW TO INSTALL MKDOCS ON MAC AND SETUP THE INTEGRATION TO GITHUB PAGES January 25, 2021
Summary:
LOCAL SETUP ON MAC OS
- brew
brew --version; - Python 3
python --version; find&installbrew list <formula1> || brew install <formula1>;brew install python3;brew install python@3.10
- Pip :
pip --version;pip3 install --upgrade pip
- MkDocs :
pip3 install mkdocs(I used this install as described in guide); option:brew install mkdocs(error)
- MkDocs Material Extensions :
pip3 install mkdocs-material
Other Plugins:
- i18n:
pip install mkdocs-static-i18n;
- Theme Materials:
pip install mkdocs-material
INSTALL ON RSTUDIO:
- You can install the development version of docmaker from GitHub with:
devtools::install_github("ronnyhdez/docmaker")- When published on CRAN, you will be able to install the package with:
install.packages("devtools")Why I don’t use this in Rstudio directly? Because the commands to render the pages do NOT seem to work with in Rstudio, I can code and preview in VS code But only the page, the R graphs are not displayed, is would be a constant changing from Rstudio <=> VS code <=> Word. Use better quarto, write all in “visual”, can paste images directly in and R will automatically create a img folder and name the file (which is a great feature, can leave without it). Internationalization is not good yet. Image galleries are very good.
CONFIGURATION IN THE GITHUB PROJECT
MKDOCS INSTALLATION ON MAC
STEP 1: VERIFY THE BREW INSTALLATION
Check if intalled:
brew –versionSTEP 2: CHANGE THE FOLDER PERMISSION TO INSTALL PYTHON, IF NEEDED
sudo chown -R $(whoami) /usr/local/lib/pkgconfig
chmod u+w /usr/local/lib/pkgconfig STEP 3: INSTALL PYTHON3
To check if python and pip are installed use:
python --version (Python 3.8.2)
pip --version (pip 20.0.2 from /usr/local/lib/python3.8/site-packages/pip (python 3.8))
Or brew list <formula1> || brew install <formula1> If not installed use:
brew install python3
20220704: Already Installed version 3.8, 3.9 I installed lates version: brew install python@3.10
Python has been installed as
/usr/local/opt/python@3.10/bin/python3
Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have been installed into
/usr/local/opt/python@3.10/libexec/bin
You can install Python packages with
/usr/local/opt/python@3.10/bin/pip3 install <package>
They will install into the site-package directory
/usr/local/lib/python3.10/site-packages
tkinter is no longer included with this formula, but it is available separately:
brew install python-tk@3.10
See: https://docs.brew.sh/Homebrew-and-Python
python@3.10 is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.
If you need to have python@3.10 first in your PATH, run:
echo 'export PATH="/usr/local/opt/python@3.10/bin:$PATH"' >> ~/.zshrc
For compilers to find python@3.10 you may need to set:
export LDFLAGS="-L/usr/local/opt/python@3.10/lib"
For pkg-config to find python@3.10 you may need to set:
export PKG_CONFIG_PATH="/usr/local/opt/python@3.10/lib/pkgconfig"
==> Summary
🍺 /usr/local/Cellar/python@3.10/3.10.5: 3,137 files, 56.8MB
==> Running `brew cleanup python@3.10`...
Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).STEP 4: Install UPGRADE PIP
pip –version
pip3 install --upgrade pip
STEP 5: INSTALL MKDOCS
pip3 install mkdocs (I used this install as described in guide).
brew install mkdocs :
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink bin/mkdocs
Target /usr/local/bin/mkdocs
already exists. You may want to remove it:
rm '/usr/local/bin/mkdocs'
STEP 6: INSTALL MKDOCS-MATERIAL
pip3 install mkdocs-material STEP 7: INSTALL MKDOCS-MATERIAL-EXTENSIONS
pip3 install mkdocs-material-extensions VERIFY AND BUILD YOUR DOCUMENTATION
STEP 1: ENSURE YOU HAVE THE MKDOCS.YML FILE IN PLACE
Here is an example configuration for the mkdocs.yml file and here you find an example project, which is based on that configuration.
configuration example project
Documentation
For full documentation visit mkdocs.org.
Commands
mkdocs new [dir-name]- Create a new project.mkdocs serve- Start the live-reloading docs server.Cnt+C- to stop server.mkdocs build- Build the documentation site.mkdocs -h- Print help message and exit.mkdocs gh-deploy- deploy to github.
Project layout
mkdocs.yml # The configuration file. docs/
index.md # The documentation homepage. … # Other markdown pages, images and other files.
To create a site
#| eval: false
cd /Users/marcelorosales/Documents/GitHub/MkDocs/MkDocsTut220704
mkdocs new Hello-siteTest INFO - Creating project directory: Hello-siteTest
INFO - Writing config file: Hello-siteTest/mkdocs.yml
INFO - Writing initial docs: Hello-siteTest/docs/index.md
#| eval: false
ls Hello-siteTest
#| eval: false
cd Hello-siteTest #| eval: false
tree .
├── docs
│ └── index.md
└── mkdocs.yml
#| eval: false
code . In editor softw Modify mkdocs.yml, the site_name, site_url, Nav, etc.
site_name: Hello-siteTest
site_url: https://example.com_or_my.github
nav:
- Home: Index.mdSave..
Live Pre-view of the site (Local Server)
In terminal.
#| eval: false
mkdocs serve INFO - Building documentation…
INFO - Cleaning site directory
INFO - Documentation built in 0.07 seconds
INFO - [16:12:35] Watching paths for changes: ‘docs’, ‘mkdocs.yml’
INFO - [16:12:35] Serving on http://127.0.0.1:8000/
INFO - [16:13:00] Browser connected: http://127.0.0.1:8000/
MkDocs Themes
In the mkdocs.yml file add a theme: Eg theme: readthedocs
site_name: Test site
site_url: https://example.com_or_my.github
nav:
- Home: index.md
- New Nav Tab 1: NewNavTab1.md
- New Nav Tab 2: NewNavTab2.md
theme: readthedocs Other themes.
theme:
# name: readthedocs
name: materialAdd images/assets
Stop server.
Create assets/ in the docs/ .
Insert images in the folder.
In the Home
Internationalization plugin
Pages
- Create the pages in the desired languages.
Index.md –> Index.en.md
| –> Index.jp.md
| –> Index.es.md
- Add plugins to .yaml file
plugins:
- search # add search box.
- i18n: # language plugin.
default_language: en
languages:
en: English
jp: 日本語
es: EspañolThen deploy: mkdocs serve
> May require Install plunging
#| eval: false
pip install mkdocs-static-i18n More info here
Images
- Create the images in the desired languages and
add the language as an extension.
img.png –> img.en.png
| –> img.ja.png
| –> img.es.png
> WARNING - Language jp is not supported by mkdocs-material==8.3.8, not setting the ‘theme.language’ option. CORRECTION: is ja for Japanese, not jp.
It works anyways‼!
- In md files just use the name of the image, plug in will automatically assign the language extension to the corresponding language .md file. Eg.
 To build site
Once site is finished, stop live preview Cnt+C
In Terminal:
#| eval: false
mkdocs buildINFO - Cleaning site directory
INFO - Building documentation to directory:
/Users/marcelorosales/Documents/GitHub/MkDocs/MkDocsTut220704/Hello-siteTest/site
INFO - Documentation built in 0.11 seconds
Will create all the files and folders required for an HTML site.
In terminal: (Make sure you are in the directory containing the site)
#| eval: false
mkdocs gh-deployTo deploy in Github
**To create a site with Terminal (>_):**
cd /Documents/GitHub..(local, not in cloud)
mkdocs new {rojectName} (Creates new dir)
cd ProjectName
tree (√ if ∃ mkdocs.yml, index.md)
In VS code:
drag/File > Add Folder to Workspace ProjectName || code mkdocs.yml
copy/paste template || code .ylm
touch .md (Create page content)
.
**In >_:**
mkdocs serve (no need to build to serve)
stop server Cont+C
Connect to Github
**With >_:**
git init (√ if ∃? .git)
gedit gitignore (edit gitignore to don’t track files…)
git add . (add all files to git)
git status (files currently staged)
git config --global user.name “MyGitAccount” (MR)
git config --global user.email “myemail.com” (hot)
git commit -m “Initial Commit”
git status (empty, no files staged) -> up to here, ver control only in local dir/repo.
In github.com:
create git repo in github.com
copy the repo_url
**In >_:**
git remote add origin repo_url
git push origin master
type github username:
type github Password: (push from local master branch to remote master branch)
**Mkdocs deploy in >_:**
mkdocs build
mkdocs gh-deploy
After first commit:
Modify code. (and save files)
mkdocs build
mkdocs gh-deploy
git add .
git status
git commit -m “”
git status (nothing to commit)
git reflog (commit history)
Other git commands:
git reflog (past git logs)
git checkout -b other-branch (Switch to a new branch)
git branch -a (lists of branches)
rm -fr .git (remove git files)
**To create a site with GitHub Desktop (>_):**
- Create mkdocs site in >_ (local, not cloud)
- Open Github Desktop
- Add > Add an existing repocitory > ..[].. > choose > path > add > ..[!∆!].. ©
create a repository> …[]…
- Name:{} > Description: {} > © Create Repository.
- Commit > Description > © Commit to main
- Go to my github.com > General > Danger zone > Change visibility > …[]… Make public > Please type … to confirm.
- Go to Pages > Branch: © gh-pages > © root > save
- ` Your site is published at Error! Hyperlink reference not valid.
After committing to github.
VS Source Control > stage all changes > commitName > Commit > Push
Adding Existing Project To Git/GitHub Using Command Line
Extra comments
>_ git init
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint: git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint: git branch -m <name>
github.com
new repository
=============================================================
Quick setup — if you’ve done this kind of thing before
or
https://github.com/MarceloRosales/mkt2.git
Get started by creating a new file or uploading an existing file. We recommend every repository include a README, LICENSE, and .gitignore.
…or create a new repository on the command line
echo "# mkt2" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/MarceloRosales/mkt2.git
git push -u origin main
…or push an existing repository from the command line
git remote add origin https://github.com/MarceloRosales/mkt2.git
git branch -M main
git push -u origin main
…or import code from another repository
You can initialize this repository with code from a Subversion, Mercurial, or TFS project.
===============================================================
>_ git status
On branch master
nothing to commit, working tree clean
>_
>_ git remote add origin https://github.com/MarceloRosales/mkt2.git
>_
>_ git push origin master
Enumerating objects: 60, done.
Counting objects: 100% (60/60), done.
Delta compression using up to 4 threads
Compressing objects: 100% (53/53), done.
Writing objects: 100% (60/60), 447.09 KiB | 1.92 MiB/s, done.
Total 60 (delta 7), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (7/7), done.
To https://github.com/MarceloRosales/mkt2.git
* [new branch] master -> master
Automatic mkdocs gh-deploy and plugin extensions
Alexys Jacob - Create beautiful and localized documentations and websites using MkDocs + Github
Use Github Actions to run mkdocs gh-deploy automatically when push new commits.
.github/workflows/gh-deploy.yml
[ ] Finish this section.
Theme Materials
Install
#| eval: false
pip install mkdocs-materialCheck this Resources¶
Some useful and awesome MkDocs plugins¶
ref. website: ultrabug
https://github.com/ultrabug/ultrabug.fr
MkDocs Wiki’s Plugins list (community based)
Plugin to handle URL redirections
Plugin to handle navigation pages ordering in a very flexible way
Plugin to hook your own functions without having to create a MkDocs plugin
Material theme extension guide
brewfile Mkdocs Install MAC OS
Demo:
**Installed required (>_)**
#| eval: false
brew --version
python --version
brew list <formula1> || brew install <formula1>
brew install python3
brew install python@3.10
pip --version
pip3 install --upgrade pip
pip3 install mkdoc
brew install mkdocs (error)
pip3 install mkdocs-material
Other Plugins:
pip install mkdocs-static-i18n
pip install mkdocs-material **Create a site with Terminal (>_)**
#| eval: false
mkdocs -h # (help)
mkdocs new {dir-name}
ls
tree
mkdocs serve
Cnt+C
+ code .
+ rstudio .
+ open -na Rstudio
+ open myproject.Rproj
- Modify yml # (simple, just to check if render)
- Theme, nav, plugs
- Add content file
mkdocs serve
Cnt+C In github.com:
create git repo in github.com (follow recommendation of Hernandez?)
1. Github > create new repo > name: {x: demo_docmaker } > description {dockmaker demo} > ©Public > © Add readme file > © Add .gitignore: ˇ{R} > © Create repository
2. Repo settings > Pages > Source > ˇBranch: © main > /(root) > ©save (new page is created)
3. Got to // Code > code > clone > htpps (copy github page address)
- git ignore R files
- copy the repo_url
**Connect Mkdocs to Gith with >_:**
#| eval: false
git init
git config --global init.defaultBranch main # New repos will use "main" as default branch.
git branch -m main # changes the name of branch from "master" to "main"
git add .
git status
git config --global user.name “MyGitAccount” (MR)
git config --global user.email “myemail.com” (hot)
git commit -m “Initial Commit”
git status (empty)
gedit gitignore #(edit gitignore to don’t track files…??) **Connect Mkdocs to Github repository >_:**
#| eval: false
git remote add origin <repo_url>
git push origin master
type github username:
type github Password:
# (push from local master branch to remote master branch) **Mkdocs site build and deploy in >_:**
#| eval: false
mkdocs build
mkdocs gh-deploy After first commit:
#| eval: false
Modify code. (and save files)
mkdocs build
mkdocs gh-deploy
git add .
git status
git commit -m “commit message”
git status Other git commands:
#| eval: false
git reflog # (past git logs)
git checkout -b other-branch # (Switch to a new branch)
git branch -a # (lists of branches)
rm -fr .git # (remove git files)
git config --global user.name "MarceloRosales"
git config --global user.email "...@hotmail.com"
git config credential.helper store
git commit -m "1st commit"
git log # If want to revert to a preview's version, Copy hash click Q to quit.
git checkout {hash copied from log}
git checkout -b {new branch name} # Create a new branch.
git branch {new branch name} {hash} # Create new branch, if revert to previous, add hash
git checkout {branch name} # To change branches
git merge {branch name} # merge branch to mainOther examples
yml example of a Mkdoc site in R documentation » here the github page » and here the render html page
Mkdocs Markdown guide
Key shortcuts format
++ctrl+alt+del+cmd+fn++
++opt++ ++alt+opt++ ++alt+shift+f++
++ctrl+alt+del+cmd+fn++
++opt++
++alt+opt++
++alt+shift+f++
Admonition anotations
!!! Fix Note
??? Collapsable Note
???+ Uncollapse collapsable note
to add content into the anotation box, 2x tab indentation is requierd.
!!! Info “This is an admonition markdown extension info icon(!).”
This is the emal address.
!!! Info "This is an **admonition** markdown extension info icon(!)."
This is the emal address.
!!! note ” This is and admonition note icon (pencil)” See manual here
!!! note " This is and admonition note icon (pencil)"
See manual [here](https://squidfunk.github.io/mkdocs-material/reference/admonitions/#collapsible-blocks)
??? “collapsable note”
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod nulla. Curabitur feugiat, tortor non consequat finibus, justo purus auctor massa, nec semper lorem quam in massa.
??? "collapsable note"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod
nulla.
???+ note Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod nulla.
Curabitur feugiat, tortor non consequat finibus, justo purus auctor massa, nec semper lorem quam in massa.
???+ note
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod nulla.
!!! example “
{: style=”width:20px”} Ansible Infra” 1. Get into the folder that you need to work with (e.g. ansible-playbook-vpn-pritunl) 2. Run leverage run init to get all the necessary Ansible roles based on each requirements.yml 3. Make whatever changes you need to make as stated in each Playbook Documentation (check Documentation section above) - Opt-1: - Opt-2:
- Opt-3:
!!! example "{: style="width:20px"} [Ansible Infra](https://github.com/binbashar/le-ansible-infra)"
1. Get into the folder that you need to work with (e.g. `ansible-playbook-vpn-pritunl`)
2. Run `leverage run init` to get all the necessary Ansible roles based on each `requirements.yml`
3. Make whatever changes you need to make as stated in each Playbook Documentation (check Documentation section above)
- Opt-1:
- Opt-2:
- Opt-3:
??? check “Governance | AWS Organizations” - [x] AWS Organizations Initialization - [x] Invite pre-exiting accounts to AWS Organizations - [ ] other
??? check "Governance | AWS Organizations"
- [x] [AWS Organizations Initialization]()
- [x] [Invite pre-exiting accounts to AWS Organizations]()
- [ ] other
!!! summary “sumary, abstract, tldr have tge same icon”
!!! summary
"sumary, abstract, tldr have tge same icon"
!!! tip !!! tip
!!! tip
`!!! tip`
!!! success !!! success
!!! success
`!!! success`
!!! question question, help, faq have tge same icon
!!! warning !!! failure !!! danger !!! bug
In html
Fail
message
Warning
message
Question / Success
message
Danger
message
Tip/Summary
message
Inline blocks
[:octicons-tag-24: 7.0.0][Inline support] · :octicons-beaker-24: Experimental
Admonitions can also be rendered as inline blocks (i.e. for sidebars), placing them to the right using the inline + end modifiers, or to the left using only the inline modifier:
!!! info inline end
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Use inline end to align to the right (left for rtl languages).
!!! info inline end
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nulla et euismod nulla.
!!! info inline Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Use inline to align to the left (right for rtl languages).
!!! info inline
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nulla et euismod nulla.
Nested Fence Format
For this refer to Fenced Code Blocks, Extension, or better the SuperFences in mkdocs page. This does not work in rmd nor word md.
Visit /Users/marcelorosales/Box Sync/Github/mkdocs/MBA03/docs/All.md and run with vs code mkdocs package.
Fenced Block
Fenced blocks have a specific use, revise later!!! >
a fenced block
or better:
!!! check “best option” in mkdocs.
fenced block
>
fenced block
title
End!!!
Tabs
Mkdocs only.
=== “Tab 1” Lorem ipsum dolor sit amet, (1) consectetur adipiscing elit.
{ .annotate }
1. :man_raising_hand: I’m an annotation!
=== “Tab 2” Phasellus posuere in sem ut cursus (1)
{ .annotate }
1. :woman_raising_hand: I’m an annotation as well!
Example:
=== “:octicons-arrow-right-16: inline end”
!!! info inline end
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
``` markdown
!!! info inline end
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nulla et euismod nulla.
```
Use `inline end` to align to the right (left for rtl languages).
=== “:octicons-arrow-left-16: inline”
!!! info inline
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et
euismod nulla.
``` markdown
!!! info inline
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nulla et euismod nulla.
```
Use `inline` to align to the left (right for rtl languages).
Next, you will setup all required dependencies to work on a Leverage project in your local machine.
::: {.grid .cards markdown=""}
- :fontawesome-brands-html5: **HTML** for content and structure
- :fontawesome-brands-js: **JavaScript** for interactivity
- :fontawesome-brands-css3: **CSS** for text running out of boxes
- :fontawesome-brands-internet-explorer: **Internet Explorer** ... huh?
:::
Example:
::: {.grid .cards markdown=""}
- :material-clock-fast:{ .lg .middle } **Set up in 5 minutes**
------------------------------------------------------------------------
Install [`mkdocs-material`](#) with [`pip`](#) and get up and running in minutes
[:octicons-arrow-right-24: Getting started](#)
- :fontawesome-brands-markdown:{ .lg .middle } **It's just Markdown**
------------------------------------------------------------------------
Focus on your content and generate a responsive and searchable static site
[:octicons-arrow-right-24: Reference](#)
- :material-format-font:{ .lg .middle } **Made to measure**
------------------------------------------------------------------------
Change the colors, fonts, language, icons, logo and more with a few lines
[:octicons-arrow-right-24: Customization](#)
- :material-scale-balance:{ .lg .middle } **Open Source, MIT**
------------------------------------------------------------------------
Material for MkDocs is licensed under MIT and available on \[GitHub\]
[:octicons-arrow-right-24: License](#)
:::
:fontawesome-brands-html5: HTML for content and structure { .card }
:fontawesome-brands-js: JavaScript for interactivity { .card }
:fontawesome-brands-css3: CSS for text running out of boxes { .card }
:fontawesome-brands-internet-explorer: Internet Explorer … huh?
Example:
Example below to be run in mkdocs files only:
=== “Unordered list”
* Sed sagittis eleifend rutrum
* Donec vitae suscipit est
* Nulla tempor lobortis orci
=== “Ordered list”
1. Sed sagittis eleifend rutrum
2. Donec vitae suscipit est
3. Nulla tempor lobortis orci
```title=“Content tabs” === “Unordered list” * Sed sagittis eleifend rutrum * Donec vitae suscipit est * Nulla tempor lobortis orci
=== “Ordered list” 1. Sed sagittis eleifend rutrum 2. Donec vitae suscipit est 3. Nulla tempor lobortis orci ```
The fence 4```` is added coz it prevents code fence to extend. I don’t know why it does that.
TOC
not added.
Adding abbreviations
Abbreviations can be defined by using a special syntax similar to links and footnotes, starting with a * and immediately followed by the term or acronym to be associated in square brackets:
The HTML specification is maintained by the W3C.
*[HTML]: Hyper Text Markup Language
*[W3C]: World Wide Web ConsortiumThe HTML specification is maintained by the W3C.
[HTML]: Hyper Text Markup Language [W3C]: World Wide Web Consortium
Adding a glossary
The [Snippets] extension can be used to implement a simple glossary by moving all abbreviations in a dedicated file1, and auto-append this file to all pages with the following configuration:
=== “includes/abbreviations.md”
```` markdown
*[HTML]: Hyper Text Markup Language
*[W3C]: World Wide Web Consortium
````
=== “mkdocs.yml”
```` yaml
markdown_extensions:
- pymdownx.snippets:
auto_append:
- includes/abbreviations.md
````
Content tabs
Sometimes, it’s desirable to group alternative content under different tabs, e.g. when describing how to access an API from different languages or environments. Material for MkDocs allows for beautiful and functional tabs, grouping code blocks and other content.
Configuration
This configuration enables content tabs, and allows to nest arbitrary content inside content tabs, including code blocks and … more content tabs! Add the following lines to mkdocs.yml:
markdown_extensions:
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: truecode:
``` title=“Content tabs” === “Unordered list”
* Sed sagittis eleifend rutrum
* Donec vitae suscipit est
* Nulla tempor lobortis orci
=== “Ordered list”
1. Sed sagittis eleifend rutrum
2. Donec vitae suscipit est
3. Nulla tempor lobortis orci
ulla tempor lobortis orci
Result:
=== “Unordered list”
* Sed sagittis eleifend rutrum
* Donec vitae suscipit est
* Nulla tempor lobortis orci
=== “Ordered list”
1. Sed sagittis eleifend rutrum
2. Donec vitae suscipit est
3. Nulla tempor lobortis orci
Images and Galleries Tests
Markdown images
Configuration ¶ This configuration adds the ability to align images, add captions to images (rendering them as figures), and mark large images for lazy-loading. Add the following lines to mkdocs.yml:
markdown_extensions:
- attr_list
- md_in_htmlLightbox¶ If you want to add image zoom functionality to your documentation, the glightbox plugin is an excellent choice, as it integrates perfectly with Material for MkDocs. Install it with pip:
pip install mkdocs-glightboxThen, add the following lines to mkdocs.yml:
plugins:
- glightbox!!! warning * Images with mkdocs markdown code will not be displayed correctly by vs code preview. * html image code is not recognize by mkdocs build * Image galleries in html may not work in mkdocs markdown
{width="300"}
{width="300"} To reference an image:
![02-Premolar][Premolar]{width="300"}
Place the reference at the end or in a list of image references. Reference code line will not be displayed. (Space between this line and the reference is required)
Above this section there is a reference list, but it is not displayed in vs code nor mkdocs is:
[Incisor]: img/01-Incisor-1000x684.jpg
[Premolar]: img/02-Premolar-1000x684.jpg
[Molar]: img/03-Molar-1000x684.jpg
[Articulator]: img/04-Articulator-1000x684.jpg
[Waxup]: img/05-Waxup-1000x684.jpg
[MetalPlate]: img/06-metalplate.png
[Pro-Arch]: img/Pro-Arch-Ig.png
[Incisor_3]: img/s300/01-Incisor-300.jpg
[Premolar_3]: img/s300/02-Premolar-300.jpg
[Molar_3]: img/s300/03-Molar-300.jpg
[Articulator_3]: img/s300/04-Articulator-300.jpg
[Waxup_3]: img/s300/05-Waxup-300.jpg
??? failure “Other references for md image size (not working with mkdocs)”
Changing image size in Markdown
With certain Markdown implementations (including Mou and Marked 2 (only macOS)) you can append **=WIDTHxHEIGHT** after the URL of the graphic file to resize the image. Do not forget the space before the =.
``
`` not working.
You can skip the HEIGHT
``
And Width
``
Nested images, from small to larger ver (not working?)
To make a link from image displayed (small size thumb img) to larger version of the img: Nested links…
](http://unsplash.it/50/50?image=1000)
{ width="300" }
{ width="10%" }
http://unsplash.it/50/50?image=1000
http://unsplash.it/500/500?image=1000
Simple list of images mkdocs
Better to place a space between images.
![Inc][Incisor]{ width="200" }
![Prem][Premolar]{width="200" }
![Mol][Molar]{width="200" }
![Art][Articulator]{width="200" } Image align left and right
{ align=left } Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
Start Text in the same line as code, { align=right } so text align to top of the image.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
Aling + image reference
![Inc][Incisor_3]{ align=left } Start Text in the same line as code, so text align to top of the image. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum is simply dummy text of the printing and typesetting industry.
![Inc][Premolar_3]{ align=right } Start Text in the same line as code, so text align to top of the image. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
Image reference + size + Align
{width=“100”; align=right} {width="100"; align=right}Start Text in the same line as code, so text align to top of the image. Lorem Ipsum is simply dummy text of the printing and typesetting industry.
{width=“100”; align=right} ![01-Incisor][Incisor_3]{width="100"; align=right}Start Text in the same line as code, so text align to top of the image. Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Image align center
Photo gallery
HTML photo gallery (bootstrap?)
Not working coz needs style or align tags. Appears just like a list of images.
<div class="container-fluid" id="spacer-Nav-Content"></div>
<div class="header" id="メディア"> <h1>ビデオ・メディア</h1></div>
<div class="wrapper"><b><a href="動画の再生方法について.html" target="_blank"><h2>動画の再生方法</h2></a></b></div>
<!-- Gallery Grid Start -minmax() in auto-fill repeating tracks, by example https://gridbyexample.com/examples/example28/ -->
<div class="wrapper">
<div class="box a"><a href="movies/Video01/video01.m3u8" target="_blank"><img src="/img/01-Incisor-1000x684.jpg" alt="" style="width:50%"/><br>上顎左側中切歯ビデオ</a></div>
<div class="box b"><a href="movies/Video02/video02.m3u8" target="_blank"><img src="/img/02-Premolar-1000x684.jpg" alt="" width="100"/><br>上顎左側第1小臼歯ビデオ</a></div>
<div class="box c"><a href="movies/Video03/video03.m3u8" target="_blank"><img src="/img/03-Molar-1000x684.jpg" alt="" width="200"/><br>上顎左側第1大臼歯ビデオ</a></div>
<div class="box d"><a href="movies/2019-ArticulatorMount/video01.m3u8" target="_blank"><img src="/img/04-Articulator-1000x684.jpg" alt="" width="200"/><br>咬合器装着ビデオ</a></div>
<div class="box d"><a href="movies/video04mp4/ProArchGI.mp4" target="_blank"><img src="/img/Pro-Arch-Ig.png" alt="" width="200"/><br>プロアーチIG咬合器装着ビデオ</a></div>
<div class="box e"><a href="movies/2019-wax-up/2019-wax-up.m3u8" target="_blank"><img src="/img/05-Waxup-1000x684.jpg" alt="" width="20"/><br>下顎右側第1大臼歯ワックスアップビデオ</a></div>
<div class="box f"><a href="movies/202001/202001.mp4" target="_blank"><img src="/img/06-metalplate.png" alt="" width="20"/><br>金属板の取り出し方法</a></div>
<!--<div class="box g">G</div>-->
<!--<div class="box h">H</div>-->
</div>
<!-- Gallery Grid End -minmax() in auto-fill repeating tracks, by example https://gridbyexample.com/examples/example28/ -->Check this out
Search:
- simple html photo gallery code
Simple list of images in html
(added the {sh} code and fence for Rmd coz of error rendering page. For md and mkdocs, delete the fence)
<img src="/docs/img/01-Incisor-1000x684.jpg" alt="HTML5 Icon" width="128" height="128">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:128px;height:128px;">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:100%;">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:30%;">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:30%;">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:30%;"><img src="/docs/img/01-Incisor-1000x684.jpg" alt="HTML5 Icon" width="128" height="128">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:128px;height:128px;">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:100%;">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:30%;">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:30%;">
<img src="/docs/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:30%;">† Does display in vs code preview,
Does not display in word md panel (preview),
Does display in mkdocs site,
It is also possible to set the size of all images at once with the
tags in heading. ex.
<!DOCTYPE html>
<html>
<head> <!--CAUTION: This is a head style! This will set the size of ALL images in the page, not only in this section but all the page -->
<style>
img {
width: 50%;
}
</style>
</head>
<body>
<img src="/img/01-Incisor-1000x684.jpg" alt="HTML5 Icon" width="128" height="128">
<img src="/img/02-Premolar-1000x684.jpg" alt="HTML5 Icon" style="width:128px;height:128px;">
.
.
.
</body>
</html>!!! warning CAUTION: This is a head style, it will set the size of ALL images in the page
Gallery using .md Table
| | | | |
|---|---|---|---|
| <div class="box a"><a href="movies/Video01/video01.m3u8" target="_blank"><img src="/img/01-Incisor-1000x684.jpg" alt="" width="30%"/><br>上顎左側中切歯ビデオ</a></div> | <div class="box b"><a href="movies/Video02/video02.m3u8" target="_blank"><img src="/img/02-Premolar-1000x684.jpg" alt="" width="200"/><br>上顎左側第1小臼歯ビデオ</a></div> | <div class="box c"><a href="movies/Video03/video03.m3u8" target="_blank"><img src="/img/03-Molar-1000x684.jpg" alt="" width="200"/><br>上顎左側第1大臼歯ビデオ</a></div> | |
|  | | | |Simple photo gallery, github free open source
Simple Photo Gallery - Vladimir Haltakovhttps://haltakov.net › simple-photo-gallery
Animated GIFs in HTML
<img src="programming.gif" alt="Computer Man" style="width:48px;height:48px;">
Image as Link
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;">
</a>Image Floating position in html
Use the CSS float property to let the image float to the right or to the left of a text:
<p><img src="smiley.gif" alt="Smiley face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p>
<p><img src="smiley.gif" alt="Smiley face" style="float:left;width:42px;height:42px;">
The image will float to the left of the text.</p>
Delete fence for mkdocs in the code below:
The image will float to the right of the text.
/img/~… path in:
Vs code: will NOT be diplayed
Mkdocs: WILL be displayed
Delete fence for mkdocs in the code below:
The image will float to the left of the text.
/docs/img/… path in:
Vs code: WILL be displayed
Mkdocs: will NOT be diplayed
Photo gallery samples
W3 school CSS photo gallery sample 1
<!-- coment this block coz it interfere with the mkdocs nav template
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<style>
/* Make the image fully responsive */
.carousel-inner img {
width: 100%;
height: 100%;
}
</style>
</head>
End head comment-->
<body>
<div id="demo" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ul class="carousel-indicators">
<li data-target="#demo" data-slide-to="0" class="active"></li>
<li data-target="#demo" data-slide-to="1"></li>
<li data-target="#demo" data-slide-to="2"></li>
</ul>
<!-- The slideshow -->
<div class="carousel-inner">
<div class="carousel-item active">
<img src="/img/01-Incisor-1000x684.jpg" alt="Los Angeles" width="1100" height="500">
</div>
<div class="carousel-item">
<img src="/img/02-Premolar-1000x684.jpg" alt="Chicago" width="1100" height="500">
</div>
<div class="carousel-item">
<img src="/img/03-Molar-1000x684.jpg" alt="New York" width="1100" height="500">
</div>
</div>
<!-- Left and right controls -->
<a class="carousel-control-prev" href="#demo" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#demo" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
</div>
</body>W3 school CSS photo gallery sample 2
w3schools photos Delete fence for mkdocs in the code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box;}
body {font-family: Verdana, sans-serif;}
.mySlides {display: none;}
img {vertical-align: middle;}
/*Slideshow container*/
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/*Caption text*/
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/*Number text (1/3 etc)*/
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/*The dots/bullets/indicators*/
.dot {
height: 10px;
width: 10px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active {
background-color: #717171;
}
/*Fading animation*/
.fade {
animation-name: fade;
animation-duration: 1.5s;
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
/*On smaller screens, decrease text size*/
@media only screen and (max-width: 300px) {
.text {font-size: 11px}
}
</style>
</head>
<body>
<h2>Automatic Slideshow</h2>
<p>Change image every 4 seconds:</p>
<div class="slideshow-container">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="/img/01-Incisor-1000x684.jpg" style="width:100%">
<div class="text">Caption Text</div>
</div>
<div class="mySlides fade">
<div class="numbertext">2 / 3</div>
<img src="/img/02-Premolar-1000x684.jpg" style="width:100%">
<div class="text">Caption Two</div>
</div>
<div class="mySlides fade">
<div class="numbertext">3 / 3</div>
<img src="/img/03-Molar-1000x684.jpg" style="width:100%">
<div class="text">Caption Three</div>
</div>
</div>
<br>
<div style="text-align:center">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<script>
let slideIndex = 0;
showSlides();
function showSlides() {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
setTimeout(showSlides, 4000); // Change image every 4 seconds
}
</script>
</body>
</html>
Resize batch files
!!! tip Batch Resize files.
Batch Rename files.
**Resize multiple images (resize img batch) in >_:**
sips -Z 600 *.jpg!!! danger
Original files will be changed, NO undo option available.
sips: sips command is used to query or modify raster image files (JPG/GIF/PNG) and ColorSync ICC profiles. Image processing options include flip, rotate, change image format/width/height. Its functionality can also be used through the “Image Events” AppleScript suite.
-Z: Maintain aspect ratio.
600: output width? size in pixels.
*.jpg: files to modify, in this case, all .jpg files in the current directory.
sips -Z 600 *.jpg --out ~/new/dir/path/and/name
This will create a new directory, make a copy of the files, modify size and save in the new directory.
Small Script to auto resize
Improve this script with user input.
#!/bin/bash
# Change format, and change max size. 20181231 DM
oldFormat=HEIC
newFormat=png
newSize=800
for i in *.$oldFormat
do
sips --setProperty format $newFormat --resampleHeightWidthMax $newSize "$i" --out "${i%$oldFormat}"$newFormat
done
exit 0Rename batch files
!!! check “Step By Step: Using The Mac Batch Rename Tool”
- Select all files you want to rename.
- Finder// File> Rename..Items > …[]… Rename Finder items: Find= text_to_find Replace with= Text_to_replace
!!! failure “**Rename all the files (rename batch) in >_: (not working, permission error)**”
!!! bug bash: ./03-Molar-1000x684.jpg: Permission denied
- Go to the directory containing files.
- run command:
find . -type f -exec bash -c `mv “$0” “${0% .jpg}-300.jpg”` {} ;find all the files in the current directory of this type of files
then, execute this command ? ? disregard the extension .jpg and add the suffix: -300.jpg
Md tables
Markdown table generator
- 1. Markdown Table Editor and Generator.
- 2. Tables Generator.
- 3. Copy Table in Excel and Paste as a Markdown Table.
- [ ]
!!! check “Md shortcut tables” - [ ] Selecting text (don`t know how separation is made (coma?, tab?, space?))
- [x] right click > Add table (with header)
- [x] Table will be automatically created
Tables created with Markdown Table Editor and Generator space cells width equally, much easer to see in raw md code but only up to 20 x 20 tables.
Tables created witn right click shortcut are in line separation and harder to see as raw data.
!!! tip ++alt+shift+f++ Table formatter. After creating the table with shortcut ( cell size depends on word lenght, difficult to read in raw data). This key command will arrange cell space to be qual. See Mardown all in one extension for more tips.
Photo gallery
HOW TO INSERT TABLES IN RSTUDIO.
A new RStudio addin to facilitate inserting tables in Rmarkdown documents
Copy Table in Excel and Paste as a Markdown Table
https://www.tablesgenerator.com/markdown_tables
Pandocs
What is Pandoc?: Is a universal document converter for:
- text markup (markdown). italics –> italics
- standalone files. .md –> .docx (or html, etc)
Install
macOS link
There is a package installer at pandoc’s download page. If you later want to uninstall the package, you can do so by downloading this script and running it with perl uninstall-pandoc.pl. Alternatively, you can install pandoc using Homebrew:
brew install pandocHomebrew can also install other software that integrates with Pandoc. For example, to install librsvg (its rsvg-convert covers formats without SVG support), Python (to use Pandoc filters), and BasicTeX (to typeset PDFs with LaTeX):
brew install librsvg python homebrew/cask/basictexNote: On unsupported versions of macOS (more than three releases old), Homebrew installs from source, which takes additional time and disk space for the ghc compiler and dependent Haskell libraries. We also provide a zip file containing the binaries and man pages, for those who prefer not to use the installer. Simply unzip the file and move the binaries and man pages to whatever directory you like. By default, Pandoc creates PDFs using LaTeX. Because a full MacTeX installation uses four gigabytes of disk space, we recommend BasicTeX or TinyTeX and using the tlmgr tool to install additional packages as needed. If you receive errors warning of fonts not found: tlmgr install collection-fontsrecommended
Using Pandoc
- Open >_
- Go to folder containing files (or use path to files)
- Ex. Txt -> RTF
pandoc test.txt --bibliography testlibrary.bib --smart --normalize -s -o success.rtf
- pandoc: use pandoc package
- test.txt: “input” file to be converted to .rtf
- –bibliography testlibrary.bib: Generate citations (bibliography) using bib file (all the metadata needed for the citations is in the file testlibrary.bib (created before), Default format is Chicago Author-Date)
- – smart: Produce topographically correct output.
- –normalize: Remove repeated spaces, other cleanup.
- -s: Produce a stand alone document.
- -o: output to a file.
- success.rtf: Is the name of the “output” file and the extension rtf is the type of file to convert to.
If input and bib files are not in the same folder where you run pandoc, you will need to include the file paths, too.
Convert Markdown into a Word Document
Enter:
pandoc -o output.docx -f markdown -t docx filename.md Academic Writing in Markdown
Here are three recommendations for people interested in learning more:
- The Markdown Field Guide: https://www.macsparky.com/markdown/
- The Pandoc website: http://pandoc.org/
- David Smith’s blog: http://www.davidsmith.name/
Create Mkdocs site
**Installed required (>_)**
#| eval: false
brew --version
python --version
brew list <formula1> || brew install <formula1>
brew install python3
brew install python@3.10
pip --version
pip3 install --upgrade pip
pip3 install mkdoc
brew install mkdocs (error)
pip3 install mkdocs-material
Other Plugins:
pip install mkdocs-static-i18n
pip install mkdocs-material **Create a site with Terminal (>_)**
mkdocs -h (help)
mkdocs new {dir-name}
cd {dir-name}
ls
tree
mkdocs serve
Cnt+C
# Other commands
code .
rstudio .
open -na Rstudio
open myproject.RprojThen continue by:
- Modify yml (simple, just to check if render)
- Theme, nav, plugs
- Create Tab2.md, Tab3.md, Tab4.md for trial
site_name: LabNotes
site_url: https://example.com_or_my.github
repo_url: https://github.com/squidfunk/mkdocs-material # url link of ripo in navbar
repo_name: squidfunk/mkdocs-material # name of ripo to be displayed in navbar
nav:
- Home:
- Hi: "index.md"
- Tab2: "01-Tab2.md"
- Tab3: "02-Tab3.md"
- Tab4:
- sub1:
- sub2:
- sub3:
- sub4: "03-Tab4.md"
theme: # https://squidfunk.github.io/mkdocs-material/setup/changing-the-colors/#accent-color
name: material
favicon: assets/NiigataUicon.png #small icon in the "browser`s" tap.Save @ /dir
features:
#- navigation.instant
- navigation.tabs #Nav tabs on top
- navigation.tabs.sticky # Keeps top nav menu from hiding.
#- header.autohide # Hides all top menu.
#- navigation.sections #uncollapse all tab sections.
- navigation.top
palette:
#primary: green # Color of the Header
#accent: red # Colors change on hover.
# Palette toggle for light mode
- primary: Default # The original was scheme: Default
accent: red # Colors change on hover.
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- scheme: slate
accent: light green # Colors change on hover.
toggle:
icon: material/brightness-4
name: Switch to light mode
accent: red # Colors change on hover.
logo: # assets/logo.png
assets/NiigataUicon.png
icon:
repo: fontawesome/brands/git-alt # repo icon
extra:
homepage: https://www.niigata-u.ac.jp/ # url for the logo icon
#include_sidebar: true
#===================================================================================
# Mkdocs Markdown Extentions, Plugins & extras
#===================================================================================
markdown_extensions:
- admonition
- abbr
- attr_list
- def_list
- footnotes
- meta
- md_in_html
- codehilite
- pymdownx.critic
- pymdownx.caret
- pymdownx.keys
- pymdownx.mark
- pymdownx.tilde
- pymdownx.tabbed
- pymdownx.details
- pymdownx.inlinehilite
- pymdownx.smartsymbols
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
- toc:
# insert a blank space before the character
permalink: "#"
plugins:
- glightbox # istall requied: images/lightbox
- search # add search box.
- i18n: # language plugin.
default_language: en
languages:
en: English
ja: 日本語
es: Español- Add content files: Copy/paste Tabs.md files
mkdocs serve
Cnt+C
mkdocs build ??
In github.com:
create git repo in github.com (follow recommendation of Hernandez?)
1. Github > create new repo >
name: {x: demo_docmaker } >
description {dockmaker demo} >
©Public >
© Add readme file >
© Add .gitignore: ˇ{R} >
© Create repository
- Repo settings > Pages >
Source: Deploy form a branch >
ˇBranch: © main > /(root) > ©save (new page is created)
- Got to // Code > code > clone > htpps (copy github page address)
https://github.com/MarceloRosales/mkd_LabNotes.git
Connect Mkdocs to Git >_:
git init
git add .
git status
Connect Mkdocs to Github repository >_:
git remote add origin {git_url}
Sometime requires:
git config –global user.name “MyGitAccount”
git config –global user.email “myemail.com”
git config credential.helper store
gedit gitignore (edit gitignore to don’t track files…??)
git commit -m “Initial Commit”
git status (empty)
git push origin master
Sometime requires:
type github username:
type github Password:
(push from local master branch to remote master branch)
Mkdocs site build and deploy >_:
mkdocs build
mkdocs gh-deploy
In github.com:
Make sure deploy branch is gh-pages.
1. Repo settings > Pages > Source: Deploy form a branch > ˇBranch: © gh-paages > /(root) > ©save (new page is created)
Adding content
After first commit:
Modify code. (and save files)
mkdocs build
mkdocs gh-deploy
git add .
git status
git commit -m “commit message”
git push origin master
Other git commands:
git reflog (past git logs)
git checkout -b other-branch (Switch to a new branch)
git branch -a (lists of branches)
rm -fr .git (remove git files)
git config –global user.name “MarceloRosales”
git config –global user.email “…@hotmail.com”
git config credential.helper store
git commit -m “1st commit”
git log # If want to revert to a preview’s version, Copy hash click Q to quit.
git checkout {hash copied from log}
git checkout -b {new branch name} # Create a new branch.
git branch {new branch name} {hash} # Create new branch, if revert to previous, add hash
git checkout {branch name} # To change branches
git merge {branch name} # merge branch to main
Create bs4_book in Rstudio
//Rstudio > New Project >
Book project using bookdown > …[]… >
Select book format: bs4_book >
© Open in new session.
Add 08-Preparation.Rmd
[Build] > Build Book >
bs4_book (wil convert .Rmd -> .md in /_book)
Creating symlinks
To make symlink:
ln -s /path/of/original/file /path/to/taget/dir/{filename} Box Sync/../.md -> ~/Documents/gitrepo/.md
Ex.
From: “/Users/marcelorosales/Box Sync/Github/mkdocs/bs4_LabNotes/_book/08-Preparation.md”
To: “/Users/marcelorosales/Documents/GitHub/Mkdocs_books/mkd_LabNotebooks/mkd_LabNotes/docs”
Samples “/Users/marcelorosales/Box Sync/Github/mkdocs/mkdocs_dumpAll/Samples/08-Preparation.Rmd”
ln -s "/Users/marcelorosales/Box Sync/Github/mkdocs/bs4_LabNotes/_book/08-Preparation.md" "/Users/marcelorosales/Documents/GitHub/Mkdocs_books/mkd_LabNotebooks/mkd_LabNotes/docs" ln -s "/Users/marcelorosales/Box Sync/Github/mkdocs/bs4_LabNotes/_book/08-Preparation.md" "/Users/marcelorosales/Box Sync/Github/mkdocs/mkdocs_dumpAll/Samples/08-Preparation.Rmd"!!! fail Partial address do NOT work.
“~/Box Sync/Github/mkdocs/bs4_LabNotes/_book/08-Preparation.md”
“~/Documents/GitHub/Mkdocs_books/mkd_LabNotebooks/mkd_LabNotes/docs”
ln -s “~/Box Sync/Github/mkdocs/bs4_LabNotes/_book/08-Preparation.md”
Allways work the in bs4_book .Rmd
R » md » mkdocs » githug
Crear páginas web con Rmarkdown, MkDocs y GitHub pages: una alternativa para documentación.
docmaker
!!! fail “Warning”
Not working as described in the tutorials
Overview
docmaker is a package that allows you to automate your steps for using GitHub pages, MkDocs and Rmarkdown.
If you have a project in which there are files built with Rmarkdown that you would like to take to MkDocs, docmaker will help you with the all the steps in the middle to achieve this.
Installation:
You can install the development version of docmaker from GitHub with:
#| eval: false
devtools::install_github("ronnyhdez/docmaker")When published on CRAN, you will be able to install the package with:
#| eval: false
install.packages("devtools")Usage
You can create your repository on GitHub, clone your repo and from there, you will need to implement a structure to be able to use GitHub pages and MkDocs. For this you can use the function:
#| eval: false
library(docmaker)
build_repo(github_page_url = "https://ronnyhdez.github.io/drawer/",
site_author = "Ronny A. Hernández Mora")Once you have a repository, you can take your Rmd notes and deploy it to GitHup pages
#| eval: false
make_doc(file = "check.Rmd", mkdocs_build = TRUE, mkdocs_deploy = TRUE)If you have several files in the root of your project directory, you can instead use the following function to build and deploy all your Rmd files:
#| eval: false
make_all_docs(deploy = TRUE)Getting help:
If you find a bug please fill an issue with a reproducible example on GitHub
Demo:
Video demo starts at 17:00 min.
dockmaker page
dockmaker blog English
Github Page
requirements:
- python - R - mkdocs - git - github account - docmaker installed in r
In Github
1. Github > create new repo > name: {x: demo_docmaker } > description {dockmaker demo} > ©Public > © Add readme file > © Add .gitignore: ˇ{R} > © Create repository
1. Repo settings > Pages > Source > ˇBranch: © main > /(root) > ©save (new page is created)
1. Got to // Code > code > clone > htpps (copy github page address)
In Rstudio
1. // New project > Version control > Git > Repository URL: {paste github repo address} > …[]… choose directory: (/Documents/github or github_repos, don’t use sync folders > ©ü Open in new session > © Create project.
- If error: Repository Already exists >Go // Open Project (in New Session) > …[]… > select folder > Open
In Rstudio console
1. Load docmaker library and make sure you are in the correct working directory.
#| eval: false
library(docmaker)
getwd()- Built the mkdocs repository (through docmaker function)
!!! bug “outdated”
///////////////// Outdated
dockmaker::build.repo() # or? build_repo(github_page_url, site_author) 1. Configure repo
dockmaker::build.repo(github_page_url = "https://myname.github.io/ex:demo_docmaker/", site_author = "My Name") //////////////////
- Build and configure repo: Updated code 2022
build_repo(github_page_url = "https://github.com/MarceloRosales/docmakertest2.git", site_author = "Marcelo Rosales")
- It creates a “docs” folder (empty) and a .yml file
- Open .yml file and modify as for mkdocs site: theme: material, nav … etc
Add content 1. // New Rmarkdown > write content… 1. // New folder > {img} > place all images here (this img folder is outside of docs).
1. Now add Rmd files to github (through >_).
**In >_**: 1. Check all modified or added files not yet commited (Rmd or images)
git status- Stage all files
git add .- Commit all files
git commit -m “estructura del repositorio y primeras notas”- Because is first time adding in the new git repo it will not commit, git will ask ” *** Please tell me who you are… “, Run:
git config user.email myemail@github
git config user.name mynameingithub- Repeat Commit all files
git commit -m “estructura del repositorio y primeras notas”- Push all files to git. Will ask username and password.
git push- To avoid typing credential on every commit and pull
git config credential.helper store- To pull form github
git pullUp to here we just added contents, but in github the doc folder is not added (coz is empty) and github pages is only rendering form the readme.md file (28:35).
To construct the mkdocs pages in Rstudio console make the .md files 1. In Rstudio > Console > If Docmaker::make_all_docs() or Docmaker::make_all_docs(FALSE), it is not going to construct the documentation in github. It is going to render in local computer, like a preview or the page before commiting to github.
!!! bug “outdated”
///////////////// Outdated
Docmaker::make_all_docs(TRUE) or docmaker::make_all_docs(deploy = TRUE) //////////////////
Update 2022
make_all_docs(deploy = FALSE)
make_all_docs(deploy = TRUE)
!!! warning This will create .md files, images, plots, etc and it will commit-push to githubpages automatically
docmaker::make_doc is to make md from Rmd one by one.
make_doc(file = "check.Rmd", mkdocs_build = TRUE, mkdocs_deploy = TRUE)
- Go back to github > code > (next to branches) ˇmain > ©gh-pages. Do not merge with main brach.
- Go Setting >Source > ˇBranch: gh-pages; (/root) > save
!!! fail
THIS DOCMAKER PACKAGE IS NOT WORKING, THERE IS AN ERROR WHILE CONVERTING THE RMD TO MD FILES.
Fail Solutions:
- Check and correct package code (with cran, issue to author or self)
- Find alternative conversion.
How to convert .Rmd into .md in R studio? [duplicate]
#| eval: false
---
title: "Example"
author: My Name
date: March 22, 2050
output: md_document
# or
output:
md_document:
variant: markdown_github
---knitr output to a different folder
---
title: "Tab1"
author: "Marcelo Rosales"
date: "2022-08-16"
output: md_document
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, encoding = encoding, output_dir = "docs") })
editor_options:
chunk_output_type: console
---
save rmarkdown output in different folder R: In RStudio how do I make knitr output to a different folder to avoid cluttering up my drive?
In console: rmarkdown::render('my.Rmd', output_file = 'folder/my.html')
- Disregard and move on!!!.
examples:
Search: rstudio how to deploy a mkdocs project
https://github.com/rstudio/team-admin.rstudio.com/blob/main/mkdocs.yml
https://team-admin.rstudio.com/getting-started/how-it-works/ nice page in github (seems it was made in Rstudio) with white background
https://leverage.binbash.com.ar/ Nice page created with Mkdocs with custom land pages. Github repo
Ultrabug: see Automatic mkdocs gh-deploy and plugin extensions, and video, web site at ultrabug
https://github.com/ultrabug/ultrabug.fr
Trial pages:
/Users/Marcelo-Rosales/Documents/GitHub_Repos/MkDocsTest1
/Users/marcelorosales/Documents/GitHub/MkDocsTest1: gh-pages active, only .md, no Rmd.
- index.en.md - index.es.md - index.ja.md - MkDocs.md: Mkdocs good info, move to archive
- VS_Code.md: Vs code demo.. archive.
/Users/marcelorosales/Box Sync/Github/mkdocs/MBA03: No gh-pages constructed, actually; DO NOT CONSTRUCT /SITE, only local, that’s why it is in Box Sync
- All.md: All notes are here
- index.md: Welcome to MkDoc
- Tab1.md: Mkdocs Markdown guide
- Tab2.md: Images and Galleries Tests
- Tab3.md: Markdown and Visual Studio Code
- Tab4.md: Html guide
/Users/marcelorosales/Documents/GitHub/MBP20mkdocsT01: Page not working (deleted)
Init.Rmd: - Docmaker package guide - Docmaker package functions code: make_all_docs, make_doc.
/Users/marcelorosales/Documents/GitHub/MBP20mkT02: Empty 404 site (deleted)
/Users/marcelorosales/Documents/GitHub/MBP20mkT03: Empty site.
/Users/ rosalesrocabadomarcelo/Documents/GitHub/mkdocs/MBAdocmaker01: No gh-page, no /site. In github: Yes, In github desktop: NO MBP15: None.
MBP20: None.
MBA11: Yes. Only test. Delete
/Users/Marcelo-Rosales/Documents/GitHub_Repos/docmaker_demo2/Init.Rmd: No /site.
- Init.Rmd: How to use docmaker tutorial (moved Rmd to dump).
mkt2: https://marcelorosales.github.io/mkt2/Page3/ Where are the files? Not in MBP20, just a test delete.
Word table: PC MBP20 MBP15 MBA11 /folder /Users/marcelorosales/Documents/GitHub/MkDocsTest1 /Users/Marcelo-Rosales/Documents/GitHub_Repos/MkDocsTest1
GH desktop yes yes Gh-page yes
Details only .md`s no .Rmd
R: In RStudio how do I make knitr output to a different folder to avoid cluttering up my drive?
Dumpall
Overview
1.Working with different file types is difficult and confusing. Here I mainly work with .R, .Rmd, .md, docx, excel, python, .html. Notting and keeping record is challenging. But I think I finally found a good workflow.
Notes and reports:
- Use MS word (.docx) file to keep record of all research, it is easy to manage tables and figures, however:
- Download Markdown add in: // Insert > Add ins > Get add ins > …[]… > Search {markdown} > ©Markdown (britva Technologies LLC) > Add
- Keep all notes in word but written as markdown, you can use the markdown viewer panel. Try not to make the file too long, md preview pane will slowdown computer
- Keep notes by date, dump all in one folder with Sync service (Box Sync).
- Keep track of all note changes: Turn ON track changes, // Review > Track changes: ON > SimpleMakup (red line to the left of doc).
- Create a gh-page to organize all notes and reports. I recommend Bookdown or mkdocs. Mkdocs seems sleeker and more compact.
- Copy paste the notes from word to Rstudio (as md or Rmd?) for now I think as .md, it is easier to go from md to Rmd than Rmd to md.
- Once copied to gh-page, highlight copied section, and use the // Track changes > Accept This change, to indicate that the section was been pushed.
- Use mainly R and Rstudio, will make things easer on the long run, vs code is also good for keeping track of changes, statistical analysis and reports.
Create mkdocs directory.
- Do not create new project in Rstudio, mkdocs will create the folder, use terminal.
- If scripting is in r; open new session // Session > New Session
# In >_
:
cd ~/Documents/GitHub
mkdocs new {dirname}
cd ~/Documents/GitHub/{dirname}
ls
tree
# Check if create correctly.
# WARNING: Close all browser tabs connected. If Browser tab is or was connected: http://127.0.0.1:8000/All/ code 404
mkdocs serve
# To stop live preview **`Cnt+C`**
touch home.md
# Add content, mod .yml
# Git and git command list:
git init
git add .
git status
git config
git config --global user.name “MarceloRosales”
git config --global user.email “selasorolecram@hotmail.com”
git commit -m "1st commit"
git log # If want to revert to a previews version, Copy hash click Q to quit.
git checkout {hash copied from log}
git checkout -b {new branch name} # Create a new branch.
git branch {new branch name} {hash} # Create new branch, if revert to previous, add hash
git checkout {branch name} # To change branches
git merge {branch name} # merge branch to main
# ref: https://youtu.be/DVRQoVRzMIY
# 2. Create repository in github.
# Copy github address
git remote add origin {https//github.com/MarceloRosales/test_.git
# https://github.com/MarceloRosales/MBP20mkT02.git
git checkout master # makesure you are in master branch
git push -u origin master # push commits to the "origin" repo and to the branch "master"; -u = save settings (next time with just "git push" will automatically add to the origin master.)
# Some times it requies
git push origin {other branch name} # to commit changes to a different branch.
git config --global user.name “MR”
git config --global user.email “….@hotmail.com”
git pull origin master
mkdocs build
git add .
git status
git commit -m "2nd commit"
git push
mkdocs gh-deploy
Non stop workflow Example
cd ~
mkdocs new MBP20mkT03
ls
cd ~/Documents/GitHub/MBP20mkT03
ls
mkdocs serve
# Change .yml file
theme:
name: material
palette:
primary: white
accent: #75AADB
font:
text: Source Sans Pro
mkdocs serve
# Create repository in github and **Copy github address**.
#make the /site folder.
mkdocs build
git init
git add .
git status
git config --global user.name “MR”
git config --global user.email “....@hotmail.com”
git remote add origin https://github.com/MarceloRosales/MBP20mkT03.git
git commit -m "1st commit"
git status # nothing to commit, working tree clean
git push origin master
mkdocs build # necessary?
mkdocs gh-deploy # all settings to deploy in github -branch gh-pages
git status
git add .
git commit -m "2nd commit"
git push origin master
# Add content
git pull origin master
mkdocs serve
mkdocs build
git add .
git status
git commit -m "3rd commit"
git push origin master
mkdocs gh-deploy creates 2 branches + the default github branch “main”: - gh-pages - master - main
The “main” branch contains: - .gitignore file - License - readme.md
The “master” branch contains: - /doc - /site - mkdocs.yml
The gh-pages contains: only all the files created in the /site folder; it mirrors the /site content to create the wegpage.
Docmaker trials
Init.Rmd in MBP20mkdocsT01
See also mkdocs_demo.Rmd too
~/Documents/GitHub/MkDocsTest1 Config git ignore like in video?
library(docmaker)
build_repo(github_page_url = "https://github.com/MarceloRosales/MBP20mkdocsT01.git", site_author = "Marcelo Rosales")
git status
git add .
git commit -m "1 commit"
git push
git pull
docmaker::make_all_docs(deploy = TRUE)
make_doc(file = "Tab1.Rmd")
make_doc function run for the first time will execute the creation of the md file and the corresponding plot image folder in the docs folder. Error for the Error UseMethod(“close”) : no applicable method for ‘close’ applied to an object of class “character”
If run for a second time, it will create the plot images folder in root and NOT in the docs folder.
Docmaker fx code
R: In RStudio how do I make knitr output to a different folder to avoid cluttering up my drive?
Yml code added examples
~/Documents/GitHub/MBP20mkT03 MBP20mkT03.Rproj Overview.Rmd
Overview.md
docs
mkdocs.yml: Color theme is white:
site_name: My Docs
theme:
name: material
palette:
primary: white
accent: #75AADB
font:
text: Source Sans Pro
nav:
- Home: index.md
- Overview: Overview.md
/Users/marcelorosales/Documents/GitHub/MBP20mkdocsT01
title: "Tab1"
author: "Marcelo Rosales"
date: "2022-08-16"
output: md_document
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, encoding = encoding, output_dir = "docs") })
editor_options:
chunk_output_type: console
Added section
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, encoding = encoding, output_dir = "docs") })Example 1:
team-admin.rstudio
https://team-admin.rstudio.com/getting-started/how-it-works/ nice page in github (seems it was made in Rstudio) with white background
site_name: "RStudio Team :: Admin Training"
repo_url: https://github.com/rstudio/team-admin.rstudio.com
copyright: RStudio, PBC. All Rights Reserved.
google_analytics:
- UA-20375833-3
- auto
edit_uri: ""
theme:
name: material
custom_dir: overrides
logo: 'images/rstudio-logo.png'
favicon: 'images/favicon.ico'
palette:
primary: white
accent: #75AADB
font:
text: Source Sans Pro
nav:
- Home: index.md
- Overview: overview.md
- 1. Getting started: <!-- #this is a folder, inside are the md files -->
- 1.1 How the course works: getting-started/how-it-works.md
- 1.2 Lab - SSH in: getting-started/lab-ssh-in.md
- 2. R:
- 2.1 Installing R: r/install-r.md
- 2.1 Lab: r/lab-install-r.md
- 3. RStudio Workbench:
- 3.1 Install RStudio Workbench: rstudio-workbench/install-rsw.md
- 3.1 Lab: rstudio-workbench/lab-install-rsw.md
- 3.2 RStudio Workbench Security: rstudio-workbench/security.md
- 3.2 Lab: rstudio-workbench/lab-security.md
- 3.3 RStudio Workbench Startup and packages: rstudio-workbench/startup-and-packages.md
- 3.3 Lab: rstudio-workbench/lab-startup-and-packages.md
- 4. RStudio Connect:
- 4.1 Installing RStudio Connect: rstudio-connect/install-connect.md
- 4.1 Lab: rstudio-connect/lab-install-connect.md
- 4.2 Configuring RStudio Connect: rstudio-connect/configure-connect.md
- 4.2 Lab: rstudio-connect/lab-configure-connect.md
- 4.3 Using RStudio Connect: rstudio-connect/using-connect.md
- 4.3 Lab: rstudio-connect/lab-using-connect.md
- 5. Deploying to Connect:
- 5.1 Deploying Shiny Apps: using-rstudio-connect/deploy-shiny.md
- 5.2 Lab: using-rstudio-connect/lab-deploy-shiny.md
- 5.3 Deploying Rmarkdown: using-rstudio-connect/deploy-markdown.md
- 5.4 Lab: using-rstudio-connect/lab-deploy-markdown.md
- 5.5 Deploying plumber APIs: using-rstudio-connect/deploy-plumber.md
- 5.6 Lab: using-rstudio-connect/lab-deploy-plumber.md
- 9. Troubleshooting:
- 9.1 Troubleshooting: troubleshooting/troubleshoot.md
- 9.2 Lab: troubleshooting/lab-troubleshoot.md
- "---": separator.md
- Cheat sheet: cheatsheet.md
- Documentation: documentation.md
- Frequently encountered problems: faq.md
- Asking questions: asking-questions.md
markdown_extensions:
- toc:
permalink: "#"
- admonition
- pymdownx.arithmatex
- pymdownx.betterem:
smart_enable: all
- pymdownx.caret
- pymdownx.critic
- pymdownx.details
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
- pymdownx.inlinehilite
- pymdownx.magiclink
- pymdownx.mark
- pymdownx.smartsymbols
- pymdownx.superfences
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.tabbed
- pymdownx.tilde
extra_css:
- assets/custom.css
- assets/cheatsheet.css
extra_javascript:
- assets/js/asciinema-player.js
- assets/js/openLinksInNewTabs.js
plugins:
- search
# - redirects:
# redirect_maps:
# overview/concept-map: overview.md
# overview/coarse-goals: overview.md
# overview/assumptions: overview.md
# overview/pre-requirements: overview.md
# overview/how-it-works: overview.md
# get-started: getting-started/how-it-works.md
# get-started/getting-started: getting-started/how-it-works.md
# get-started/ssh-in: getting-started/lab-ssh-in.md
# install-r: r/install-r.md
# install-r/install-r: r/install-r.md
# install-r/install-r-exercise: r/lab-install-r.mdExample 2:
https://leverage.binbash.com.ar/ Nice page created with Mkdocs with custom land pages. Github repo
# ref link: https://alinex.gitlab.io/env/mkdocs/
# Site Information
site_name: Binbash Leverage™
repo_name: "binbashar/le-ref-architecture-doc"
repo_url: https://github.com/binbashar/le-ref-architecture-doc
site_url: https://leverage.binbash.com.ar/
site_description: Binbash Leverage Reference Architecture Documentation
site_author: Binbash
copyright: Copyright © 2017-2022 <a href="https://www.binbash.com.ar">Binbash</a>
# Mkdocs Theme (Material Mkdocs) + Extras
theme:
name: material
custom_dir: material
language: en
#logo: assets/images/logos/binbash-icon.png
icon: # https://www.materialpalette.com/icons
logo: material/book-open-page-variant
favicon: assets/images/logos/favicon.ico
font:
text: Roboto
code: Roboto Mono
features:
- navigation.tabs
- navigation.instant
- header.autohide
#- content.tabs.link #Insiders only so far
palette: # https://www.materialpalette.com/colors
- scheme: default
#primary: "teal" # comment to replace by /docs/assets/stylesheets
accent: deep purple
toggle:
icon: material/toggle-switch-off-outline
name: Switch to dark mode
- scheme: slate
#primary: "teal" # comment to replace by /docs/assets/stylesheets
accent: teal
toggle:
icon: material/toggle-switch
name: Switch to light mode
include_sidebar: true
extra:
analytics:
provider: google
property: !ENV GOOGLE_ANALYTICS_KEY
## Temporally only available for Insiders
## (https://squidfunk.github.io/mkdocs-material/setup/setting-up-site-analytics/#was-this-page-helpful)
# feedback:
# title: Was this page helpful?
# ratings:
# - icon: material/emoticon-happy-outline
# name: This page was helpful
# data: 1
# note: >-
# Thanks for your feedback!
# - icon: material/emoticon-sad-outline
# name: This page could be improved
# data: 0
# note: >-
# Thanks for your feedback! Help us improve this page by
# using our <a href="..." target=_blank>feedback form</a>.
social:
- icon: material/home
link: 'https://www.binbash.com.ar'
- icon: material/github
link: 'https://github.com/binbashar'
- icon: material/linkedin
link: 'https://www.linkedin.com/company/binbash'
- icon: material/slack
link: 'https://join.slack.com/t/binbashar/shared_invite/zt-fw1692b6-9k4ADsWJ47lKacszphXM1w'
- icon: material/youtube
link: 'https://www.youtube.com/channel/UCUjQ3duzxQB_VtNsKNqPwDA/playlists'
- icon: fontawesome/brands/medium
link: 'https://medium.com/binbash-inc'
- icon: material/twitter
link: 'https://twitter.com/binbash_devops'
- icon: material/docker
link: 'https://hub.docker.com/orgs/binbash'
alternate:
# Switch to English
- name: English
#link: https://leverage.binbash.com.ar
link: /
lang: en
# Switch to Spanish
- name: Spanish
#link: https://leverage.binbash.com.ar/es/
link: /es
lang: es
# Mkdocs Markdown Extentions, Plugins & extras
markdown_extensions:
- admonition
- abbr
- attr_list
- def_list
- footnotes
- meta
- md_in_html
- codehilite
- pymdownx.critic
- pymdownx.caret
- pymdownx.keys
- pymdownx.mark
- pymdownx.tilde
- pymdownx.tabbed
- pymdownx.details
- pymdownx.inlinehilite
- pymdownx.smartsymbols
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
- toc:
# insert a blank space before the character
permalink: " ¶"
plugins:
- search
# - awesome-pages
extra_css:
- assets/stylesheets/extra.css
# Mkdocs Navigation Tree
nav:
- Home:
- Home: index.md
- Welcome: "welcome.md"
- First steps: "first-steps/introduction.md"
- How it works:
- Reference Architecture:
- Overview: "how-it-works/ref-architecture/index.md"
- General concepts:
- Why Leverage?: "how-it-works/ref-architecture/general-concepts/why-leverage.md"
- Why our stack?: "how-it-works/ref-architecture/general-concepts/why-tech-stack.md"
- Considerations: "how-it-works/ref-architecture/considerations.md"
- Work with us:
- Overview: "work-with-us/index.md"
- Support:
- Support: "work-with-us/support.md"
- Releases:
- Releases and Versions: "work-with-us/releases/releases-and-versions.md"
- Versions compatibility matrix: "work-with-us/releases/versions-compatibility-matrix.md"
- Leverage vs Competition: "work-with-us/leverage-vs-competition.md"
#- Subscription Plans: "work-with-us/subscription-plans.md"
- Contribute: "work-with-us/contribute.md"
- Roadmap:
- Reference Architecture:
- Overview: "work-with-us/roadmap/ref-arch/overview.md"
- Operational Excellence: "work-with-us/roadmap/ref-arch/operational-excellence.md"
- Reliability & Performance: "work-with-us/roadmap/ref-arch/reliability-performance.md"
- Security: "work-with-us/roadmap/ref-arch/security.md"
- Cost Optimization: "work-with-us/roadmap/ref-arch/cost-optimization.md"
- Demo Applications: "work-with-us/roadmap/ref-arch/demo-apps.md"
- Leverage CLI: "work-with-us/roadmap/leverage-cli/overview.md"
- Careers: "work-with-us/careers.md"
#- Team: "work-with-us/team.md"
#- Testimonials: "work-with-us/testimonials.md"
- FAQs: "work-with-us/faqs.md"
- Contact Us: https://www.binbash.com.ar/contactR: In RStudio how do I make knitr output to a different folder to avoid cluttering up my drive?
Bookdown and GitHub Pages
Bookdown and GitHub Pages
==Git book is the default theme for bookdown.==
- [ ] [Gitbook style]( https://bookdown.org/yihui/bookdown/html.html)
- [ ] [The Material Design theme in the rmdformats package in bookdown]( https://bookdown.org/yihui/rmarkdown/rmdformats.html)
How to change colors and attributes of Table of Contents in R Markdown HTML document?
!!! note SEE THIS TWO‼
- [ ] [memoiR]( https://ericmarcon.github.io/memoiR/ ). Templates to publish well-formatted documents both in HTML and PDF formats In R Markdown.
Gallery:
- HTML GitBook
- HTML Bootstrap 4 book (documentation on Zotero, Shyni, very extensive. R34D I7!!!. Docs, writing a bs4_book
- Simple Article
+ HTML Document
+ Downcute HTML
+ distill article
- [Zotero](https://ericmarcon.github.io/WorkingWithR/chap-logiciels.html#sec:Zotero)
R Markdown and Bookdown Templates to Publish Documents
- [ ] [Pkdown](https://pkgdown.r-lib.org/) pkgdown is designed to make it quick and easy to build a website for your package with R studio.
- [ ] https://rmarkdown.rstudio.com/gallery.html
Get Started With Our Bookdown Thesis Template video https://youtu.be/LBHxcuCMjnk
My lecture notes Rmd template • lecturenotes - Grant McDermott
Change toc_depth field in bookdown pdf output
Use with zotero!!
To insert citations with Zotero in Rstudio:
© [visual]… ++shift+cmd+F8++
Opt+cmd+T ++shift+cmd+I++ ++shift+cmd+F7++
- {rticles} for document formatting
- {Zotero Plugin} for citations
- {report} & {glue} for making reproducible model summaries
- {gt} + {gtsummary} for tables
- {ggplot} + {ggpubr} for graphs
R packages required:
install.packages(“memoiR”) install.packages(“distill”) install.packages(“rmdformats”) install.packages(“rmarkdown”)
library(memoiR) library(distill) library(rmdformats) library(rmarkdown)
Types of books–> html
Avoid using the straight brackets, [] like in [Build] coz it confuse gitbook as a reference.
1. Website using blogdown
2. Book project using book down
- gitbook
- bs4_book: [Bulild]:
1. bs4_book. converts .Rmd to .md automatically‼‼ saved on /_book.
2. epub_book.
3. R Package using devtools
4. Distill Blog
- [Bulild]: 1. Distill_blog.
5. Distill Website
- [Bulild]: 1. Distill_site.
6. Document Project using memoiR
- Memoir: [Bulild]
1. git_book. OK
2. bs4_book. OK
3. ePub_book. OK
- Simple Article: ++Knit++
1. html_document2. OK
2. git_book. OK
3. downcute. OK
- Stylish Article: ++Knit++
1. html_document2. NOT WORKING!
2. git_book. OK
3. downcute. OK
- Beamer Presentation: ++Knit++
1. beamer_presentation2. NOT OK
2. Powerpoint_presentation2. OK
3. slidy_presentation2. ?
4. ioslide_presentation2. ?
7. Simple R Markdown Website
- [Bulild]: 1. Rmd_website. OK
R books samples view:
MBP20
gitbook:
bs4_book:
Distill_blog:
Distill_website:
[MemoiR:] - gitbook
- bs4_book
- Simple Article: ˇKnit: Html_document2
- Stylish Article: ˇKnit: downcute:
Simple Rmarkdown Website:
Idea:
bs4_book, converts .Rmd to .md automatically‼‼ saved on /_book. Create bs4 in Rstuidio @ BoxSync –> build .md files => Create Mkdocs with github in /Doc/github –> for .md files use symlink to bs4.md’s => build page –> push to github.
Why use Mkdocs instead of just using the Rbookdown::bs4? Mkdocs admonitions are much easy to follow and nice clean layout.
Book projects using bookdown
- gitbook
- bs4_book: It converts .Rmd to .md automatically‼‼ saved on /_book.
.Rmd files –> to –>.md files in /_book folder.
Distill Blog and Distill Website
//Environment > Build > Build Website
Document Project using memoiR
Memoir
Build tab
Gitbook (working)
Bs4_book (working)
_output.yml: Theme: primary: “#092872” (color)
Epub_book (working, save in books app. )
Simple Article
No Build tab
Html_document2 (working)
Gitbook (working)
Downcute (working)
Stylish Article
No Build tab
Html_document2 (Not Working)
Gitbook (working)
Downcute (working)
Beamer Presentation
No Build tab
Beamer_presentation2: Not working
[WARNING] Deprecated: --self-contained. use --embed-resources --standalone
! LaTeX Error: File `framed.sty’ not found.
! Emergency stop.
powerpoint_presentation2: Working
Memoir Simple Article Stylish Article Beamer Presentation
Simple R Markdown Website
For more information about simple R Markdown websites, please read the documentation at https://bookdown.org/yihui/rmarkdown/rmarkdown-site.html.
Please also note that simple R Markdown sites are not based on blogdown. They are probably good for websites with only a few Rmd documents. For larger-scale and more sophisticated websites (such as blogs), you may want to use blogdown instead: https://github.com/rstudio/blogdown.
Hugo: use / set up
- Install golang.
- Install hugo. @ https://gohugo.io/ Mac
brew install hugo - brew should have updated your path to include Hugo. You can confirm by opening a new terminal window and running a few commands:
<!--- # show the location of the hugo executable -->
which hugo
$ /usr/local/bin/hugo
<!--- # show the installed version -->
ls -l $( which hugo )
$ lrwxr-xr-x 1 mdhender admin 30 Mar 28 22:19 /usr/local/bin/hugo -> ../Cellar/hugo/0.13_1/bin/hugo
<!--- # verify that hugo runs correctly -->
hugo version
$ Hugo Static Site Generator v0.13 BuildDate: 2015-03-09T21:34:47-05:00
Build from Source: To compile Hugo yourself
rew install go.Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add.
You can also
New project >
Quarto
Summary
- Create New quarto project.
File > New Project > New directory > Quarto website > Browse: ~/Documents/GitHub/Quarto; dir name: descSPIM_LSmicro > create repository.
Files:
- Renv » + styles.css » + _quarto.yml + renv.lock + about.qmd + index.qmd + Research_Notes_230601.Rproj
Files + hiden files:
- .git » - .Rproj.user » - Renv » + styles.css + _quarto.yml + .gitignore + renv.lock + about.qmd + index.qmd + Research_Notes_230601.Rproj
Render Q site files:
- _site » - .git - .quarto
- .Rproj.user - renv + styles.css + _quarto.yml + .gitignore + .Rprofile + renv.lock + about.qmd + index.qmd + Research_Notes_230601.Rproj
Open files: index.qmd, _quarto.yml
Folder contains: styles.css about.qmd index.qmd descSPIM_LSmicro.Rproj _quarto.yml
- Configure _quarto.yml file nav
Auto-completion works by pressing tab. Careful!! tab level influence auto-complation options. If in the wrong level, then option will not be found.
See: Website Navigation Page Layout
Create scss files for theme and theme-dark options:
theme.scss
/*-- scss:defaults --*/
$link-color: #39729E;
$text-muted: #6a737b;
// Navigation element colors
$footer-bg: #181818;
$navbar-bg: #EEEEEE ;
/*-- scss:rules --*/
.layout-example {
background: $gray-500;
color: $white;
text-align: center;
margin-bottom: 1em;
font-family: $font-family-monospace;
font-size: .875em;
font-weight: 600;
padding-top: 1em;
border-radius: 3px;
}
.left {
text-align: left;
padding-left: 1em;
}
.right {
text-align: right;
padding-right: 1em;
}
.hello-quarto-banner h1 {
margin-top: 0;
margin-bottom: 0.5rem;
}theme-dark.scss
/*-- scss:defaults --*/
// Base document colors
$body-bg: #181818;
$body-color: white;
$link-color: #75AADB;
$light: #525252;
// Navigation element colors
$footer-bg: #181818;
$navbar-bg: #303030;
// Code blocks
$code-block-bg-alpha: -.8;
// Bootstrap popovers
$popover-bg: #242424;
// Bootstrap inputs
$input-bg: #242424;
$dropdown-bg: $body-bg;
$dropdown-color: $body-color;
$dropdown-link-color: $body-color;
$dropdown-link-hover-bg: $gray-600;
$dropdown-link-hover-color: white;
/*-- scss:rules --*/
.layout-example {
background: $gray-700;
}- Render the created page and check status.
Build > Render Web site
Folder now contains: _quarto.yml docs styles.css about.qmd index.qmd descSPIM_LSmicro.Rproj theme-dark.scss theme.scss
- Add a .nojekyll file to the root of your repository that tells GitHub Pages not to do additional processing of your published site using Jekyll (the GitHub default site generation tool). see: Quarto-GitHub Pages
#| eval: false
touch .nojekyll- Connect to GitHub.
Go to GitHub account > Create New Repository > Repo name > Add description > Create Repo
Git ignore: R files
In github.com:
1. Github > create new repo > name: > description: > ©Public > © Add readme file > © Add .gitignore: ˇ{R} > © Create repository
1. Repo settings > Pages > Source > ˇBranch: © main > /(root) > ©save (new page is created)
1. Got to // Code > code > clone > htpps (copy github page address)
git ignore R files copy the repo_url
**Connect Quarto website to Github with >_:**
git init
git config –global init.defaultBranch main # New repos will use “main” as default branch. git branch -m main # changes the name of branch from “master” to “main” git add .
git status
git config –global user.name
git config –global user.email <myemail.com> # (hot)
git commit -m “Initial Commit”
git status # (empty)
gedit gitignore (edit gitignore to don’t track files…??)
Messages: (Solved) @ git init: Using ‘master’ as the name for the initial branch. This default branch name is subject to change. To configure the initial branch name to use in all of your new repositories, which will suppress this warning, call: git config –global init.defaultBranch
**>_:**
git remote add origin
! [rejected] main -> main (fetch first) error: failed to push some refs to ‘https://github.com/MarceloRosales/descSPIM_LSmicro.git’ git pull * [new branch] main -> origin/main There is no tracking information for the current branch. Please specify which branch you want to merge with.
What to do when git push is rejected Solution 1
git pull origin main git push origin main
! [rejected] main -> main (fetch first) error: failed to push some refs to ‘https://github.com/MarceloRosales/descSPIM_LSmicro.git’ Solution 2 (solved)
git push -f origin main # Forces push, careful!! deletes one of the branches (local?/remote?)
type github username: type github Password: (push from local main branch to remote main branch)
===================================
Up to now, there have been conflicts conectig github and local repo; this might help. Try next time.
See: https://quarto.org/docs/publishing/github-pages.html
Publish Command The quarto publish command is an easy way to publish locally rendered documents and websites. Before attempting to use quarto publish (either locally or from a GitHub Action) you should be sure to configure the Source Branch and Ignore Output as described below.
Source Branch Before attempting to publish you should ensure that the Source branch for your repository is gh-pages (now is
) and that the site directory is set to the repository root (/) (now
). You can modify these options in Settings : Pages for your repository.
git checkout --orphan gh-pages # main?
git reset --hard # make sure you've committed changes before running this!
git commit --allow-empty -m "Initialising main branch"
git push origin gh-pages # main? fatal: a branch named 'gh-pages' already exists
HEAD is now at cb777f4 Initialising main branch
[master 2b12c59] Initialising main branch
Everything up-to-date
Ignoring Output It’s important to note that you don’t need to check your _site or _book directory into version control (if you have done this in the past you know it makes for very messy diffs!). Before proceeding you should add the output directory of your project to .gitignore. For example:
.gitignore
/.quarto/
/_site/
If you’ve already checked these files into source control you may need to remove them explicitly:
git rm -r _siteSee also Freezing Computations.
===================================
After first commit:
Modify code. (and save files)
Render
git add .
git status
git commit -m “commit message”
git status
git push git pull
Other git commands:
git reflog (past git logs)
git checkout -b other-branch (Switch to a new branch)
git branch -a (lists of branches)
rm -fr .git (remove git files)
git config –global user.name “MR”
git config –global user.email “…@ho”
git config credential.helper store
git commit -m “1st commit”
git log # If want to revert to a preview’s version, Copy hash click Q to quit.
git checkout {hash copied from log}
git checkout -b {new branch name} # Create a new branch.
git branch {new branch name} {hash} # Create new branch, if revert to previous, add hash
git checkout {branch name} # To change branches
git merge {branch name} # merge b[](https://qiita.com/Takao_/items/5e563d5ea61d2829e497)ranch to main
Deploy to github pages:
Settings > Pages > Branch:
, built: > save
link address will be display at the top of the GitHub Pages Github Pages > Your site is live at….
Set address in Repo profile:
Code > About (gear icon) > …[]… > website: use you GitHub Pages website
Add custom domain:
Outline
What I have done it so far… What are the problems? What are the solution? What I am expecting to accomplish?
To learn more about Quarto websites visit https://quarto.org/docs/websites.
The choice between using Quarto and simple R Markdown depends on the specific needs and requirements of your project. Here are a few reasons why you might consider using Quarto:
Enhanced functionality: Quarto offers additional features and functionality compared to simple R Markdown. It provides support for literate programming, version control, customizable templates, and more. If you require advanced capabilities for your project, such as generating reports with complex formatting, incorporating interactive elements, or integrating code and documentation seamlessly, Quarto can be a powerful tool.
Document generation and collaboration: Quarto is designed for collaborative document generation, making it easier for teams to work together on projects. It provides features like automated rendering, document caching, and document diffing, which can facilitate collaboration and streamline the document development process.
Extensibility: Quarto allows for extensibility through custom engines, allowing you to integrate additional programming languages or document formats into your project. This flexibility can be beneficial if you need to incorporate non-R code or work with specific document formats beyond what simple R Markdown offers.
Community and support: Quarto has an active community of users and developers who contribute to its development and provide support. If you encounter any issues or have questions, you can rely on community resources to find assistance and guidance.
However, it’s important to note that simple R Markdown is still a powerful and widely used tool for generating documents with R. If your project requirements are straightforward and don’t require the additional features provided by Quarto, using simple R Markdown may be sufficient and more straightforward. Ultimately, the choice between Quarto and simple R Markdown should be based on your specific project needs, preferences, and the complexity of the document you aim to generate.
Intent
Problem 1: Notebook keeping.
Experimental notes are distributed in many different folders and files; sometimes even in different drives and it is difficult to keep track of all information. A centralized direct access to information at any time is required.
The standard way to do it is by using Microsoft Office programs
Word:
Pros:
- Best way to manage “tables” within text editor.
- Inter-compatibility with word, excel, ppt and other programs.
- Easy to send and collaborate with others.
- The Standard for all purposes.
Cons:
- File size gets too big very fast.
- images and links slows down computer.
- Files are scatter all around different folders, hard to manage.
- No easy way to compile information across projects and experiments.
Problem 2: Software and code management.
- Code management is a serious problem, word cannot manage it at all.
Software:
- brew to install all research software.
- MS Office
- R and RStudio
- VS Code
- Quarto
- Zotero
- Anaconda
- Git
- GitHub
- Git Kraken
- ImageJ
- Calibre
- DigiKam
- Docker?
- Syncthing
- FreeCad
- Blender
Small digression: Think on the possibility of a centrilized Folder for all notes, word, r, qmd, pyton, bash, and using symlinks to move and compile projects (like a puzzle) to create new content.
Why I am changeing to quarto?
Solutions:
key Shortcuts: Files: Excel best tricks.xlsx; Markdown02.docx
Notekeeping:
1. Save all notes in one place.
/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes, then symlik to other projects.
- Does symlinks work with github, syncthing, synology, host (hostinger), etc?
- Which type of symlik is best? soft or hard?
2. Files and folders:
/Users/marcelorosales/Box Sync/Github
- DotFiles: What are dotfiles? To create executable file to install all programs ex. brew.sh and settings at once with one executable command.
- conda shells
- iTerm: Fonts
- GitBooks: What are Gitbooks?
- mkdocs
- NiigataU-Carving: html
- Quarto (VS and R)
- Rstudio: Shared files among devices
- Visual Studio Code
/Users/marcelorosales/Box Sync/Documents/R
- Course01-R Programming A-Z
- Course02- R Programing - Advanced Analitics
- R Bookdown
- R Example scripts
- R exmple df
- R external sources
- R package files
- R Preferences and packages
- Rmarkdown
- Tests forlder
- Working Directory
MBP20 files: /Users/marcelorosales/Documents/GitHub:
- Bioinformatics_RNA-seq (Gitbook)**
- Carving (HTML web page made entirely manually)
- DotFiles (Empty) x
- Example (Hugo Site trial01, empty) x
- Img (RNA analysis image samples)
- Mkdocs_books (Trial site with 1 symlink file from /Box Sync/Github/mkdocs/bs4_LabNotes/ _book/08-Preparation.md) *
- mkdocs_Tests (Trial of submenus in mkdocs) x
- MkDocsTest1 (Trial of mkdocs multilingual feature, VS_code,md, MkDocs,md) *
- Quarto:
- quarto-tip-a-day (webpage downloaded from quarto site)
- quarto-trials:
- quarto_blog
- quarto_book
- quarto_project
- quarto_website (Quarto page test01, https://marcelorosales.github.io/Quarto_website_test01/) +++
- quarto_blog
- quarto-web (Downloaded entire quarto web site)
- Research_Experiments:
- PhotoConvertibleCells (Example only, no content)
- PhotoConvertibleCells (Example only, no content)
- Research_Notebook: (Experiment Notebooks, All reseach Notes, https://marcelorosales.github.io/Research_Notebook/ )
- Retrolog (Hugo lithium) x
- Temptests (RNA Seq for STAT3 example of RNA sequencing) **
- VS Code (VS code cheat sheets) *
- ZdocTest1 (Zdoc-blogdown test) x
- zipfiles
- Hugotree.docx
- Research_Notebook.Rmd (Research Notes, Research Notebook) **
MBP15 files:
Synology files:
Github pages:
MarceloRosales/MkDocsTest1
MarceloRosales/Research_Notebook
MarceloRosales/mkd_LabNotes
MarceloRosales/Bioinformatics_RNA-seq
MarceloRosales/NiigataU-SV
MarceloRosales/Carving
MarceloRosales/MarceloRosales ¿???
MarceloRosales/PCC-Experiment
MarceloRosales/RBD02
MarceloRosales/NiigataU-Carving
MarceloRosales/RBlogdowntest01
MarceloRosales/WebDev-01
MarceloRosales/BootstrapCarrousel
MarceloRosales/staticrypt
MkDocsTest1 https://marcelorosales.github.io/MkDocsTest1/MkDocs/
Research_Notebook https://marcelorosales.github.io/Research_Notebook/
mkd_LabNotes https://marcelorosales.github.io/mkd_LabNotes/
Bioinformatics_RNA-seq https://marcelorosales.github.io/Bioinformatics_RNA-seq/
NiigataU-SV https://marcelorosales.github.io/NiigataU-SV/
Carving https://marcelorosales.github.io/Carving/
MarceloRosales ¿?? PCC-Experiment https://marcelorosales.github.io/PCC-Experiment/
RBD02 https://marcelorosales.github.io/RBD02/ A minimal book ex.
NiigataU-Carving https://marcelorosales.github.io/NiigataU-Carving/
RBlogdowntest01 (not live) WebDev-01 https://marcelorosales.github.io/WebDev-01/
BootstrapCarrousel https://marcelorosales.github.io/BootstrapCarrousel/
Staticrypt (exec only)
MarceloRosales/MkDocsTest1 > MkDocsTest1 <https://marcelorosales.github.io/MkDocsTest1/MkDocs/ >
MarceloRosales/Research_Notebook > Research_Notebook https://marcelorosales.github.io/Research_Notebook/
MarceloRosales/mkd_LabNotes > mkd_LabNotes https://marcelorosales.github.io/mkd_LabNotes/
MarceloRosales/Bioinformatics_RNA-seq > Bioinformatics_RNA-seq https://marcelorosales.github.io/Bioinformatics_RNA-seq/
MarceloRosales/NiigataU-SV > NiigataU-SV https://marcelorosales.github.io/NiigataU-SV/
MarceloRosales/Carving > Carving https://marcelorosales.github.io/Carving/
MarceloRosales/MarceloRosales ¿??? > MarceloRosales ¿?? MarceloRosales/PCC-Experiment > PCC-Experiment https://marcelorosales.github.io/PCC-Experiment/
MarceloRosales/RBD02 > RBD02 https://marcelorosales.github.io/RBD02/ A minimal book ex.
MarceloRosales/NiigataU-Carving > NiigataU-Carving https://marcelorosales.github.io/NiigataU-Carving/
MarceloRosales/RBlogdowntest01 > RBlogdowntest01 (not live) MarceloRosales/WebDev-01 > WebDev-01 https://marcelorosales.github.io/WebDev-01/
MarceloRosales/BootstrapCarrousel > BootstrapCarrousel https://marcelorosales.github.io/BootstrapCarrousel/
MarceloRosales/staticrypt > Staticrypt (exec only)
| MarceloRosales/MkDocsTest1 | > | MkDocsTest1 https://marcelorosales.github.io/MkDocsTest1/MkDocs/ |
| MarceloRosales/Research_Notebook | > | Research_Notebook https://marcelorosales.github.io/Research_Notebook/ |
| MarceloRosales/mkd_LabNotes | > | mkd_LabNotes https://marcelorosales.github.io/mkd_LabNotes/ |
| MarceloRosales/Bioinformatics_RNA-seq | > | Bioinformatics_RNA-seq https://marcelorosales.github.io/Bioinformatics_RNA-seq/ |
| MarceloRosales/NiigataU-SV | > | NiigataU-SV https://marcelorosales.github.io/NiigataU-SV/ |
| MarceloRosales/Carving | > | Carving https://marcelorosales.github.io/Carving/ |
| MarceloRosales/MarceloRosales ¿??? | > | <MarceloRosales ¿??> |
| MarceloRosales/PCC-Experiment | > | PCC-Experiment https://marcelorosales.github.io/PCC-Experiment/ |
| MarceloRosales/RBD02 | > | RBD02 <https://marcelorosales.github.io/RBD02/ A minimal book ex.> |
| MarceloRosales/NiigataU-Carving | > | NiigataU-Carving https://marcelorosales.github.io/NiigataU-Carving/ |
| MarceloRosales/RBlogdowntest01 | > | <RBlogdowntest01 (not live)> |
| MarceloRosales/WebDev-01 | > | WebDev-01 https://marcelorosales.github.io/WebDev-01/ |
| MarceloRosales/BootstrapCarrousel | > | BootstrapCarrousel https://marcelorosales.github.io/BootstrapCarrousel/ |
| MarceloRosales/staticrypt | > | <Staticrypt (exec only)> |
How to use:
Where do I write the text first? word, Rstudio .qmd, VS code?
Seems like VS code is the best transitional software for word and Rstudio.
- I am thinking I will I will use the 3 of them (word, RStudio (RS).qmd, VS code (VSC)) at the same time.
- Seems like VC code is the middle ground between word and Rstudio. 20230502 test: Use VS code as the main text/code editor, then copy paste to word.
- Create a qmd file/project in RS, git init, save project.
- Open RS qmd file or better, open the project folder in VS code and use as main text editor.
- Change/add content, save in VS code > will auto update in RS (no need to do anything except to reload/open file).
- Check if render is correct.(It is possible to render in VS directly as well)
- Copy/paste to word and save in word. Currently it is not possible to open a word file directly in VSC.
- Create a qmd file/project in RS, git init, save project.
- Use word and .qmd (in source mode only) at the same time and indistinctively…
- DO NOT SWITCH TO VISUAL MODE. Changing to visual mode will modify text in the source code format. Space between lines is doble and there is no way to change it in the ui of rstudio, only in the render output. It makes it difficult to read and orginize.
- Thus, keep all records in the word file at all times. Make de word file the default saving format.
- Open Untitled .qmd files to try and test code chunks or formats.
- Open an Image .qmd file in visual mode to store all image code and links for a fast gallery, then easy to copy/paste images to other places.
- If large code needs to be quickly formated for word (coz copy/paste from rstudio to word directly does not copy code highlight formats), use VS code, copy/paste Rstudio > VS Code > word. Then adjust line spacing.
Open Word file
(See Markdown02.docx > Word and Rstudio for detail info on the code)
files:
Mac:
#| eval: false
Markdown02 <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown02.docx"
Research_map <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Research_map and guide.docx"
Markdown01 <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown01.docx"
Notes <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/"
#open in mac OS
system(paste("open", shQuote(Markdown02)))
system(paste("open", shQuote(Research_map)))
system(paste("open", shQuote(Notes)))Windows:
#| eval: false
file_path <- "/Users/marcelorosales/Box Sync/Niigata Uni Box/Books-Notes/Notes/Markdown01.docx"
shell(paste("start", shQuote(file_path)))
# or
system(paste("start", shQuote(file_path)))Quarto extensions:
quarto add quarto-ext/lightbox
git pull
hint: You have divergent branches and need to specify how to reconcile them. hint: You can do so by running one of the following commands sometime before hint: your next pull: hint: hint: git config pull.rebase false # merge hint: git config pull.rebase true # rebase hint: git config pull.ff only # fast-forward only hint: hint: You can replace “git config” with “git config –global” to set a default hint: preference for all repositories. You can also pass –rebase, –no-rebase, hint: or –ff-only on the command line to override the configured default per hint: invocation. fatal: Need to specify how to reconcile divergent branches.
git config pull.rebase true
git pull
Auto-merging docs/blog.html CONFLICT (content): Merge conflict in docs/blog.html Auto-merging docs/posts/quarto_start.html Auto-merging docs/search.json error: could not apply f3a6a9e… error? hint: Resolve all conflicts manually, mark them as resolved with hint: “git add/rm
git checkout docs/blog.html: needs merge error: you need to resolve your current index first
git status interactive rebase in progress; onto bf0a829 Last command done (1 command done): pick f3a6a9e error? No commands remaining. You are currently rebasing branch ‘master’ on ‘bf0a829’. (fix conflicts and then run “git rebase –continue”) (use “git rebase –skip” to skip this patch) (use “git rebase –abort” to check out the original branch)
Changes to be committed: (use “git restore –staged
Unmerged paths: (use “git restore –staged
Changes not staged for commit: (use “git add
~/Doc/G/Q/quarto-tr/quarto_website @bf0a8290 rebase-i 1/1 ~1 +4 !1
git add
commit bf0a82908adb25739312fc1472774f1c884f54c0 (HEAD, origin/master) Author: MarceloRosales selasorolecram@hotmail.com Date: Fri Mar 31 12:18:08 2023 +0900
misc update
commit 2f93766898fab40f2b516968cb4db51608d3cead Author: “MarceloRosales” <“selasorolecram@hotmail.com”> Date: Thu Mar 30 20:34:08 2023 +0900
fatal: It seems that there is already a rebase-merge directory, and I wonder if you are in the middle of another rebase. If that is the case, please try git rebase (–continue | –abort | –skip) If that is not the case, please rm -fr “.git/rebase-merge” and run me again. I am stopping in case you still have something valuable there.
https://www.gakkai-tama.com/register_form/jps132/menu
Code Notation
---
format:
html:
code-fold: true
code-copy: true
code-overflow: wrap
------
title: Simple Lightbox Example
filters:
- lightbox
lightbox: auto
---
{group="my-gallery"}
{group="my-gallery"}
{group="my-gallery"}plot(mtcars)
plot(cars)Videos in Q
In visual editor: Insert Anything You can also use the catch-all Cmd+//Ctrl+/ shortcut to insert just about anything. Just execute the shortcut then type what you want to insert.
Or simply: /
For iframe video, select the html Block, it will make a {=html} block that will display the video when quarto page is render. see https://docs.posit.co/ide/user/ide/guide/documents/visual-editor.html
Code for videos:
# In quarto for videosee https://quarto.org/docs/authoring/videos.html#video-url
or to insert web pages.
<iframe width="780" height="500" src="https://quarto.org/" title="Quarto Documentation"></iframe>top
## Videos
5 — Markdown Images — Mastering Markdown
5 simple tips to making responsive layouts the easy way
How To Create Image Gallery Using HTML, CSS and Javascript | Lightbox Gallery
Lightbox Gallery
Plan 220826
- Create all the files in .Rmd as normal (in Box sync service) as bs4_book
Use Rstudio::New Project.
mkdocs new LabNotes….
- Build site in bs4 -> Converts .Rmd to .m -> Creates a folder with all converted .md files (all files in Box Sync, do NOT connect with git or GitHub)
- Create Mkdocs repositories in /documents/GitHub/
- Confect them to a GitHub repo
- Use symlinks for the .md files stored in doc/github/ folders
- Make GitHub commits as normal
- Build and deploy site as normal. So far OK.
Plan 220901
All the data together is big, too big for cloud or laptop. Perhaps better place it all in Synology and then symlinks of only the .Rmd to clouds. Modifying a symlink What if sinology gets disconnected? Since it is also connected to github. Data will still be available anywhere. Create and
Problem: Even by dividing the section in individual Rmd files to make building and rendering book more manageable, and place them in sinology cloud with symlinks and connected with github, updates and changes made with other connected devices will be not possible. Symlink will point to the file with path to file to a specific folder (in sinology), but in other devices, the symlink path will not work. The file needs to be physically or remotely connected with the device, in this case, perhaps will be better:
[ ] Place all the Rmd files in cloud service (Box)
[ ] Create the symlinks from Box to Local folder (Git/Githb) for each device in use.
[ ] Connect each local book to same repository in gihub. ]; building of the book will not be possible form
Important folders:
MBP20
Box > Github > Mkdocs > mkdocs_dumpAll (all the Rmd and md? From all experiment, notes): make the symlinks from here to the other folders.
Samples: Contains all the book samples except mkdocs materialize.
Bs4_book creates md files to create the html (useful for converting into mkdocs materialize)
Temp: Contains all the Rmd files form the LabNotesAll_bs4, continuation of the folder with the same name (2nd trial)
MBA03 (mkdocs build locally for All.md only, no html files)
LabNotesAll_bs4 (currently working in this project as trial, contains: Initialization, Terminal, VSCode, Markdown. All are first trial)
bs4_LabNotes
Gitbooks:
Niigata Uni Box > Book-Notes >
Notes: All notes are here.
Documents > GitHub >
Research_Notebook: Made in bookdown, is the old research notes (do not mistake with other samples. Keep for the moment)‼
~/Box Sync/Github/mkdocs/mkdocs_dumpAll/Samples/Book samples/SimpleArticle_samp
/Volumes/homes/RosalesJM/SynDS220/GitHub/Experiments_Lab/LabNotesAll/AllNotes_SimpArt
~/Box Sync/Github/mkdocs/LabNotesAll_bs4
~/Box Sync/Github/mkdocs/mkdocs_dumpAll/Markdown02.Rmd
Special entries to review later
Markdown all in one. For toc, see how to modify table here.
Handbook Markdown Guide. Seems like only works for gitlab….
Rmarkdown into Word - change a title in toc
In the yaml set:
How to Create A Batch Cask Installer for Homebrew (Using a Simple Bash Script). https://youtu.be/1J9NKpjJegk
Create the brewfile with dump command.
Customize Prompt with dotfiles.
Make a MkDocs Site. Made Site, very good documentation but is an md non RStudio package, so I change to quarto for better productivity
create a Hugo Theme form scratch
Costumize iTerm2. (Powerlevel10k theme installed succesfully )
Zotero plugin not downloading form chrome (refreshed page and worked normal).
Outlines: Tips for Preparing Large Writing Projects (play list): https://youtu.be/osxUFsnY6zg
Academic Writing in Markdown: bib, Bib(La)Tex, Pandocs, Marked 2 AppleScripts: Zotpick (playlist) https://www.youtube.com/watch?v=hpAJMSS8pvs&list=PLXt-tu7G1H3tLeZgbbUmYjE0_kvbjA4YU
R tip: Schedule R scripts on a Mac review this again, good for run exc files on schedule.
R Markdown Advanced Tips to Become a Better Data Scientist & RStudio Connect | With Tom Mock Good, review, specially the part of shiny applications.
Rmarkdown directing output file into a directory
Uni biopro2 webpage
Setting up a brand new Hugo Site
Building a Hugo Theme from Scratch
Building a Hugo Theme from Scratch PART 2
Virtual machines.
VirtualBox: How to Use Snapshots
How to Record and Play Back Mouse Activity in macOS automator
.
https://www.w3schools.com/html/html_comments.asp
Git & GitHub Crash Course For Beginners. Vid
.
Getting Started - Installing Git
How to set a Directory as an Argument in Bash
R Programming Tutorial - 3 - How to Run a Simple Program.
Iterm2 customization macOS set up for coding and development (2022 edition) Install and customise Powerlevel10k theme for ZSH
iTerm2 - Accessibility and Full Disk Access
If you want to access special directories/files such as ~/Library/Application Support/AddressBookor ~/Pictures/Photos Library.photoslibrary, yes you need to give Full Disk Access to iTerm2. If don’t, you can not access those directories. For more information, here is the iTerm2 wiki https://gitlab.com/gnachman/iterm2/wikis/fulldiskaccess. Preferences > Security & Privacy > Privacy > Unlock to make changes > Full disk access > + > Applications > iTerm2 > Open > Quit >
All books on bookdown.org
Scientific Research and Methodology:
Translational Bioinformatics with R
Omic Sciences
Network Estimation in Spatial Transcriptomics
Machine Learning for Biostatistics
bookdown: Authoring Books and Technical Documents with R Markdown
Machine Learning: Teoría y Práctica
R Markdown Cookbook
foot
!/bin/bash Change format, and change max size. 20181231 DM
oldFormat=HEIC newFormat=png newSize=800
for i in *.$oldFormat do sips –setProperty format $newFormat –resampleHeightWidthMax \(newSize "\)i” –out “\({i%\)oldFormat}”$newFormat done exit 0
Scientific Research and Methodology: Translational Bioinformatics with R Omic Sciences Network Estimation in Spatial Transcriptomics Machine Learning for Biostatistics bookdown: Authoring Books and Technical Documents with R Markdown Machine Learning: Teoría y Práctica R Markdown Cookbook
Footnotes
It’s highly recommended to put the Markdown file containing the abbreviations outside of the
docsfolder (here, a folder with the nameincludesis used), as MkDocs might otherwise complain about an unreferenced file. In vs preview, this glossary snippet will be displayed (auto-append) at the end of the page, will it be displayed in mkdocs page?.↩︎








Comments
Markdown-comments
{% comment %}
These commments will not include inside the source. {% endcomment %}
whatever: : comment
whatever: whatever comment
But this mesage will appear!
{::comment} This text is completely ignored by kramdown - a comment in the text. {:/comment}
Do you see {::comment}this text{:/comment}? {::comment}some other comment{:/}
!!! check “This works best”