code summary
matplotlib
Image Size
Create a figure with the specified size:
plt.figure(figsize=(w,h))
Default size:
plt.figure(figsize=(6.4,4.8))
Adjust default plot size:
import matplotlib plt.rcParams['figure.figsize'] = [width, height]
tmux
tmux attach -t 0
: Attach to session 0- Ctrl + b + Arrow Keys: Switch to the session in the specified direction
- Ctrl + b + Number: Switch to the session with the specified number
- Ctrl + b + d: Return to shell while keeping the session alive
- Ctrl + c + Ctrl + c: Close emacs
Python
Execution Path os.getcwd()
main.__file__
: Get the path including the filename and extension.os.path.dirname(os.path.realpath(__file__))
: Get the path of the folder containing the file. Use this to ensure functionality when executing Python files from the terminal.os.getcwd()
: Get the current working directory. Works as intended when executing*.py
files from the explorer, but returns the terminal path when run from the terminal.
>>> import os
>>> import __main__ as main
>>> x = main.__file__
>>> print(x, "\n")
C:/Users/admin/Desktop/Python/test.py
>>> y = os.path.dirname(os.path.realpath(__file__))
>>> print(y, "\n")
C:/Users/admin/Desktop/Python
>>> z = os.getcwd()
>>> print(z)
C:/Users/admin/Desktop/Python
Check if Path Exists os.path.exists(directory)
os.path.exists(directory)
: Returns True or False based on whether the path exists.
Create Folder os.makedirs(directory)
os.makedirs(directory)
: Creates a folder if the entered path does not exist.def create_directory(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print("Error: Failed to create the directory.")
Delete Folder
Code to delete empty folders while traversing subfolders.
import os
directory = os.path.dirname(os.path.realpath(__file__))
for (path, dir, files) in os.walk(directory):
try:
os.removedirs(str(path))
except:
print("디렉토리가 비어있지 않습니다.")
Find Specific Files in Subdirectories of the Running File
Code to find all Python files in the folder where the execution file is located, including its subdirectories.
The folder containing the execution file is also included in the search range, so the execution file itself is included in the file_list
.
directory = os.getcwd()
file_list = []
for (path, dir, files) in os.walk(directory):
for filename in files:
ext = os.path.splitext(filename)[-1]
if ext == '.py':
file_list.append("%s\\%s" % (path, filename))
Execution Variables sys.argv
Receiving the part after python using sys.argv = foo.split()
.
# 파일 실행
import os
os.system("python " + "file_directory/foo.py " + argv1 + " " + argv2)
## foo.py 내부 코드
import sys
# sys.argv[0]는 "file_directory/foo.py "임
variable1 = sys.argv[1]
variable2 = sys.argv[2]
File Reading and Writing
Reading and writing should be done separately. Adding “t” indicates text mode, “b” indicates binary mode.
- “rt” is read-text mode, read-only, throws an error if file does not exist
- “w” is write mode, creates a new file regardless of whether it exists
- “a” is append mode, creates a new file if it does not exist, otherwise appends to the end of the existing file
- “x” is create mode, throws an error if the file already exists
# 텍스트 파일 열고 내용 가져오기, 그리고 닫기
foo_read = open(file_directory + "foo.txt", "rt", encoding="utf-8")
lines = foo_read.readlines()
foo_read.close()
readlines()
reads each line of a txt file as an element (string) in a list. If there is a newline character, '\n'
is also included at the end. The .strip()
method can be used to remove the trailing '\n'
.
foo_write = open(file_directory + "foo.txt", "wt", encoding="utf-8")
foo_write.write("bar\n") # 한 줄 쓰기
lines = ["bar1\n", "bar2\n", "bar3\n"]
foo_write.lines(lines) # 여러 줄 쓰기
foo_write.close()
Strings
strip()
: Removes characters from both ends of a string. Without a variable, it removes whitespaces (including newlines). Useful for removing spaces at the start and end of a string.sort()
: Sorts strings in alphabetical order. For reverse order, usereverse=True
.replace()
: Replaces a substring within a string.translate()
: Replaces characters within a string.Difference between replace and translate1
replace(‘old_string’, ’new_string’) replaces the old substring with a new one within the string (the string itself is not changed, the result is returned). For example, replace ‘world’ with ‘Python’ in ‘Hello, world!’ and returns the result. while replace changes a substring, translate can be used to change individual characters. translate changes characters within a string. First, create a conversion table with str.maketrans(‘old_char’, ’new_char’), then use translate(table) to replace characters and return the result. For example, replace ‘a’ with 1, ’e’ with 2, ‘i’ with 3, ‘o’ with 4, and ‘u’ with 5 in the string ‘apple’.
>>> table = str.maketrans('aeiou', '12345') >>> 'apple'.translate(table) '1ppl2'
split()
: Splits a string into a list based on the input variable.>>> x.split(',') ['1', '3', '4']
Well-organized site
Lists
.sorted()
: Sorts strings in alphabetical order. For reverse order, usereverse=True
.Save and load lists
import pickle
list = [1, 2, 3, 4]
# 리스트 저장
with open("list.pkl", "wb") as f:
pickle.dump(list, f)
# 리스트 불러오기
with open("list.pkl", "rb") as f:
list = pickle.load(f)
Julia
$\LaTeX$
Font Size
$\Huge AB$ \Huge AB
$\huge AB$ \huge AB
$\LARGE AB$ \LARGE AB
$\Large AB$ \Large AB
$\large AB$ \large AB
$\normalsize AB$ \normalsize AB
$\small AB$ \small AB
$\footnotesize AB$ \footnotesize AB
$\scriptsize AB$ \scriptsize AB
$\tiny AB$ \tiny AB
PyTorch and TensorFlow
GPU
Check GPU
- P: torch.cuda.is_available()
Arrays
Constants
- P: torch.tensor([1,2,3])
- TF: tf.constant([1,2,3])
Parameters
- P: torch.tensor([1,2,3], requires_grad=True)
- TF: tf.variable([1,2,3])
Models
Class
- P: class model(nn.Module)
- TF: class model(tf.keras.Model)
TF: model.complie()
TF: model.fit(data, label, epochs, batch_size, verbose)
verbose
: Integer. 0, 1, or 2. (Training output mode)- 0 = silent,
- 1 = progress bar,
- 2 = one line per epoch.
TF: model.complie()
VS Code
MarkdownAllinOne
Function for automatic Markdown table formatting: Shift + Alt + F
- Prevent expanding folders when opening files: Explorer: Auto Reveal
Enable Auto Word Wrap
Automatic code word wrap: Editor: Word Wrap
- Ctrl + Shift + P $\to$ Enable word wrap by searching word wrap
- Toggle key: Alt + z
Automatically wrap tab strip: Editor: Wrap Tabs
Set Keyboard Shortcuts: keybindings.json
Path: C:/Users/user/AppData/Roaming/Code/User/keybindings.json
Automatically add parentheses in superscript within Markdown:
{ "key": "shift+6", "command": "editor.action.insertSnippet", "when": "editorTextFocus && editorLangId == 'markdown'", "args": { "snippet": "^{$0\\}" } }
- To apply it to .tex files, use
editorLangId == 'latex'
- To apply it to .tex files, use