import re
# トークナイザー
def tokenize(code):
token_specification = [
('NUMBER', r'\d+'), # 整数
('ID', r'[A-Za-z_]\w*'), # 識別子
('ASSIGN', r'='), # 代入演算子
('END', r';'), # 文の終わり
('OP', r'[+\-*/]'), # 演算子
('NEWLINE', r'\n'), # 改行
('SKIP', r'[ \t]'), # 空白とタブ
('MISMATCH', r'.'), # 一致しない文字
]
tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
get_token = re.compile(tok_regex).finditer
tokens = []
for mo in get_token(code):
kind = mo.lastgroup
value = mo.group()
if kind == 'NUMBER':
value = int(value)
elif kind == 'ID' and value in {'if', 'while', 'def'}:
kind = value.upper()
elif kind == 'SKIP':
continue
elif kind == 'NEWLINE':
value = '\n'
elif kind == 'MISMATCH':
raise RuntimeError(f'{value} unexpected on line {code}')
tokens.append((kind, value))
return tokens
# パーサークラス
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.pos = 0
def parse(self):
statements = []
while self.pos < len(self.tokens):
statement = self.statement()
if statement:
statements.append(statement)
return statements
def statement(self):
if self.pos >= len(self.tokens):
return None
token = self.tokens[self.pos]
if token[0] == 'ID' and self.pos + 1 < len(self.tokens) and self.tokens[self.pos + 1][0] == 'ASSIGN':
return self.assignment()
elif token[0] in {'ID', 'NUMBER'} or (token[0] == 'OP' and token[1] == '-'):
return self.expression()
else:
raise SyntaxError(f'Unexpected token: {token}')
def assignment(self):
id_token = self.tokens[self.pos]
self.pos += 1 # skip ID
self.pos += 1 # skip ASSIGN
expr = self.expression()
self.expect('END')
return ('assign', id_token[1], expr)
def expression(self):
term = self.term()
while self.pos < len(self.tokens) and self.tokens[self.pos][0] == 'OP':
op = self.tokens[self.pos]
self.pos += 1
term = (op[1], term, self.term())
return term
def term(self):
token = self.tokens[self.pos]
if token[0] == 'NUMBER':
self.pos += 1
return token[1]
elif token[0] == 'ID':
self.pos += 1
return ('var', token[1])
else:
raise SyntaxError(f'Unexpected token: {token}')
def expect(self, kind):
if self.pos < len(self.tokens) and self.tokens[self.pos][0] == kind:
self.pos += 1
else:
raise SyntaxError(f'Expected {kind}')
# インタプリタクラス
class Interpreter:
def __init__(self):
self.variables = {}
def evaluate(self, node):
if isinstance(node, int):
return node
elif isinstance(node, tuple):
if node[0] == 'assign':
self.variables[node[1]] = self.evaluate(node[2])
return self.variables[node[1]]
elif node[0] == 'var':
if node[1] in self.variables:
return self.variables[node[1]]
else:
raise NameError(f"Variable '{node[1]}' is not defined")
else:
left = self.evaluate(node[1])
right = self.evaluate(node[2])
if node[0] == '+':
return left + right
elif node[0] == '-':
return left - right
elif node[0] == '*':
return left * right
elif node[0] == '/':
return left / right
return None
# REPL (Read-Eval-Print Loop)
def repl():
interpreter = Interpreter()
while True:
try:
code = input('>>> ')
if code == 'exit':
break
tokens = tokenize(code)
parser = Parser(tokens)
tree = parser.parse()
for statement in tree:
result = interpreter.evaluate(statement)
if result is not None:
print(result)
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
repl()
タグ: programming
CSS ローディングアイコン
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Animation</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="loading"></div>
</body>
</html>
style.css
@charset "utf-8";
.loading{
width: 32px;
height: 32px;
border-top: 8px solid red;
border-right: 8px solid blue;
border-bottom: 8px solid green;
border-left: 8px solid yellow;
border-radius: 50%;
animation: spin 800ms infinite linear;
/*animation-timing-function: linear;*/
}
@keyframes spin {
100%{
transform: rotate(360deg);
}
}
python WEBブラウザ
import sys
import os
import json
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, QWidget, QTabWidget, QAction, QMenuBar, QMenu, QListWidget, QInputDialog, QMessageBox, QFileDialog, QToolBar)
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEngineDownloadItem
from PyQt5.QtCore import QUrl, QTimer, Qt
class Browser(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Advanced Browser')
self.setGeometry(100, 100, 1200, 800)
self.bookmarks = []
self.history = []
self.home_page = 'http://www.google.com'
self.auto_browse_url = ''
self.auto_browse_interval = 60
self.timer = QTimer(self)
self.timer.timeout.connect(self.auto_browse)
self.load_settings()
self.tab_widget = QTabWidget()
self.tab_widget.setDocumentMode(True)
self.tab_widget.tabBarDoubleClicked.connect(self.add_new_tab)
self.tab_widget.currentChanged.connect(self.update_url_bar)
self.tab_widget.setTabsClosable(True)
self.tab_widget.tabCloseRequested.connect(self.close_current_tab)
self.setCentralWidget(self.tab_widget)
self.status = QLineEdit()
self.status.setReadOnly(True)
self.statusBar().addPermanentWidget(self.status)
navtb = QToolBar("Navigation")
self.addToolBar(navtb)
self.url_bar = QLineEdit()
self.url_bar.returnPressed.connect(self.navigate_to_url)
self.back_button = QPushButton('<')
self.back_button.clicked.connect(lambda: self.tab_widget.currentWidget().back())
self.forward_button = QPushButton('>')
self.forward_button.clicked.connect(lambda: self.tab_widget.currentWidget().forward())
self.reload_button = QPushButton('R')
self.reload_button.clicked.connect(lambda: self.tab_widget.currentWidget().reload())
self.add_tab_button = QPushButton('+')
self.add_tab_button.clicked.connect(self.add_new_tab)
self.auto_browse_button = QPushButton('Auto Browse')
self.auto_browse_button.clicked.connect(self.toggle_auto_browse)
navtb.addWidget(self.back_button)
navtb.addWidget(self.forward_button)
navtb.addWidget(self.reload_button)
navtb.addWidget(self.url_bar)
navtb.addWidget(self.add_tab_button)
navtb.addWidget(self.auto_browse_button)
self.menu_bar = QMenuBar()
self.setMenuBar(self.menu_bar)
self.file_menu = QMenu("&File", self)
self.menu_bar.addMenu(self.file_menu)
self.bookmark_menu = QMenu("&Bookmarks", self)
self.menu_bar.addMenu(self.bookmark_menu)
self.bookmark_menu.addAction("Add Bookmark", self.add_bookmark)
self.bookmark_menu.addAction("Show Bookmarks", self.show_bookmarks)
self.history_menu = QMenu("&History", self)
self.menu_bar.addMenu(self.history_menu)
self.history_menu.addAction("Show History", self.show_history)
self.settings_menu = QMenu("&Settings", self)
self.menu_bar.addMenu(self.settings_menu)
self.settings_menu.addAction("Set Home Page", self.set_home_page)
self.settings_menu.addAction("Set Auto Browse", self.set_auto_browse)
self.add_new_tab(QUrl(self.home_page), "Home")
def add_new_tab(self, qurl=None, label="New Tab"):
if qurl is None:
qurl = QUrl(self.home_page)
browser = QWebEngineView()
browser.setUrl(qurl)
i = self.tab_widget.addTab(browser, label)
self.tab_widget.setCurrentIndex(i)
browser.urlChanged.connect(lambda qurl, browser=browser: self.update_url(qurl, browser))
browser.loadFinished.connect(lambda _, i=i, browser=browser: self.tab_widget.setTabText(i, browser.page().title()))
browser.page().profile().downloadRequested.connect(self.download_requested)
def update_url(self, qurl, browser=None):
if browser != self.tab_widget.currentWidget():
return
self.url_bar.setText(qurl.toString())
self.status.setText(qurl.toString())
self.history.append(qurl.toString())
def navigate_to_url(self):
qurl = QUrl(self.url_bar.text())
self.tab_widget.currentWidget().setUrl(qurl)
def update_url_bar(self, i):
qurl = self.tab_widget.currentWidget().url()
self.url_bar.setText(qurl.toString())
self.status.setText(qurl.toString())
def close_current_tab(self, i):
if self.tab_widget.count() < 2:
return
self.tab_widget.removeTab(i)
def add_bookmark(self):
url = self.url_bar.text()
if url and url not in self.bookmarks:
self.bookmarks.append(url)
QMessageBox.information(self, "Bookmark Added", "Bookmark has been added.")
self.save_settings()
def show_bookmarks(self):
dlg = QInputDialog(self)
dlg.setLabelText("Bookmarks:")
dlg.setComboBoxItems(self.bookmarks)
dlg.exec_()
def show_history(self):
dlg = QInputDialog(self)
dlg.setLabelText("History:")
dlg.setComboBoxItems(self.history)
dlg.exec_()
def set_home_page(self):
url, ok = QInputDialog.getText(self, "Set Home Page", "Enter URL:")
if ok and url:
self.home_page = url
self.save_settings()
def set_auto_browse(self):
url, ok1 = QInputDialog.getText(self, "Set Auto Browse URL", "Enter URL:")
if ok1 and url:
interval, ok2 = QInputDialog.getInt(self, "Set Auto Browse Interval", "Enter Interval (seconds):", min=1)
if ok2:
self.auto_browse_url = url
self.auto_browse_interval = interval
self.save_settings()
def toggle_auto_browse(self):
if self.timer.isActive():
self.timer.stop()
self.auto_browse_button.setText("Auto Browse")
else:
self.timer.start(self.auto_browse_interval * 1000)
self.auto_browse_button.setText("Stop Auto Browse")
def auto_browse(self):
if self.auto_browse_url:
self.tab_widget.currentWidget().setUrl(QUrl(self.auto_browse_url))
def download_requested(self, download):
path, _ = QFileDialog.getSaveFileName(self, "Save File", download.path())
if path:
download.setPath(path)
download.accept()
def load_settings(self):
if os.path.exists('browser_settings.json'):
with open('browser_settings.json', 'r') as f:
settings = json.load(f)
self.bookmarks = settings.get('bookmarks', [])
self.history = settings.get('history', [])
self.home_page = settings.get('home_page', 'http://www.google.com')
self.auto_browse_url = settings.get('auto_browse_url', '')
self.auto_browse_interval = settings.get('auto_browse_interval', 60)
def save_settings(self):
settings = {
'bookmarks': self.bookmarks,
'history': self.history,
'home_page': self.home_page,
'auto_browse_url': self.auto_browse_url,
'auto_browse_interval': self.auto_browse_interval
}
with open('browser_settings.json', 'w') as f:
json.dump(settings, f)
app = QApplication(sys.argv)
app.setApplicationName("Advanced Browser")
window = Browser()
window.show()
sys.exit(app.exec_())
CSS @keyframe
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Animation</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box"></div>
</body>
</html>
style.css
@charset "utf-8";
.box {
width: 80px;
height: 80px;
background: pink;
animation-name: move-around;
animation-duration: 4s;
animation-iteration-count: infinite;
}
@keyframes move-around {
25% {
transform: translate(100px, 0);
border-radius: 0;
}
50% {
transform: translate(100px, 100px);
border-radius: 50%;
}
75% {
transform: translate(0, 100px);
border-radius: 0;
}
}
python バケモン
import random
class Bakemon:
def __init__(self, name, hp, attack):
self.name = name
self.hp = hp
self.attack = attack
def is_alive(self):
return self.hp > 0
def take_damage(self, damage):
self.hp -= damage
if self.hp < 0:
self.hp = 0
def attack_opponent(self, opponent):
damage = random.randint(1, self.attack)
opponent.take_damage(damage)
return damage
def create_bakemon():
bakemon_list = [
Bakemon("Bakachu", 50, 10),
Bakemon("Charabak", 60, 12),
Bakemon("Bakasaur", 55, 11),
Bakemon("Squirtlemon", 50, 10)
]
return bakemon_list
def choose_bakemon(bakemon_list):
print("Choose your Bakemon:")
for idx, bakemon in enumerate(bakemon_list):
print(f"{idx + 1}. {bakemon.name} (HP: {bakemon.hp}, Attack: {bakemon.attack})")
choice = int(input("Enter the number of your choice: ")) - 1
return bakemon_list[choice]
def battle(player_bakemon, enemy_bakemon):
print(f"A wild {enemy_bakemon.name} appeared!")
while player_bakemon.is_alive() and enemy_bakemon.is_alive():
print(f"\n{player_bakemon.name} (HP: {player_bakemon.hp}) vs {enemy_bakemon.name} (HP: {enemy_bakemon.hp})")
action = input("Do you want to attack (a) or run (r)? ").lower()
if action == 'a':
damage = player_bakemon.attack_opponent(enemy_bakemon)
print(f"{player_bakemon.name} dealt {damage} damage to {enemy_bakemon.name}!")
if enemy_bakemon.is_alive():
damage = enemy_bakemon.attack_opponent(player_bakemon)
print(f"{enemy_bakemon.name} dealt {damage} damage to {player_bakemon.name}!")
else:
print(f"{enemy_bakemon.name} is defeated!")
break
elif action == 'r':
print("You ran away!")
break
else:
print("Invalid action. Please choose again.")
if not player_bakemon.is_alive():
print(f"{player_bakemon.name} is defeated! Game over.")
return False
return True
def main():
print("Welcome to the Bakemon game!")
bakemon_list = create_bakemon()
player_bakemon = choose_bakemon(bakemon_list)
while True:
enemy_bakemon = random.choice(bakemon_list)
if enemy_bakemon == player_bakemon:
continue
if not battle(player_bakemon, enemy_bakemon):
break
play_again = input("Do you want to battle again? (y/n): ").lower()
if play_again != 'y':
print("Thanks for playing! Goodbye.")
break
if __name__ == "__main__":
main()
GPT-2 ChatBot
import nltk
from transformers import pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import numpy as np
import spacy
# nltkのセットアップ(初回のみ)
nltk.download('punkt')
# spaCyのセットアップ
nlp = spacy.load("en_core_web_sm")
# サンプルデータ(インテントとそのサンプル文)
training_sentences = [
"Hello", "Hi", "Hey", "Good morning", "Good evening",
"How are you?", "What's up?", "How's it going?",
"Bye", "Goodbye", "See you later", "Take care",
"Thank you", "Thanks", "I appreciate it",
"What's your name?", "Who are you?",
"What can you do?", "Tell me a joke", "Make me laugh",
"What's the weather like?", "How's the weather?",
"Book a flight", "I need to book a flight", "Can you book a flight for me?"
]
intents = [
"greeting", "greeting", "greeting", "greeting", "greeting",
"how_are_you", "how_are_you", "how_are_you",
"goodbye", "goodbye", "goodbye", "goodbye",
"thanks", "thanks", "thanks",
"name", "name",
"capabilities", "joke", "joke",
"weather", "weather",
"book_flight", "book_flight", "book_flight"
]
# 特徴抽出器と分類器のセットアップ
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(training_sentences)
classifier = LogisticRegression()
classifier.fit(X, intents)
# GPT-2 を使用したテキスト生成パイプラインの作成
chatbot = pipeline("text-generation", model="gpt2")
# インテントに基づく応答
responses = {
"greeting": ["Hello! How can I help you?", "Hi there! What can I do for you?"],
"how_are_you": ["I'm just a bot, but I'm here to help you!", "I'm fine, thank you! How can I assist you today?"],
"goodbye": ["Goodbye! Have a great day!", "See you later!"],
"thanks": ["You're welcome!", "No problem!"],
"name": ["I am your friendly chatbot.", "I'm an AI created to assist you."],
"capabilities": ["I can chat with you and help answer your questions!", "I'm here to assist you with various tasks."],
"joke": ["Why did the scarecrow win an award? Because he was outstanding in his field!"],
"weather": ["The weather is nice today!", "It's a bit cloudy, but still good."],
"book_flight": ["Sure, I can help you with that. Where would you like to go?"]
}
# 未知のインテントに対するエラーレスポンス
default_responses = ["I'm not sure I understand. Can you please rephrase?", "Sorry, I don't have an answer for that."]
# インテント認識
def get_intent(user_input):
X_test = vectorizer.transform([user_input])
intent = classifier.predict(X_test)[0]
return intent
# エンティティ認識
def get_entities(user_input):
doc = nlp(user_input)
entities = {ent.label_: ent.text for ent in doc.ents}
return entities
# 応答生成
def get_response(user_input):
intent = get_intent(user_input)
entities = get_entities(user_input)
if intent in responses:
response = np.random.choice(responses[intent])
if intent == "book_flight" and "GPE" in entities:
response = f"Sure, I can help you book a flight to {entities['GPE']}. When would you like to travel?"
return response
else:
response = chatbot(user_input, max_length=50, num_return_sequences=1)
return response[0]['generated_text']
# メイン関数
def main():
print("Chatbot: Hello! How can I help you today? (Type 'exit' to quit)")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("Chatbot: Goodbye!")
break
response = get_response(user_input)
print(f"Chatbot: {response}")
if __name__ == "__main__":
main()
CSS transition-delay
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Animation</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box"></div>
</body>
</html>
style.css
@charset "utf-8";
.box {
width: 80px;
height: 80px;
background: pink;
transition-property: transform;
transition-duration: 500ms;
transition-delay: 1s;
}
.box:hover {
transform: translateX(100px);
}
java 数当てゲーム
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean playAgain = true;
int highScore = 0;
System.out.println("数当てゲームへようこそ!");
while (playAgain) {
int minRange = 1;
int maxRange = 100;
int randomNumber = (int) (Math.random() * (maxRange - minRange + 1)) + minRange;
int attempts = 0;
System.out.println("1から100までの数を当ててください!");
while (true) {
System.out.print("予想した数字を入力してください: ");
if (!scanner.hasNextInt()) {
System.out.println("無効な入力です。数値を入力してください。");
scanner.next(); // 不正な入力をクリア
continue;
}
int guessedNumber = scanner.nextInt();
attempts++;
if (guessedNumber < randomNumber) {
System.out.println("もっと大きい数字です。");
} else if (guessedNumber > randomNumber) {
System.out.println("もっと小さい数字です。");
} else {
System.out.println("おめでとうございます!正解です!");
System.out.println("あなたの試行回数: " + attempts);
if (attempts < highScore || highScore == 0) {
highScore = attempts;
System.out.println("新しいハイスコア!試行回数: " + highScore);
} else {
System.out.println("ハイスコアは" + highScore + "回です。");
}
break;
}
}
System.out.print("もう一度プレイしますか? (y/n): ");
String playChoice = scanner.next();
playAgain = playChoice.equalsIgnoreCase("y");
}
System.out.println("ゲームを終了します。");
System.out.println("最終ハイスコア: " + highScore);
scanner.close();
}
}
CSS ブレイクポイント
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Media Queries</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html>
style.css
@charset "utf-8";
body {
background: pink;
}
/* width >= 600px */
@media (min-width: 600px) {
body {
background: skyblue;
}
}
@media (min-width: 800px) {
body {
background: orange;
}
}
動画共有サイト
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>動画共有サイト</title>
<style>
/* スタイルは省略 */
</style>
</head>
<body>
<header>
<h1>動画共有サイト</h1>
</header>
<main>
<section id="video-container">
<!-- 動画を表示 -->
<iframe width="560" height="315" src="https://www.youtube.com/embed/Qkls4DCX_9I" frameborder="0" allowfullscreen></iframe>
</section>
<section id="comments-container">
<!-- コメントを表示 -->
</section>
<section id="comment-form-container">
<!-- コメントを投稿するフォーム -->
<form id="comment-form">
<textarea id="comment-input" rows="3" placeholder="コメントを入力してください"></textarea>
<button type="submit">コメントを投稿</button>
</form>
</section>
<section id="categories">
<!-- カテゴリ一覧 -->
<h2>カテゴリ</h2>
<ul>
<li><a href="#">音楽</a></li>
<li><a href="#">スポーツ</a></li>
<li><a href="#">ゲーム</a></li>
<li><a href="#">ニュース</a></li>
</ul>
</section>
</main>
<footer>
<!-- お気に入りボタン -->
<button id="favorite-button">お気に入り</button>
<!-- 検索フォーム -->
<input type="text" id="search-input" placeholder="動画を検索">
<button id="search-button">検索</button>
</footer>
<script>
// コメントを追加する関数
function addComment(comment) {
var commentsContainer = document.getElementById('comments-container');
var commentElement = document.createElement('div');
commentElement.textContent = comment;
commentsContainer.appendChild(commentElement);
}
// フォームの送信イベントを処理する
document.getElementById('comment-form').addEventListener('submit', function(event) {
event.preventDefault(); // フォームのデフォルトの動作を停止
var commentInput = document.getElementById('comment-input');
var commentText = commentInput.value.trim(); // 入力されたコメントを取得
if (commentText !== '') {
addComment(commentText); // コメントを追加
commentInput.value = ''; // 入力欄をクリア
}
});
// お気に入りボタンのクリックイベントを処理する
document.getElementById('favorite-button').addEventListener('click', function() {
alert('動画をお気に入りに追加しました!');
});
// 検索ボタンのクリックイベントを処理する
document.getElementById('search-button').addEventListener('click', function() {
var searchInput = document.getElementById('search-input').value.trim();
alert('「' + searchInput + '」で検索しました!');
});
</script>
</body>
</html>