Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
MistEO authored Feb 9, 2024
0 parents commit abfb28e
Show file tree
Hide file tree
Showing 7 changed files with 394 additions and 0 deletions.
141 changes: 141 additions & 0 deletions .github/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@

# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
pytestdebug.log

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/
doc/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# End of https://www.toptal.com/developers/gitignore/api/python
41 changes: 41 additions & 0 deletions .github/rank.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from scoring import file_score, best_file_score
from pathlib import Path

if __name__ == '__main__':

score_list = []

for player in Path('.').glob('*'):
if player.is_file():
continue
if player.stem.startswith('.'):
continue

result = best_file_score([x for x in player.glob('**/*') if x.is_file()])
if result:
path, score = result
score_list.append((player.stem, path, score))

score_list.sort(key=lambda x: x[2][2])
ranking = "| Rank | Player | File | Length | Category | Score |\n"
ranking += "| ---- | ------ | ---- | ------ | -------- | ----- |\n"
for i, (player, path, score) in enumerate(score_list):
ranking += f"| {i+1} | [{player}]({player}) | [{path.name}]({path}) | {score[0]} | {score[1]} | {score[2]} |\n"

print(ranking)

with open('README.md', 'r', encoding='utf-8') as f:
content = f.read()

BEGIN_FLAG = '<!-- begin of RANKING -->'
END_FLAG = '<!-- end of RANKING -->'
begin = content.find(BEGIN_FLAG)
end = content.find(END_FLAG)
if begin == -1 or end == -1:
print('Error: README.md is not valid.')
exit()

content = content[:begin] + BEGIN_FLAG + '\n' + ranking + content[end:]

with open('README.md', 'w', encoding='utf-8') as f:
f.write(content)
72 changes: 72 additions & 0 deletions .github/scoring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import sys
import typing
import pathlib


def file_score(path: pathlib.Path) -> typing.Optional[typing.Tuple[int, int, int]]:
"""Return the score of a file based on its length and number of used characters."""

try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
except UnicodeDecodeError:
print(f'File: {path} is not UTF-8.')
return None
except Exception as e:
print(f'File: {path} cannot be read. Error: {e}')
return None

# if not content.isascii():
# print(f'File: {path} is not ASCII.')
# return None

# for char in 'HELLOWORLDhelloworld':
# if char in content:
# print(f'File: {path} contains {char}.')
# return None

# Score based on length
score_len = len(content)

# Score based on number of used characters
score_cate = len(set(content))

return score_len, score_cate, score_len * score_cate


def best_file_score(path_list: typing.List[pathlib.Path]) -> typing.Optional[typing.Tuple[int, int, int]]:
"""Return the best score of a list of files."""

str_list = [str(p) for p in path_list]
print(f'Scoring files: {str_list}\n')

min_scores = (0, 0, 0)
min_path = pathlib.Path()
for path in path_list:
if not path.exists():
print(f'File: {path} does not exist.')
continue
scores = file_score(path)
if not scores:
continue
print(f'File: {path}, Length: {scores[0]}, Category: {scores[1]}, Score: {scores[2]}')
if scores[2] < min_scores[2] or min_scores[2] == 0:
min_scores = scores
min_path = path

if min_scores[2] == 0:
print(f'\nNo valid file in {str_list}.\n\n')
return None
else:
print(f'\nBest file: {min_path}, Length: {min_scores[0]}, Category: {min_scores[1]}, Score: {min_scores[2]}\n\n')
return min_path, min_scores


if __name__ == '__main__':

if len(sys.argv) < 2:
print('Usage: python scoring.py <files>')
exit()

paths = [pathlib.Path(arg) for arg in sys.argv[1:]]
best_file_score(paths)
21 changes: 21 additions & 0 deletions .github/workflows/auto_rank.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Auto Rank

on:
push:
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Auto Rank
run: |
python3 .github/rank.py
- uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
message: "chore: Auto Rank"
branch: ${{ github.ref }}
74 changes: 74 additions & 0 deletions .github/workflows/auto_reply.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
name: Cyber Referee

on:
pull_request_target:

jobs:
auto_reply:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:

- name: Self-introduction
uses: thollander/actions-comment-pull-request@v2
with:
message: "啾啾啾!裁判来咯!"
comment_tag: "Self-introduction"
reactions: laugh

- name: Check out code
uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0

- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@v37

- name: Scoring
id: scoring
run: |
echo Changes: ${{ steps.changed-files.outputs.all_changed_files }}
comment=$(python .github/scoring.py ${{ steps.changed-files.outputs.all_changed_files }})
echo "$comment"
echo "$comment" > comment.txt
if [[ $comment == *"No valid file"* ]]; then
echo valid=False | tee -a $GITHUB_OUTPUT
else
echo valid=True | tee -a $GITHUB_OUTPUT
fi
- name: Post Score
uses: thollander/actions-comment-pull-request@v2
with:
filePath: comment.txt
reactions: rocket


- name: Post Invalid
if: steps.scoring.outputs.valid != 'True'
uses: thollander/actions-comment-pull-request@v2
with:
message: "你这瓜保熟吗?"
reactions: eyes


- name: Post Valid
if: steps.scoring.outputs.valid == 'True'
uses: thollander/actions-comment-pull-request@v2
with:
message: "你的代码写的也忒好咧!"
reactions: hooray


# - name: Auto Merge
# if: steps.scoring.outputs.valid == 'True'
# uses: pascalgn/[email protected]
# env:
# MERGE_LABELS: ""
# GITHUB_TOKEN: ${{ secrets.MISTEOPAT }}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 InvoluteHell

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading

0 comments on commit abfb28e

Please sign in to comment.