Skip to content

Instantly share code, notes, and snippets.

@duoduoffff
Last active February 12, 2025 02:47
Show Gist options
  • Save duoduoffff/b877104ddb086dd14d5a6a2e19fa6de2 to your computer and use it in GitHub Desktop.
Save duoduoffff/b877104ddb086dd14d5a6a2e19fa6de2 to your computer and use it in GitHub Desktop.
My useful setup tools installing Fedora
///usr/share/fontconfig/conf.avail/64-language-selector-prefer.conf
//very important to rectify Chinese fonts display
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<alias>
<family>sans-serif</family>
<prefer>
<family>Noto Sans CJK SC</family>
<family>Noto Sans CJK TC</family>
<family>Noto Sans CJK HK</family>
<family>Noto Sans CJK JP</family>
<family>Noto Sans CJK KR</family>
</prefer>
</alias>
<alias>
<family>serif</family>
<prefer>
<family>Noto Serif CJK SC</family>
<family>Noto Serif CJK TC</family>
<family>Noto Serif CJK HK</family>
<family>Noto Serif CJK JP</family>
<family>Noto Serif CJK KR</family>
</prefer>
</alias>
<alias>
<family>monospace</family>
<prefer>
<family>Noto Sans Mono CJK SC</family>
<family>Noto Sans Mono CJK TC</family>
<family>Noto Sans Mono CJK HK</family>
<family>Noto Sans Mono CJK JP</family>
<family>Noto Sans Mono CJK KR</family>
</prefer>
</alias>
</fontconfig>
#!/usr/bin/bash
/usr/local/bin/clash -f ~/.config/clash/config.yaml
#! /usr/bin/bash
SERVER="10.233.56.25"
ping -c 3 $SERVER
if [[ $? -eq 0 ]]; then
CREDENTIAL=/Users/notrachel/.smbCredentials.txt
stat $CREDENTIAL
if [[ $? -eq 0 ]]; then
sudo mount -t cifs -o credentials=~/.smbCredentials.txt //$SERVER/irminsulSea/ /media/irminsulSea/
else
echo "Credential does not exist!"
exit 1
fi
else
echo "Server offline!"
exit 2
fi
# ~/.config/systemd/user/auto-theme.service
[Unit]
Description=Automatically change desktop theme
After=graphical-session.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=no
RestartSec=1
ExecStart=/Users/notrachel/Scripts/auto-theme.sh
Environment=WAYLAND_DISPLAY=wayland-0
[Install]
WantedBy=default.target
#!/bin/bash
# Have to manually compile sunwait from scratch. https://github.com/risacher/sunwait/
LIGHT_THEME="org.kde.breeze.desktop"
DARK_THEME="org.kde.breezedark.desktop"
LATITUDE="30.7649N"
LONGITUDE="102.1193E"
function detectDayOrNight() {
DN=$(sunwait poll exit civil $LATITUDE $LONGITUDE)
echo $DN
if [[ $DN == "DAY" ]]; then
lookandfeeltool -a $LIGHT_THEME
sunwait wait sun set $LATITUDE $LONGITUDE
elif [[ $DN == "NIGHT" ]]; then
lookandfeeltool -a $DARK_THEME
sunwait wait sun rise $LATITUDE $LONGITUDE
else
echo "Validation falied!!"
exit 2
fi
}
while true; do
detectDayOrNight
done
#!/usr/bin/env python3
import os
import argparse
import hashlib
def parse_arguments():
parser = argparse.ArgumentParser(description="批量生成目录下文件的 SHA256 校验值,并写入一个文本文件中。")
parser.add_argument('-d', '--directory', type=str, default='.',
help='指定校验值文件所在的目录。默认为当前工作目录。')
parser.add_argument('-t', '--extension', type=str, default=None,
help='指定要生成校验值的文件扩展名(例如:txt)。默认为所有非隐藏文件。')
parser.add_argument('-f', '--filename', type=str, default='checksum.txt',
help='指定校验值文件的名字。默认为 checksum.txt。')
return parser.parse_args()
def is_hidden(filepath):
return any(part.startswith('.') for part in filepath.split(os.sep))
def compute_sha256(filepath):
sha256_hash = hashlib.sha256()
try:
with open(filepath, 'rb') as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
except Exception as e:
print(f"无法读取文件 {filepath}: {e}")
return None
def main():
args = parse_arguments()
target_directory = os.path.abspath(args.directory)
if not os.path.isdir(target_directory):
print(f"指定的目录不存在: {target_directory}")
return
checksum_filename = args.filename
checksum_filepath = os.path.join(target_directory, checksum_filename)
extension_filter = args.extension
if extension_filter:
if not extension_filter.startswith('.'):
extension_filter = '.' + extension_filter
files_to_process = []
for root, dirs, files in os.walk(target_directory):
for file in files:
if is_hidden(file):
continue # 跳过隐藏文件
if extension_filter:
if not file.lower().endswith(extension_filter.lower()):
continue # 跳过不符合扩展名的文件
full_path = os.path.join(root, file)
relative_path = os.path.relpath(full_path, target_directory)
files_to_process.append(relative_path)
if not files_to_process:
print("没有找到符合条件的文件来生成校验值。")
return
with open(checksum_filepath, 'w', encoding='utf-8') as checksum_file:
for file in files_to_process:
full_path = os.path.join(target_directory, file)
sha256 = compute_sha256(full_path)
if sha256:
checksum_file.write(f"{sha256} {file}\n")
print(f"已处理: {file}")
print(f"校验值已写入: {checksum_filepath}")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
import argparse
import sys
def parse_checksum_file(file_path):
"""
解析校验和文件,返回一个字典映射文件名到校验值。
"""
checksums = {}
try:
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
parts = line.strip().split()
if len(parts) < 2:
continue # 跳过格式不正确的行
checksum, filename = parts[0], ' '.join(parts[1:])
checksums[filename] = checksum
except Exception as e:
print(f"无法读取文件 {file_path}: {e}")
sys.exit(1)
return checksums
def compare_checksums(file1, file2):
"""
比较两个校验和字典,并返回差异。
"""
checksums1 = parse_checksum_file(file1)
checksums2 = parse_checksum_file(file2)
files1 = set(checksums1.keys())
files2 = set(checksums2.keys())
only_in_1 = files1 - files2
only_in_2 = files2 - files1
in_both = files1 & files2
different = []
for file in in_both:
if checksums1[file] != checksums2[file]:
different.append(file)
return only_in_1, only_in_2, different
def main():
parser = argparse.ArgumentParser(description="比较两个校验和文件,找出不同的文件。")
parser.add_argument('checksum1', type=str, help='第一个校验和文件路径')
parser.add_argument('checksum2', type=str, help='第二个校验和文件路径')
args = parser.parse_args()
only_in_1, only_in_2, different = compare_checksums(args.checksum1, args.checksum2)
if only_in_1:
print(f"\n只存在于 {args.checksum1} 中的文件 ({len(only_in_1)} 个):")
for file in sorted(only_in_1):
print(f" {file}")
if only_in_2:
print(f"\n只存在于 {args.checksum2} 中的文件 ({len(only_in_2)} 个):")
for file in sorted(only_in_2):
print(f" {file}")
if different:
print(f"\n在两个文件中都存在但校验和不同的文件 ({len(different)} 个):")
for file in sorted(different):
print(f" {file}")
else:
print("\n所有在两个校验和文件中存在的文件的校验和值都一致。")
if __name__ == "__main__":
main()
import subprocess
import sys
import os
import codecs
# 获取输入输出参数
input_file = sys.argv[1]
input_path = sys.argv[1]
input_filename = os.path.basename(input_path)
if len(sys.argv) > 2:
if sys.argv[2].startswith('-o'):
output = sys.argv[2][2:]
else:
output = ''
else:
output = ''
# 调用uchardet检测编码
result = subprocess.run(['uchardet', input_file],
stdout=subprocess.PIPE).stdout.decode().strip().lower()
# 定义输出文件
if output:
output_file = output
else:
filename = os.path.join(os.path.dirname(input_file), input_filename)
output_file = filename + '.utf8.txt'
print(f'Detected encoding: {result}')
with codecs.open(input_file, encoding=result) as f:
content = f.read()
with codecs.open(output_file, 'w', encoding='utf-8') as f:
f.write(content)
print('Conversion completed!')
#!/usr/local/bin/python3
import argparse
import re
import sys
import unicodedata
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--length-per-line", type=int, default=68, help="length of each line")
parser.add_argument("-i", "--input-file", help="input file path")
parser.add_argument("-r", "--input-raw", help="raw input string")
parser.add_argument("-o", "--output", help="output file path")
parser.add_argument("-", "--stdin", action="store_true", help="use stdin as input")
args = parser.parse_args()
line_length = args.length_per_line
def get_width(char):
char_type = unicodedata.category(char)
if(char_type in ["Lo", "Po"]):
return 2
else:
return 1
def get_cat(char):
return unicodedata.category(char)
def manage_lines(lines):
for i in range(len(lines)-1):
current = lines[i][-1]
next = lines[i+1][0]
# print("current", current, i)
# print(get_cat(current))
if(get_width(current) == 1):
#print("hello")
current_word = lines[i].split(" ")[-1]
next_word = lines[i+1].split(" ")[0]
correct_word = "".join([current_word, next_word])
if(len(current_word) >0 and len(next_word) >0 ):
current_prefix = lines[i].removesuffix(current_word)
print(current_prefix)
next_suffix = lines[i+1].removeprefix(next_word)
print(unicodedata.category(current_prefix[-1]))
if get_width(current_prefix[-1]) == 1 and get_width(next_suffix[0]) == 1:
lines[i] = current_prefix
lines[i+1] = "".join([correct_word, next_suffix])
return lines
def split_text(text):
lines = []
current_line = ""
current_line_len = 0
for char in text:
char_width = get_width(char)
#print(char_width)
if current_line_len + char_width <= line_length:
current_line += char
current_line_len += char_width
else:
lines.append(current_line.rstrip())
current_line = char
current_line_len = char_width
lines.append(current_line.rstrip())
lines = manage_lines(lines)
return '\n'.join(lines)
def remove_emoji(text):
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
return emoji_pattern.sub('',text)
if __name__ == '__main__':
if args.stdin:
text = sys.stdin.read()
output = split_text(remove_emoji(text))
print(output)
elif args.input_file:
with open(args.input_file) as f:
text = f.read()
output = split_text(remove_emoji(text))
if args.output:
with open(args.output, 'w') as f:
f.write(output)
else:
filename = args.input_file.replace('.','_')
filename = "{0}.txt".format(filename)
with open(filename, 'w') as f:
f.write(output)
elif args.input_raw:
text = args.input_raw
output = split_text(remove_emoji(text))
print(output)
else:
parser.print_help()
import math
# IP地址到整数转换
def ipToInt(ip):
ip = ip.split('.')
res = 0
mul = 24
for i in ip:
res += int(i) * (2 ** mul)
mul -= 8
return res
# 整数到IP地址转换
def intToIp(num):
ip = ''
for i in range(4):
ip += str(num // (2 ** (24-8*i))) + '.'
num %= 2 ** (24-8*i)
return ip[:-1]
# 计算IP范围二进制长度差距
def ipRangeDiff(start, end):
startNum = ipToInt(start)
endNum = ipToInt(end)
return math.ceil(math.log2(endNum-startNum))
# 根据差距计算子网掩码
def getSubnetMask(start, end):
diff = ipRangeDiff(start, end)
maskLen = 32 - int(math.log2(2**diff))
maskNum = (2**maskLen - 1) << (32 - maskLen)
return intToIp(maskNum)
def getSubnetMask(start, end):
diff = ipRangeDiff(start, end)
maskLen = 32 - int(math.log2(2**diff))
maskNum = (2**maskLen - 1) << (32 - maskLen)
mask = intToIp(maskNum)
return mask, f'/{maskLen}'
def get_input():
start = input("请输入起始IP地址:")
end = input("请输入结束IP地址:")
return start, end
if __name__ == '__main__':
while True:
start, end = get_input()
mask, prefix = getSubnetMask(start, end)
print(f"您输入的IP范围是:{start} - {end}")
print(f"对应的子网掩码是:{mask}")
print(f"子网前缀是:{prefix}")
print("是否继续计算子网掩码?(y/n)")
if input() != 'y':
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment