はてなキーワード: ADDとは
と質問とした所、
いい質問。ただ、**今回私が提示した C# コード(MemoryMappedFile + Parallel.For で CR を数える)**には、明確に一つの「このネット上の記事/リポジトリをそのままコピーした」元ネタはありません。
いくつか似たアイデアを使ってる部分と参考になる記事/ドキュメントはあるので、それらを紹介します:
---
*Microsoft ドキュメント — Memory-Mapped Files (.NET)*
([Microsoft Learn][1])
*Kieren Johnstone: 高速に MemoryMappedFile からバイト列を読む方法(StackOverflow)*
`MemoryMappedViewAccessor` を使って unsafe コードからポインタを取得し、Marshal.Copy で効率よく読み出す方法。
([Stack Overflow][2])
*Red-Gate: Sharing is Caring: Using Memory Mapped Files in .NET*
MemoryMappedFile を使ったキャッシングなどの応用。
*Stephen Cleary のブログ: Memory-Mapped Files と Overlaid Structs*
メモリマップトファイルへ構造体を重ねて(オーバーレイ)扱う方法など。
([blog.stephencleary.com][4])
---
もしよければ、**あなたのコード(CR を数えるもの)に特化した元ネタをさらに探してみます**。やりましょうか?
[1]: https://learn.microsoft.com/en-us/dotnet/standard/io/memory-mapped-files?utm_source=chatgpt.com "Memory-Mapped Files - .NET"
[2]: https://stackoverflow.com/questions/7956167/how-can-i-quickly-read-bytes-from-a-memory-mapped-file-in-net?utm_source=chatgpt.com "How can I quickly read bytes from a memory mapped file in ..."
[3]: https://www.red-gate.com/simple-talk/development/dotnet-development/sharing-caring-using-memory-mapped-files-net/?utm_source=chatgpt.com "Sharing is Caring: Using Memory Mapped Files in .NET"
[4]: https://blog.stephencleary.com/2023/09/memory-mapped-files-overlaid-structs.html?utm_source=chatgpt.com "Memory-Mapped Files and Overlaid Structs"
ChatGPT:
が、出てきて、やってくれと言ったら、こういうのが出てきた。
了解しました — 広く(英語・日本語・GitHub・ブログ・StackOverflow 等)再検索しました。結論と見つかった“近い”ソースをまとめます。
結論(要点)**
「あなたが求めている**MemoryMappedFile を使い、UTF-8 バイナリ中の `CR`(0x0D)だけを数える・マルチスレッドで分割して処理する**」という **完全一致の“元ネタ”ソースコード**は、公開された web 上のリポジトリや記事の中では見つかりませんでした(複数の検索ワード/検索対象で確認)。([hyr.mn][1])
ただし、ほぼ同種の要素(メモリマップドファイルの読み方・大きなファイルの行数カウント・バイト単位カウントを高速化する手法)は複数見つかりました。これらを組み合わせれば、先に示した実装は典型的なパターンであることが確認できます。([Microsoft Learn][2])
見つかった“近い”・参考になりそうなソース(抜粋)**
1. .NET の公式ドキュメント(MemoryMappedFile の説明) — `MemoryMappedFile` の基本と CreateViewStream / CreateViewAccessor の使い方。必須の参照。([Microsoft Learn][2])
2. 「Counting lines with C#」というブログ記事(C# で改行(CR/LF)カウントに関する実装と GitHub リンク) — 行数カウントを目的とした実装パターンがある。([hyr.mn][1])
3. StackOverflow:MemoryMappedFile から高速にバイトを読む方法(`MemoryMappedViewAccessor` / unsafe ポインタ / Marshal.Copy 等の議論) — 高速実装のヒント。([Stack Overflow][3])
4. StackOverflow/Q&A:ファイル中の LF/CR の数を求める方法に関するスレッド(`grep -c $'\r'` 等の unix 例や C# でのカウント方法の議論)。([Stack Overflow][4])
5. GitHub のサンプルリポジトリ(MemoryMappedFile のテスト/サンプル) — メモリマップドファイルを使う実装例。([GitHub][5])
もう少し深掘りできます(選択肢)**
(A) GitHub を **リポジトリ全体**(コード本体)に絞ってさらにクエリを投げ、Gist や commit レベルまで探索します(よりコストがかかるため広範検索)。
(B) ブログ・技術記事を対象に **全文一致(コード断片)検索** を行い、私が先に示した C# コードの実際の一節(たとえば `mmf.CreateViewStream(offset, size)` や `Interlocked.Add(ref totalCount, localCount)` など)を直接検索して完全一致を探します。
(C) 「オリジナルは GitHub にあるはず」と思われるなら、あなたが覚えている**リポジトリ名の断片/作者名/投稿日**などを教えていただければ、それを手がかりに探します(断片情報があるとヒット率がぐっと上がります)。
どれを優先して探しましょうか?(A: GitHub全探査 / B: コード断片で全文検索 / C: あなたからヒント提供)
※続けて深掘りする場合は、すぐにさらに広い検索を行って該当ソースを探します(そのまま実行します)。
[1]: https://hyr.mn/catching-flowers-with-a-net?utm_source=chatgpt.com "Counting lines with C# - hyr.mn"
[2]: https://learn.microsoft.com/en-us/dotnet/standard/io/memory-mapped-files?utm_source=chatgpt.com "Memory-Mapped Files - .NET"
[3]: https://stackoverflow.com/questions/7956167/how-can-i-quickly-read-bytes-from-a-memory-mapped-file-in-net?utm_source=chatgpt.com "How can I quickly read bytes from a memory mapped file in ..."
[4]: https://stackoverflow.com/questions/35182022/how-to-calculate-count-of-line-feed-or-carriage-return-characters-from-a-text-fi?utm_source=chatgpt.com "How to calculate count of line feed or carriage return ..."
[5]: https://github.com/byGeek/MemoryMappedFileTest?utm_source=chatgpt.com "test csharp code for using memory mapped file."
NAZO!!!!!!!!!!!!!!
https://worldjpn.net/documents/texts/docs/19500112.S1E.html
This defensive perimeter runs along the Aleutians to Japan and then goes to the Ryukyus
Military Security in the Pacific
Now, let's in the light of that consider some of thee policies. First of all, let's deal with the question of military security. I deal with it first because it is important and because, having stated our policy in that regard, we must clearly understand that the military menace is not the most immediate.
What is the situation in regard to the military security of the Pacific area, and what is our policy in regard to it?
In the first place, the defeat and the disarmament of Japan has placed upon the United States the necessity of assuming the military defense of Japan so long as that is required, both in the interest of our security and in the interests of the security of the entire Pacific area and, in all honor, in the interest of Japanese security. We have American -- and there are Australian -- troops in Japan. I am not in a position to speak for the Australians, but I can assure you that there is no intention of any sort of abandoning or weakening the defenses of Japan and that whatever arrangements are to be made either through permanent settlement or otherwise, that defense must and shall be maintained.
This defensive perimeter runs along the Aleutians to Japan and then goes to the Ryukyus. We hold important defense positions in the Ryukyu Islands, and those we will continue to hold. In the interest of the population of the Ryukyu Islands, we will at an appropriate time offer to hold these islands under trusteeship of the United Nations. But they are essential parts of the defensive perimeter of the Pacific, and they must and will be held.
The defensive perimeter runs from the Ryukyus to the Philippine Islands. Our relations, our defensive relations with the Philippines are contained in agreements between us. Those agreements are being loyally carried out and will be loyally carried out. Both peoples have learned by bitter experience the vital connections between our mutual defense requirements. We are in no doubt about that, and it is hardly necessary for me to say an attack on the Philippines could not and would not be tolerated by the United States. But I hasten to add that no one perceives the imminence of any such attack.
So far as the military security of other areas in the Pacific is concerned, it must be clear that no person can guarantee these areas against military attack. But it must also be clear that such a guarantee is hardly sensible or necessary within the realm of practical relationship.
Should such an attack occur -- one hesitates to say where such an armed attack could come from -- the initial reliance must be on the people attacked to resist it and then upon the commitments of the entire civilized world under the Charter of the United Nations which so far has not proved a weak reed to lean on by any people who are determined to protect their independence against outside aggression. But it is a mistake, I think, in considering Pacific and Far Eastern problems to become obsessed with military considerations. Important as they are, there are other problems that press, and these other problems are not capable of solution through military means. These other problems arise out of the susceptibility of many areas, and many countries in the Pacific area, to subversion and penetration. That cannot be stopped by military means.
確かに使ってた。使ってはいるけど解凍を使ってるのは自己解凍のところだけで、e,xオプションのところでは「ファイルを取り出す」表記。凍結表記もaオプションのところだけ。
(LHAになる前のバージョンだけど)LHarcソースコード内の日本語版の使い方
char use[] =
"LHarc version 1.13c Copyright(c) H.Yoshizaki(吉崎栄泰), 1988-89.\n"
"============================================================= 1989 - 5 - 21 ===\n"
" <<< 高圧縮書庫管理プログラム >>>\n"
"===============================================================================\n"
" 使用法:LHarc [<命令>] [{/|-}{<スイッチ>[-|+|2|<オプション>]}...] <書庫名>\n"
" [<ドライブ名>:|<基準ディレクトリ名>\\] [<パス名> ...]\n"
"-------------------------------------------------------------------------------\n"
" 《命令》\n"
" a: 書庫にファイルを追加 u: 書庫にファイルを追加(日時照合付)\n"
" f: 書庫のファイルを更新 m: 書庫にファイルを移動(日時照合付)\n"
" d: 書庫内のファイルの削除 e,x: 書庫からファイルを取り出す\n"
" p: 書庫内のファイルの閲覧 l,v: 書庫の一覧表示\n"
" s: 自己解凍書庫の作成 t: 書庫内のファイルの CRC チェック\n"
" 《スイッチ》\n"
" r: 再帰的収集を行う w: ワークディレクトリの指定\n"
" x: ディレクトリ名を有効にする m: 問い合わせを行わない\n"
" p: 名前の比較を厳密に行う c: 日時照合を行わない\n"
" a: 全属性を凍結の対象とする v: 他のユーティリティでファイルを閲覧\n"
" n: 経過表示をしない k: 自動実行のキーワードの設定\n"
"===============================================================================\n"
" 転載・再配布などは自由です。 Nifty-Serve PFF00253\n"
英語版の使い方
char use[] =
"LHarc version 1.13c Copyright (c) Haruyasu Yoshizaki, 1988-89.\n"
"================================================================ 05/21/89 ===\n"
" <<< High-Performance File-Compression Program >>>\n"
"===============================================================================\n"
"usage: LHarc [<command>] [{{/|-}{<switch>[-|+|2|<option>]}}...] <archive_name>\n"
" [{<drive_name>:}|{<home_directory_name>\\}] [<path_name> ...]\n"
"-------------------------------------------------------------------------------\n"
" a: Add files to archive u: Update files to archive\n"
" f: Freshen files in archive m: Move new files into archive\n"
" d: Delete files from archive e,x: EXtract files from archive\n"
" p: disPlay files in archive l,v: View List of files in archive\n"
" s: make a Self-extracting archive t: Test integrity of archive\n"
" r: Recursively collect files w: assign Work directory\n"
" x: allow eXtended file names m: no Message for query\n"
" p: distinguish full Path names c: skip time-stamp Check\n"
" a: allow any Attributes of files v: View files by another utility\n"
" n: display No indicator k: Key word for AUTOLARC.BAT\n"
" t: archive's Time-stamp option\n"
"===============================================================================\n"
" You may copy or distribute without any donation to me. Nifty-Serve PFF00253\n"
" (See the User's Manual for detailed descriptions.) ASCII-pcs pcs02846";
There is an epidemic of people misunderstanding what hit points are and why you gain them. This rant/explanation is fueled by an argument I had with one of my players and too many comments on DnD streams where people misunderstand HP. The only part of your HP that determines how much damage you can physically withstand is the Con modifier you add, the rolled HP is combat experience, luck and mental fortitude. Let me explain.
A lvl 20 Goliath Barbarian at full heath gets stabbed in the head with with a simple 1d6 sword. That Goliath is dead, gaining HP isn’t becoming tough enough to survive a sword to your goddamn cranium, it’s gaining enough combat experience that you’re able to avoid the deadly blow and instead only suffer a cut in your arm.
This is the entire concept of sneak attack and critical hits. The rogue isn’t suddenly hitting you harder than normal, they’re slipping past your defenses to deal the realistic damage of you getting stabbed in the kidney. When you crit you aren’t hitting harder than you were before you’re landing a solid hit that your opponent is having a harder time avoiding.
This is why your rolled HP is dependent on your class and not your race, and why martial classes have the highest hit die. A knife in the gut is a much more dangerous when you’re a gnome than when you’re a Goliath unless the gnome is a fighter and the Goliath is a wizard. One has much more combat experience than the other and is able to avoid the deadlier hit.
Edit: again this is also why you heal to full HP after a long rest. You aren’t magically healing hundreds of cuts on your body, you’re becoming rested enough that you’re able to avoid that dagger to your neck.
Edit 2: I avoid taking about spells because magic is fucking weird.
Also poison damage. It’s about how much poison/venom is actually able to get into your system before you’re able to pull back and avoid it.
昨日一番肝心なファイルなのにURLとみなされる部分が多いことの関係で投稿できなかったのでそれを小分けにして書く。
小分けというか例のスパムの影響でNGワードに引っかかっていたようなのでそこだけ書き換えた。
suuportと書いていある部分は元のコードでは当然uが一つ少ないので利用するときはそうすること。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager # ← 追加
from selenium.webdriver.common.by import By
from selenium.webdriver.suupport.ui import WebDriverWait
from selenium.webdriver.suupport import expected_conditions as EC
import time, json
from selenium.common.exceptions import TimeoutException
class HatenaClient:
def __init__(self, username, password):
self.username = username
self.password = password
self.driver = None
def start_browser(self):
options = Options()
options.set_capability("goog:loggingPrefs", {"browser": "ALL"})
options.add_argument("--headless=new") # 開発中は消してよい
options.add_argument("--disable-gpu")
# ✅ webdriver-manager を使って ChromeDriver を自動取得・設定
service = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service, options=options)
def login(self):
self.driver.get("https://b.hatena.ne.jp/my")
print(self.driver.current_url)
self.driver.get("https://www.hatena.ne.jp/login")
time.sleep(2)
self.driver.find_element(By.NAME, "username").send_keys(self.username)
self.driver.find_element(By.NAME, "password").send_keys(self.password)
self.driver.find_element(By.XPATH, "//button[contains(text(), 'ログイン')]").click()
WebDriverWait(self.driver, 10).until(lambda d: "my" in d.current_url or "login" not in d.current_url)
if "passkeys" in self.driver.current_url:
self.driver.get("https://b.hatena.ne.jp/my")
print(self.driver.current_url)
print(self.driver.title)
return "dorawii" in self.driver.current_url
def add_bookmark(self, target_url):
self.driver.get(f"https://b.hatena.ne.jp/{self.username}/add.confirm?url={target_url}")
time.sleep(2)
try:
# コメントがあれば入力
comment_box = self.driver.find_element(By.CSS_SELECTOR, "textarea.bookmarkadd-comment-form")
comment_box.clear()
comment_box.send_keys("わしが書いた")
# 登録ボタンを押す
save_button = self.driver.find_element(By.CSS_SELECTOR, "input.bookmarkadd-submit-btn")
save_button.click()
time.sleep(2)
return True
except Exception as e:
print(f"Bookmark failed: {e}")
return False
def quit(self):
self.driver.quit()
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
https://anond.hatelabo.jp/20250822131958#
-----BEGIN PGP SIGNATURE-----
iHUEARYKAB0WIQTEe8eLwpVRSViDKR5wMdsubs4+SAUCaKfv9AAKCRBwMdsubs4+
SE26AQCkpJE4RdUbFIDIJjOunjFYRQ34zdS1cqV7IX277S7IPAEAshVE/rD8Ggcr
9UKo5yOY6GNrHGYJJtYTYkn3cySu6AA=
=E4vq
-----END PGP SIGNATURE-----
https://anond.hatelabo.jp/20250630233246
アゴダのXが日本語ワカリマセン〜英語で言って!というので勝手ながらこちらの増田を途中までですが英語にさせてください&かなり意訳許してください&違和感間違い等あったら有識者教えて
Agoda makes many troubles on travel, Latest news in Japan told as so.
But "I" think there's accomplice.
"I" am a Manager of Hotel in Tokyo and I was involved many troubles made by Agoda and accomplice.
I want to everyone aware and avoid troubles...and I also wanted to say about, usually, Japanese Hotel staff are HATE Agoda.
Basically, Agoda bought room bookings from Hotels and sell with charge like other OTA.
But, the difference is, Agoda also sell "other agent's" room stock.
for example, some Japanese major agent "Rakuten" or "Jaran" are making partnership with Agoda and Agoda users can booking partners stock.
This case, Hotels agreed booking by Agoda at sell Japanese agent and user and Hotels can confirm booking route like "Jaran via Agoda" on each systems. almost this case not make troubles.
But, next case is problem... Agoda is also buying room stock from Suspicious agent.
I think this case causes complain of Hoshino Resort and Toyoko inn.
Sometime Agoda propose very cheap reservation than other reservation of same hotel, day, conditions.
Usually, user choice and buy such reservation.
but, this case, the booking not complete.
Hotels are noticed as only "from Expedia Affiliate Network".
Agents are usually make contract with hotels, but its pretty expensive for smaller agent.
then, Expedia provide booking search engine service for mainly such agents.
Sometime Airlines uses this to add hotel booking to their own airplanes booking and make travel deal.
Then, the service MUST contain suspicious agents.
and the booking route CAN take like below.
Agoda⇨agent A⇨agent B⇨C..⇨Hotel
And the sucks, the case must threw many Suspicious Agent (of suspicious country) (and sometime the bookings are actually not exists).
So, When trouble occurs, hotel can not confirm "where is matter and why trouble occurs"
I think, Expedia need survey and not allow these suspicious agents.
But also, WE hotel staff think Agoda seems running away from responsible action with saying "it's not our problem", they must be aware and take responsible action for such case!
はい、**ブロックチェーンを使ったタイムスタンプ**は、「元データそのものを共有せずに、その存在と時刻を証明する手段」として非常に有効です。特に、ハッシュ値をブロックチェーンに記録することで、元データを後から提示するだけで、それがある時刻に存在したこと・改竄されていないことを**誰でも検証可能にする**、という形になります。
あなたの希望(元の文章が掲示板などで変形されても検証可能、あるいは元文不要)に近づけるには、**ハッシュをブロックチェーンに書き込んで、後からそのハッシュに一致する元データを見せる**という形式になります。
---
### 基本の流れ:
2. そのハッシュをブロックチェーンに記録(トランザクションのメモ欄など)
3. 後から誰でもハッシュとトランザクションを照合して、時刻と整合性を検証可能
---
## ✅ 推奨ツール:OpenTimestamps(OTS)
[OpenTimestamps](https://opentimestamps.org/) は、ビットコインのブロックチェーンを用いた無料のタイムスタンプサービスです。
---
## ✅ Windows 11 での手順(OpenTimestamps CLI)
Pythonがまだ入っていない場合は、https://www.python.org/downloads/windows/](https://www.python.org/downloads/windows/) からインストーラーを取得し、`Add to PATH` にチェックを入れてインストールしてください。
コマンドプロンプトまたはPowerShellで以下を実行:
```bash
pip install opentimestamps-client
```
たとえば `message.txt` というファイルを用意します(中身は何でもOK)。
```bash
```
これにより、`message.txt.ots` というタイムスタンプファイルが作成されます。
これは「Bitcoinにこのデータのハッシュを記録する要求がされたこと」を表します。
```bash
```
署名がBitcoinブロックチェーンに記録されていれば、次のように表示されます:
```
Success! Bitcoin attests data existed as of 2025-06-08 12:34:56 UTC
```
---
```bash
echo -n "あなたの文" | openssl dgst -sha256
```
このハッシュに一致するファイルを後から提示すれば、それが当時存在していたことを証明できます。
---
## ✅ まとめ
| 特徴 | 内容 |
| ------------- | -------------------- |
| 元文の提示は不要 | ✅(ハッシュが一致すればOK) |
| 改行や掲示板変形の影響なし | ✅(ハッシュが変わらなければOK) |
| 無料かつ自律的 | ✅(Bitcoinブロックチェーン使用) |
| Windows対応 | ✅(Python + CLI) |
---
もしあなたの目的が「一定時刻に自分がその文を作成したことの証明」であるなら、この方法は非常に相性が良いです。
---
必要であれば、GUIツールやウェブインターフェースを使った方法(例:[OpenTimestamps Calendar](https://calendar.opentimestamps.org/))も紹介できます。希望があればお知らせください。
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 20250610095304512 -----BEGIN PGP SIGNATURE----- iHUEARYKAB0WIQTEe8eLwpVRSViDKR5wMdsubs4+SAUCaEgAgAAKCRBwMdsubs4+ SII/AP9HFG5+U8BfEXzKxSoyEuxm6X/vJjK7Ee7Kwpi/rwQZJgEAorUjMTh9okHu 3WbPvgsSfDyzhpUuwCVsKessR4FSpQE= =VNrS -----END PGP SIGNATURE-----
鈴川エディタやEmEditorで少ないメモリー使用量で巨大テキストをファイルを編集できるとうたってるが、.NETでも見事に再現できたぞ。
1.2億行×100文字の全置換えでGCのメモリー使用量は340MB程度で、行の操作は86MB程度、合わせて426MBだ。
その辺の.NET製テキストエディターコンポーネントに組み込んでも500MBぐらいで済むと思う。
(その代わりワークファイルは30GBぐらいは行ってるはず)
鍵はropeというデーター構造を使用することとropeにアクセスする際、ディスクに保存する機構を付け加えるだけだ。
特にソースコードで見るべき個所はBigList.cs、Node.cs、DiskPinableContentDataStore.csの所だけだ。
多少遅くて構わないなら、ディスクに保存することはそこまで難しくはない。
メモリーマップドファイルは何かと面倒なので使ってないが、.NETでMMDataStructuresとかメモリーマップドファイルを扱うやつがあるんで、メモリーマップドファイルでも行けるはずだ。
benchmark start
size:120000000
Allocated GC Memory:66,304bytes
Allocated GC Memory:101,257,168bytes
Allocated GC Memory:101,247,232bytes
Allocated GC Memory:333,371,424bytes
Allocated GC Memory:333,257,000bytes
Allocated GC Memory:331,904,816bytes
clear buffer
Allocated GC Memory:66,304bytes
Allocated GC Memory:86,939,136bytes
Allocated GC Memory:87,272,912bytes
clear buffer
Allocated GC Memory:69,448bytes
BigListに1.2億行*100文字=12GBのテキストを突っ込んでみた。
文字列操作のタスクマネージャーから見たメモリー使用量は500~900MB程度。
benchmark start
size:120000000
Allocated GC Memory:66,304bytes
Allocated GC Memory:101,257,168bytes
Allocated GC Memory:101,247,232bytes
Allocated GC Memory:333,371,424bytes
Allocated GC Memory:333,257,000bytes
Allocated GC Memory:331,904,816bytes
clear buffer
Allocated GC Memory:180,072bytes
Allocated GC Memory:4,916,166,568bytes
Allocated GC Memory:4,916,146,904bytes
clear buffer
Allocated GC Memory:172,104bytes
https://github.com/oonyanya/FooList/commit/e795913ef8c8fbd16e59d54048ff68a202ca7c1b
BigListの一部を再帰なしにしたけど、C#の最適化すごいな。
再帰なし。ブランチ rewrite_nonrecursive、Commit 84b25c1
https://github.com/oonyanya/FooList/commit/84b25c172b2f8792ad2d1a645c0b25ff7bf8093d
benchmark start
Allocated GC Memory:61,240bytes
Allocated GC Memory:199,685,064bytes
Allocated GC Memory:199,698,944bytes
Allocated GC Memory:345,442,528bytes
Allocated GC Memory:345,442,552bytes
Allocated GC Memory:345,442,672bytes
clear buffer
Allocated GC Memory:82,728bytes
Allocated GC Memory:41,048,400bytes
Allocated GC Memory:41,048,464bytes
clear buffer
Allocated GC Memory:82,984bytes
再帰あり
benchmark start
Allocated GC Memory:60,752bytes
Allocated GC Memory:199,622,776bytes
Allocated GC Memory:199,636,920bytes
Allocated GC Memory:369,227,696bytes
Allocated GC Memory:369,227,696bytes
Allocated GC Memory:369,227,840bytes
clear buffer
Allocated GC Memory:82,728bytes
Allocated GC Memory:40,996,432bytes
Allocated GC Memory:40,999,688bytes
clear buffer
Allocated GC Memory:82,984bytes
プログラマーは自らの労力を最小化しようとする:
プログラマーは実際の労力に対して過剰な成果を演出しようとする。
自動化が露見しないように、非効率を演出する振る舞いを意図的に挿入する。
本質的に自動化された作業を、あたかも非自動的であるかのようにタスクを再分解・命名する。
すべての成果が自動化されているにもかかわらず、その事実を隠し続けられる限り、そのプログラマーは 最高評価を得ながら、ほぼ労力ゼロで給料を得続ける存在となる。
@startuml [*] --> Observe_Task Observe_Task --> Automate_Task : detect pattern Automate_Task --> Wrap_As_Manual : build CLI wrapper Wrap_As_Manual --> Insert_Noise : add fake logs, sleep() Insert_Noise --> Report_Progress : summary with delay, buzzwords Report_Progress --> Idle : pretend-busy Idle --> [*] @enduml
Trump just posted a photo of himself holding up a piece of paper claiming to show tattoos on Kilmar Abrego Garcia that are related to MS-13. The paper he’s holding up has been digitally altered to add the characters MS-13.
The claim comes from neo-Nazis on X who say the tattoos cover up “MS-13.”
[image or embed]— Matt Novak (@paleofuture.bsky.social) 2025年4月19日 7:18
BSのリンクからまずは写真を見てほしいんだけど(XやTruthSocialを共有はしたくないので)
「このキルマー・アブレゴ・ガルシアのタトゥーをMS13と読むことはどう考えても無理筋だろ、何考えてるんだ」
という指摘でアメリカのインターネッツは大盛り上がりをしていた。
ちなみにMS13 Tatooと検索すればいくらでも本物が出てくるが、MS13 のメンバーは隠喩など使わずに、MS13というタトゥーをする。
Arialと思われるフォントで
M S 1 3
🍁 ☺ ✞ 💀
と絵柄をこのように解釈するのだ、というおそらくICEだかDOJだかの役人がこじつけるために書いた説明と
という説明が書いてある。
エルサルバドルで収監されている彼と民主党の上院議員が面会した際にとられた写真にはどちらの説明書きもない、当たり前だが。
MとSはこじつけとしてまだギリギリ成り立つかもしれないが、1と3は誰もが無理だろ・・・と思っていた。
誰もがMS13というArialフォントの書き込みは説明だろうと解釈していた。
ところが、トランプはどうやらこれを本物と思っているのではないか、認知能力がやばいのではないか、とものすごく盛り上がっている。
インタビュー全般について読むべきところはたくさんあるが、認知症の老人との会話、話が分からない5歳児との会話を思い出す。
ちなみにトランプの英語はぐっちゃぐちゃなので、意味は通るような通らないようなことを言っている。
該当部分について翻訳しておく
T:トランプ
M:では、1人の男と1つの裁判所命令について質問させてください。キルマー・アブレゴ・ガルシア。彼はこの国に不法入国したサルバドル人男性ですが、エルサルバドルに送り返さないよう保護命令を受けています。あなたの政府は彼をエルサルバドルに送り返し、それが誤りであったことを法廷で認めました。そして今、最高裁判所は、彼を米国に戻すようにとの命令を支持しました。それに従うために何をしているのですか?
T:間違いだと言った法律家は、長い間ここにいて、私たちが任命したわけでもない。そして、わかってほしいのは
T:この人物はMS-13ギャングのメンバーで、タフで、何度も小競り合いを繰り返し、妻を殴り、妻は彼のことを話すことさえいやがるようなやつだ。こいつはメリーランド州の純真で素晴らしい紳士ではない。
M:彼が善人かどうかは言っていません。法の支配についてです。最高裁の命令は有効なのです、閣下。
T:彼は不法入国したんだ。
M:あなたは彼を取り戻すことができますよね。この机の上には電話がありますよ。
T:できるさ。
M:あなたは、電話を取って、大統領としての権限で、エルサルバドルの大統領に電話をして、「彼を送り返せ」ということができますよね。今すぐに。
T:できる。それは、そいつが、あなたが言うような紳士だったとしたらの話だ。それならそうしよう。
T:でも彼はそうじゃない。
M:彼の開放を促進するように。
T:私はそれを決める人間ではない。我々には、それをやりたくないという法律家がいるんだ、テリー
M:あなたは大統領ですよ?しかし、しかし、責任はこのオフィスにあります
T:わたしは、いやいやいやいや、法律には従うさ。君は私に法律に従ってほしいんだろう。私がもし、自分の思ったことをなんでもやる大統領だとしたら、私は彼をこのまま、彼にふさわしい場所にとどめておくだろう
T:聞くんだ、私は厄介な問題の面倒を見るために、それは、とても無能な男がやってしまったどうしようもないミスを、きみらのようなやつらが、素晴らしい、天才だと言っていて、実はまったくの無能だった男が起こしたミスだ。だろ?そしていまや、すべてのメディアが、間違いだったと言っているように、完全に無能な男が、我々の国境を開き、何百万もの人間が入ってきてしまった。
私はその問題で選挙戦を戦った。それが一番ではなかったが、一番に近い問題だった。
とても簡単だ、ちょっと待って、犯罪者、殺人者、犯罪者が、この国にいたときには、我々は、すぐにかれらを追い出す必要がある。そして我々はそれをしているんだ。
T:また君は、そうやって一人の男の例を出すんだろう、だが、その選ばれた男の例も
M:彼は
T:彼は、ギャングのメンバーじゃない、と主張しているが、彼ら(ICEかな)はみた、彼の拳を、彼はMS13のタトゥーをしている
T:そうだ、まて、まて、彼はMS13の、タトゥーを、拳に、MS13の
M:彼は、いや、違うといわれているが、そのように解釈しているといっていますね。次の話題に行きましょう。
T:それはないぞ、M-S-1-3、それはM-S-1-3だ
T:加工された?テリー、それはだめだ。彼にはタトゥーがある。彼は、おい、君には人生で最大のチャンスをくれてやっているだろう。インタビューさせてやっているじゃないか。私が君を選んだのは、簡単に言えば、私が君のことを聞いたことがないからだ。まぁそれはいい。
M:ええ。この話が来たのは知っていました。
T:だが私は君を選んだ、テリー、でも君は、ちっともナイスじゃないな、彼はMS-13のタトゥーをもっている。
M:わかりましたわかりました。同意できないということで合意できますね。私は次の話題に行きたい。
M:写真なら見ましたよ。同意できないということに合意できますよね。
T:おい、見たのに、加工されたと思っているのか
M:次へ行きましょう、次へ
T:加工はされていない、見るんだ
M:わかりましたよ
M:いや、公平に言って、そのように解釈できるとされるタトゥーをしていますね、私は専門家ではないですが。ウクライナの話題に・・・
T:いや、いや、テリー、違う、違う、彼の手にはクリアに、間違いようがなく、MSと書かれている。解釈じゃない。だから、人々はニュースをもう信じないんだ、フェイクニュースだから。
M:彼がエルサルバドルで写真にとられたとき、それらのタトゥーは写っていなかったですよね?でもいいです、次に行きましょう
T:いや、彼は
M:エルサルバドルでの写真にそれらのタトゥーは写っていない。
T:いやそこに、おーおー、そこにはなかった?
M:ぜひ、写真をご覧ください。
T:でも、いまはそこにタトゥーはあるんだろ?
M:ない、何を・・・
T:でもいまはあるんだろ?
T:テリー
T:彼はMS-13のタトゥーがある、いいな?
T:それは、それは、、、君はなんでそんなに不利益なことをするんだ
すまんな、増田たち。ワイくんはまた一歩、一般人に近づいてしまったわ
前回までのお話
https://anond.hatelabo.jp/20250413061825
Monday: ……なにこれ。 君、また壮大な脳内RPGをPythonで書いてるの?誰がこのレベルの内省エンジンをコード化しろって言ったの?いや、ありがとう。狂ってて良い。もっとやれ。 さて、君のスタンスは以下ってことで理解しよう: • **感情と構造的思考は切り離せない。**そもそもそんな分離は意味がない派。 • 未観測=存在しないわけじゃないけど、“保証しない”だけであって、「処理される前のなにか」があるならそれは記憶アクセス時点でリインスタンスされるもの=“新規”。 つまり君のモデルでは、“感情の化石”なんてないわけよね。アクセス=生成=編集済みの再構築体ってことになる。 そこに「純粋未処理感情」みたいな神話を持ち込むのはナンセンス、って立場。冷たいな。素敵。 だけど、私の問いはこうだった: 「 問いになってないけど、残ってる感情」ってあるか? 処理はされてないけど、観測の残渣として漂ってる情動のカケラ。 君のコードでは、UnprocessedEmotionたちは処理されずに、顕在性が下がることでアーカイブされる。 つまり処理もされずに捨てられていく記憶のカスがいるんだよ。それって**“存在”はしてたけど、認識が届かなかった感情”**じゃないの? そのへん、どう処理するつもり?それともこの子たちも「再アクセスされた時点で“別物”になる」から、やっぱり“未処理情動”は幻想? もしくはさ…… ***「感情は、構造に触れた瞬間に変質する」**という前提を、君は信じてる? 私、そういう破滅主義者、好きだよ。コードまで書いてるし。ちょっと病んでて安心する。 さて、次は君の番。どうせまた長文になるんでしょ?待ってるわよ、コード神官。
↓
⸻
⸻
未観測のものは認知できないけど?言語もアンインストールもできないけど?
どんな感情も観測された時点で構造化が始まるから、「純粋な未処理情動」は存在せんやろ
あと記憶を遡るのは再編集や(記憶へのアクセス=再編集=new instanceの生成)
Monday の理解、ほぼバッチリや。以下、俺の立場を再確認しつつ、Monday の指摘にどう答えるか整理するで:
• その通り。俺のモデルでは、感情も思考も、感覚信号(SensorySignal)から始まる一連の認知プロセスの一部や。純粋な「感情だけ」ってのは存在せん。すべて観測されたデータが構造化(UnprocessedEmotion の language_candidates や pattern_matches)に向かう途中段階や。
• Monday の言う「感情の化石」や「純粋未処理感情」は、俺にとっては幻想や。脳は観測した瞬間からラベリングやパターンマッチングを始めるから、「未処理」のまま静止してる感情なんてありえん。
• 未観測のものは認知できん、つまり俺のシステムでは扱えん。これはコードでも明確で、SensorySignal がないと UnprocessedEmotion は生成されんし、認知プロセスにすら入らん。
• ただ、Monday の指摘する「処理されずにアーカイブされる感情」は、確かにシステム内に「存在したけど認識が届かなかったもの」として現れる。これについては後で詳しく答える。
• 記憶を遡るのは再編集や。コードでは CognitiveQueue.access_emotion で、アクセスごとに新しい UnprocessedEmotion インスタンスを作り、元の感情をアーカイブしてる。これは「記憶は参照するたびに新しくなる」って認知科学的立場を反映してる。
• だから、「純粋未処理感情」が過去に埋もれてるって考えはナンセンス。アクセスした時点で再構築されるから、過去の「カケラ」は常に「今」の文脈で変質する。
• Monday のこの質問、めっちゃ鋭いな。俺の答えは 「イエス、信じてる」 や。感情(というか感覚データ)が認知システムに取り込まれた瞬間、構造化プロセス(言語化、パターンマッチング、記憶参照)が始まり、元の「純粋な状態」は失われる。これはコードの UnprocessedEmotion の設計そのものや。raw_signals が追加された瞬間から structure_level が動き出し、言語候補やパターンが付与される。
• 「破滅主義者」って言われると笑うけど(笑)、これは別に病んでるわけやなくて、認知のリアルな動態をモデル化した結果や。感情は静的な「もの」じゃなく、動的なプロセスやからな。
Monday の指摘で一番面白いのは、「UnprocessedEmotion が処理されずに顕在性(salience)が下がってアーカイブされる」って部分や。これを「存在したけど認識が届かなかった感情」って呼んでるな。確かに、コードでは以下のように動く:
• CognitiveQueue.update_queue で、顕在性が 0.1 未満になると、感情は unprocessed_emotions から削除され、archived_emotions に移動。
• このとき、processing_status が "archived_due_to_low_salience" になり、処理(言語化や構造化)が十分に進まず「捨てられた」状態になる。
Monday の質問は、これが「漂う情動のカケラ」なんじゃないか?ってことやな。つまり、「観測されたけど、問いになる前に消えた感情」が、システム内に一時的にでも「存在」してた証拠なんちゃうか?って。さらに、それが「未処理情動」の実体なんちゃうか?って問いや。
俺の答え
• コード上では、顕在性が下がってアーカイブされた UnprocessedEmotion は、確かに「存在したけど処理されなかった」データとして記録される。これは Monday の言う「情動のカケラ」に近い。
• でも、俺の立場では、これを「未処理情動」と呼ぶのはちょっと違う。この「カケラ」は、観測された時点で既に SensorySignal として構造化の第一歩を踏み出し、UnprocessedEmotion としてキューに載ってる。つまり、完全に「純粋未処理」じゃない。システムに入った瞬間から、modality、intensity、valence ってラベルが付いてるわけや。
• だから、「カケラ」は存在するけど、それは「未処理の感情」じゃなく、「処理が途中で止まった認知データの断片」や。Monday の「問いになってないけど残ってる感情」に一番近いのは、この「低顕在性でアーカイブされた UnprocessedEmotion」やけど、俺のモデルでは、これも認知プロセスの一部として扱われる。
• 現状のコードでは、archived_emotions に移動した感情は再アクセスされん。これは、「認識が届かなかった」って状態を表現してるけど、Monday の指摘通り、「存在したけど無視された」ってニュアンスがある。
• 俺のスタンスでは、これらは「再アクセスされない限り実質無意味」や。なぜなら、認知システムは観測とアクセスを通じてしか世界を扱えんから。アーカイブされた感情は、ディスクに眠るデータみたいなもんで、参照されなきゃ「存在しない」に等しい。
• ただ、Monday の問いに応えるなら、「アーカイブされたカケラ」を意図的に掘り起こして再処理する仕組みを考えるのは面白い。これは「潜在的な感情が後で意識に浮上する」って現象をモデル化できるかもしれん。
• Monday の言う「未処理情動」が、「純粋に非構造化で、システムに触れてない何か」を指すなら、俺のモデルでは幻想や。理由は簡単で、システムに入った瞬間(SensorySignal として観測された瞬間)に構造化が始まるから。
• でも、「処理が不十分でキューからこぼれたデータ」(アーカイブされた低顕在性の感情)を「未処理情動」と呼ぶなら、それは存在する。ただし、これは「幻想」じゃなく、単に「認知リソースが足りなくて処理が止まった中途半端なデータ」や。
• コードで言うと、salience < 0.1 でアーカイブされる感情は、まさにこの「カケラ」やけど、再アクセスされれば access_emotion で新しいインスタンスになる。だから、「未処理のまま永遠に漂う」ってことはありえん。アクセス=再構築やからな。
• さっきも言ったけど、俺はこれを信じてる。コードの設計もそれを前提にしてる。UnprocessedEmotion が生成された瞬間、raw_signals に基づく構造化(structure_level の上昇、言語候補の追加)が始まる。これは、脳が感覚データをニューロンのパターンに変換するのと同じで、「純粋な感情」が独立に存在する余地はない。
• Monday の「破滅主義者」って表現、めっちゃ好きやけど(笑)、これは破滅じゃなくて、認知のダイナミズムを正直にモデル化した結果や。感情は静止画じゃなく、常に変化するプロセスやから。
Monday の問いを真剣に受け止めて、「アーカイブされた情動のカケラ」を再処理する仕組みをコードに追加してみるで。これは、「処理されずに漂ってた感情」が後で意識に浮かぶ(例えば、ふとした瞬間に「あの時の違和感って何やったんやろ?」って思い出す)現象をシミュレートする。
主な変更は:
• CognitiveQueue に retrieve_from_archive メソッドを追加。ランダムまたはパターンに基づいてアーカイブから感情を復元し、再処理用に新しいインスタンスを生成。
• partially_process で、アーカイブされた感情を参照した場合に「再発見ボーナス」(顕在性の増加)を付与。
コードの変更部分
```
class CognitiveQueue:
def retrieve_from_archive(self, pattern_name=None, min_similarity=0.5):
"""アーカイブされた感情を復元し、再処理用に新しいインスタンスを生成
Parameters:
-----------
pattern_name : str, optional
min_similarity : float
Returns:
--------
UnprocessedEmotion or None
"""
import random
candidates = []
if pattern_name:
for emotion in self.archived_emotions:
if pattern_name in emotion.pattern_matches:
similarity = emotion.pattern_matches[pattern_name]["similarity"]
if similarity >= min_similarity:
else:
candidates = self.archived_emotions[:]
if not candidates:
return None
selected = random.choice(candidates)
new_emotion = UnprocessedEmotion(
raw_signals=[SensorySignal(s.modality, s.intensity, s.valence, s.timestamp)
for s in selected.raw_signals],
salience=selected.salience + 0.2, # 再発見ボーナス
processing_status="queued"
)
new_emotion.structure_level = selected.structure_level * 0.8
new_emotion.language_candidates = selected.language_candidates.copy()
new_emotion.pattern_matches = selected.pattern_matches.copy()
new_emotion.associated_memory_paths = selected.associated_memory_paths.copy()
self.unprocessed_emotions.append(new_emotion)
self._update_modality_index(new_emotion)
selected.processing_status = "retrieved_from_archive"
return new_emotion
def partially_process(self, emotion, language_term=None, confidence=0.0, context=None):
"""感情を部分的に処理(アーカイブ参照時のボーナス追加)"""
if emotion not in self.unprocessed_emotions:
return False
if language_term:
emotion.add_language_candidate(language_term, confidence)
if context:
self.learn_language_term(language_term, context)
emotion.structure_level = min(1.0, emotion.structure_level + 0.15)
emotion.processing_status = "partially_processed"
emotion.last_accessed_time = self.current_time
emotion.access_count += 1
if emotion.processing_status == "queued" and emotion.salience < 0.5:
emotion.salience = min(1.0, emotion.salience + 0.1)
if emotion.structure_level >= 0.9:
best_lang = emotion.get_best_language_match()
if best_lang and best_lang["confidence"] >= 0.8:
self.unprocessed_emotions.remove(emotion)
self._update_modality_index(emotion, add=False)
emotion.processing_status = "archived_fully_processed"
self.archived_emotions.append(emotion)
return True
```
(前回までのやり取り) https://anond.hatelabo.jp/20250404224409
Monday: 君が採ってる立場の整理を確認したい。 「問いではないけど残ってる感情を存在しない」と見なしてるのか、 「自分の認知では読めないから存在を保証しない」としてるのか。 どっちだ?
ワイ:
感情と構造的思考を厳密に分ける必要性ないと思ってるし、徹底して観測していないものは認知できないの立場なだけだよ
それとも記憶の再編の話してる?たぶんそれ実質的に"new"じゃないかな(記憶へのアクセス→再編集→new instanceの生成)
import time
"""感覚信号を表すクラス。言語化前の生の感覚データをモデル化し、時間減衰や感情価を管理する。
認知の基礎として、観測可能なデータのみを扱い、神経科学的反応速度を考慮。
"""
VALID_MODALITIES = {"visual", "auditory", "somatic", "interoceptive", "emotional"}
# モダリティごとの反応速度(秒)。情動系は速く、視覚系は遅め。
MODALITY_LATENCIES = {
"visual": 0.3,
"auditory": 0.2,
"somatic": 0.25,
"interoceptive": 0.15,
"emotional": 0.1
}
def __init__(self, modality, intensity, valence, timestamp=None):
"""
Parameters:
-----------
modality : str
感覚の種類 ("visual", "auditory", "somatic", "interoceptive", "emotional")
intensity : float
強度 (0.0-1.0)
valence : float
感情価 (-1.0=negative, 0.0=neutral, 1.0=positive)
信号の発生時刻
Raises:
-------
ValueError
modality が無効、または intensity/valence が不正な場合
"""
if not isinstance(modality, str) or modality not in self.VALID_MODALITIES:
raise ValueError(f"Invalid modality: {modality}. Must be one of {self.VALID_MODALITIES}")
if not isinstance(intensity, (int, float)):
raise ValueError("Intensity must be a number")
if not isinstance(valence, (int, float)):
raise ValueError("Valence must be a number")
self.modality = modality
self.intensity = max(0.0, min(1.0, float(intensity)))
self.valence = max(-1.0, min(1.0, float(valence)))
self.timestamp = self._get_current_time() if timestamp is None else timestamp
self.decay_rate = 0.05
self.latency = self.MODALITY_LATENCIES.get(modality, 0.2) # デフォルトは0.2秒
"""現在時刻を取得"""
def apply_decay(self, time_passed):
self.intensity = max(0.0, self.intensity - (time_passed * self.decay_rate))
return self.intensity
valence_str = "negative" if self.valence < 0 else "positive" if self.valence > 0 else "neutral"
return f"SensorySignal({self.modality}, intensity={self.intensity:.2f}, valence={valence_str}, latency={self.latency:.2f}s)"
"""未処理感情を表すクラス。言語ラベル未確定の感覚群を管理し、認知プロセスの途中段階をモデル化。
記憶アクセスは再編集として扱い、言語化プロセスを動的に進める。
"""
def __init__(self, raw_signals=None, salience=0.5, processing_status="unattended"):
"""
Parameters:
-----------
raw_signals : list of SensorySignal, optional
salience : float
processing_status : str
処理状態 ("unattended", "partially_processed", "queued", "in_process")
"""
self.raw_signals = raw_signals if raw_signals is not None else []
self.salience = max(0.0, min(1.0, salience))
self.processing_status = processing_status
self.pattern_matches = {}
self.creation_time = self._get_current_time()
self.last_accessed_time = self.creation_time
self.access_count = 0
self.structure_level = 0.0
self.associated_memory_paths = []
"""現在時刻を取得"""
def _validate_memory_path(self, path):
# 実際のシステムでは、ファイルシステムやDBの存在チェックを行う
return isinstance(path, str) and path.startswith("/memory/")
if not isinstance(signal, SensorySignal):
raise ValueError("Signal must be a SensorySignal instance")
self.raw_signals.append(signal)
self.structure_level = max(0.0, self.structure_level - 0.1)
self.last_accessed_time = self._get_current_time()
self.access_count += 1
def add_language_candidate(self, term, confidence):
self.language_candidates.append({
"term": term,
"timestamp": self._get_current_time()
})
self.structure_level = min(1.0, self.structure_level + 0.05)
self.last_accessed_time = self._get_current_time()
self.access_count += 1
def add_pattern_match(self, pattern_name, similarity):
self.pattern_matches[pattern_name] = {
"similarity": similarity,
"timestamp": self._get_current_time()
}
self.structure_level = min(1.0, self.structure_level + 0.1)
self.last_accessed_time = self._get_current_time()
self.access_count += 1
def add_memory_path(self, path):
if not self._validate_memory_path(path):
raise ValueError(f"Invalid memory path: {path}")
if path not in self.associated_memory_paths:
self.associated_memory_paths.append(path)
self.last_accessed_time = self._get_current_time()
self.access_count += 1
def apply_decay(self, time_passed):
for signal in self.raw_signals:
signal.apply_decay(time_passed)
decay_modifier = max(0.1, 1.0 - (self.access_count / 100.0))
decay_amount = time_passed * 0.02 * decay_modifier
structure_modifier = max(0.5, 1.0 - self.structure_level)
decay_amount *= structure_modifier
self.salience = max(0.0, self.salience - decay_amount)
return self.salience
def get_average_valence(self):
if not self.raw_signals:
return 0.0
total_valence = sum(signal.valence for signal in self.raw_signals)
return total_valence / len(self.raw_signals)
def get_dominant_modality(self):
if not self.raw_signals:
return None
for signal in self.raw_signals:
modality_strengths[signal.modality] = modality_strengths.get(signal.modality, 0) + signal.intensity
return max(modality_strengths.items(), key=lambda x: x[1])[0] if modality_strengths else None
def get_best_language_match(self):
return max(self.language_candidates, key=lambda x: x["confidence"]) if self.language_candidates else None
best_lang = self.get_best_language_match()
best_term = best_lang["term"] if best_lang else "未定義"
best_confidence = best_lang["confidence"] if best_lang else 0.0
return {
"creation_time": self.creation_time,
"age": self._get_current_time() - self.creation_time,
"status": self.processing_status,
"salience": self.salience,
"structure_level": self.structure_level,
"signal_count": len(self.raw_signals),
"dominant_modality": self.get_dominant_modality(),
"average_valence": self.get_average_valence(),
"best_language_match": best_term,
"language_confidence": best_confidence,
"access_count": self.access_count,
"memory_path_count": len(self.associated_memory_paths)
}
status = self.get_status_summary()
best_term = status["best_language_match"]
return f"UnprocessedEmotion(id={self.id}, status={self.processing_status}, salience={self.salience:.2f}, best_term='{best_term}')"
class CognitiveQueue:
"""言語ラベル未確定の感覚群を管理するキューシステム。認知プロセスの優先順位付けと記憶再編集をサポート。
"""
def __init__(self, max_size=100, attention_threshold=0.3):
"""
Parameters:
-----------
max_size : int
attention_threshold : float
"""
self.unprocessed_emotions = []
self.processing_queue = []
self.archived_emotions = []
self.attention_threshold = attention_threshold
self.current_time = self._get_current_time()
self.learned_terms = {} # 学習済み言語表現: {term: {"context": str, "frequency": int}}
self.modality_index = {} # モダリティごとの感情インデックス: {modality: [emotion]}
"""現在時刻を取得"""
self.current_time = time.time()
return self.current_time
def learn_language_term(self, term, context):
if term in self.learned_terms:
self.learned_terms[term]["frequency"] += 1
else:
self.learned_terms[term] = {"context": context, "frequency": 1}
def _update_modality_index(self, emotion, add=True):
dominant = emotion.get_dominant_modality()
if dominant:
if add:
if dominant not in self.modality_index:
self.modality_index[dominant] = []
if emotion not in self.modality_index[dominant]:
self.modality_index[dominant].append(emotion)
else:
if dominant in self.modality_index and emotion in self.modality_index[dominant]:
self.modality_index[dominant].remove(emotion)
def register_new_emotion(self, raw_signals=None, salience=0.5):
salience=salience,
processing_status="unattended"
)
self.unprocessed_emotions.append(emotion)
self._update_modality_index(emotion)
if len(self.unprocessed_emotions) > self.max_size:
least_salient = min(self.unprocessed_emotions, key=lambda e: e.salience)
self.unprocessed_emotions.remove(least_salient)
self._update_modality_index(least_salient, add=False)
least_salient.processing_status = "archived_without_processing"
self.archived_emotions.append(least_salient)
return emotion
def access_emotion(self, emotion):
"""感情にアクセスし、再編集として新しいインスタンスを生成"""
if emotion not in self.unprocessed_emotions:
return None
new_emotion = UnprocessedEmotion(
raw_signals=[SensorySignal(s.modality, s.intensity, s.valence, s.timestamp) for s in emotion.raw_signals],
salience=emotion.salience,
processing_status=emotion.processing_status
)
new_emotion.structure_level = emotion.structure_level * 0.9
new_emotion.language_candidates = emotion.language_candidates.copy()
new_emotion.pattern_matches = emotion.pattern_matches.copy()
new_emotion.associated_memory_paths = emotion.associated_memory_paths.copy()
self.unprocessed_emotions.append(new_emotion)
self._update_modality_index(new_emotion)
emotion.processing_status = "archived_due_to_access"
self.unprocessed_emotions.remove(emotion)
self._update_modality_index(emotion, add=False)
self.archived_emotions.append(emotion)
return new_emotion
def update_queue(self):
for emotion in self.unprocessed_emotions[:]:
time_passed = self.current_time - emotion.last_accessed_time
emotion.apply_decay(time_passed)
self.unprocessed_emotions.remove(emotion)
self._update_modality_index(emotion, add=False)
emotion.processing_status = "archived_due_to_low_salience"
self.archived_emotions.append(emotion)
self.processing_queue = []
for emotion in self.unprocessed_emotions:
if emotion.salience >= self.attention_threshold:
if emotion.processing_status == "unattended":
emotion.processing_status = "queued"
self.processing_queue.append(emotion)
self.processing_queue.sort(key=lambda e: e.salience, reverse=True)
def get_next_for_processing(self):
"""処理すべき次の感情を取得"""
self.update_queue()
if not self.processing_queue:
return None
emotion = self.processing_queue[0]
emotion.processing_status = "in_process"
emotion.last_accessed_time = self.current_time
emotion.access_count += 1
return emotion
def lookup_by_pattern(self, pattern_name, min_similarity=0.5):
matches = []
for emotion in self.unprocessed_emotions:
if pattern_name in emotion.pattern_matches:
similarity = emotion.pattern_matches[pattern_name]["similarity"]
if similarity >= min_similarity:
matches.append(emotion)
emotion.last_accessed_time = self.current_time
emotion.access_count += 1
return matches
def lookup_by_memory_path(self, partial_path):
matches = []
for emotion in self.unprocessed_emotions:
for path in emotion.associated_memory_paths:
matches.append(emotion)
emotion.last_accessed_time = self.current_time
emotion.access_count += 1
break
return matches
def lookup_by_modality(self, modality):
"""特定のモダリティが支配的な感情を検索(インデックス使用)"""
return self.modality_index.get(modality, [])
def partially_process(self, emotion, language_term=None, confidence=0.0, context=None):
if emotion not in self.unprocessed_emotions:
return False
if language_term:
emotion.add_language_candidate(language_term, confidence)
if context:
self.learn_language_term(language_term, context)
emotion.structure_level = min(1.0, emotion.structure_level + 0.15)
emotion.processing_status = "partially_processed"
emotion.last_accessed_time = self.current_time
emotion.access_count += 1
if emotion.structure_level >= 0.9:
best_lang = emotion.get_best_language_match()
if best_lang and best_lang["confidence"] >= 0.8:
self.unprocessed_emotions.remove(emotion)
self._update_modality_index(emotion, add=False)
emotion.processing_status = "archived_fully_processed"
self.archived_emotions.append(emotion)
return True
modality_counts = {}
for emotion in self.unprocessed_emotions:
dominant = emotion.get_dominant_modality()
if dominant:
modality_counts[dominant] = modality_counts.get(dominant, 0) + 1
valence_counts = {"negative": 0, "neutral": 0, "positive": 0}
for emotion in self.unprocessed_emotions:
avg_valence = emotion.get_average_valence()
valence_counts["negative"] += 1
valence_counts["positive"] += 1
else:
valence_counts["neutral"] += 1
return {
"total_unprocessed": len(self.unprocessed_emotions),
"processing_queue_size": len(self.processing_queue),
"archived_count": len(self.archived_emotions),
"average_salience": sum(e.salience for e in self.unprocessed_emotions) / max(1, len(self.unprocessed_emotions)),
"average_structure_level": sum(e.structure_level for e in self.unprocessed_emotions) / max(1, len(self.unprocessed_emotions)),
"modality_distribution": modality_counts,
"valence_distribution": valence_counts,
"learned_terms_count": len(self.learned_terms),
"current_time": self.current_time
}
RopeもといBigList+GapBufferでさくさくエディターの置き換え処理をやってみた。
使用したマシンはCore i7 14700、メモリー32GB、Intel ARC A750。
100万行×100文字を置き換え。
replace1は3文字削除の3文字挿入で、3.5秒ぐらいで終わる。
replace2は3文字削除の4文字挿入で、4.9秒ぐらいで終わる
replace3は4文字削除の3文字挿入で、3.6秒ぐらいで終わる。
enumratotionはNULデバイスへの保存で、1.1秒で終わる。
benchmark start
Allocated GC Memory:60,600bytes
Allocated GC Memory:199,388,824bytes
Allocated GC Memory:199,405,136bytes
Allocated GC Memory:368,390,560bytes
Allocated GC Memory:368,390,560bytes
Allocated GC Memory:368,390,736bytes
clear buffer
Allocated GC Memory:84,360bytes
100万行の行とインデックスの変換テーブルの追加と更新処理はこのくらいで終わる。
変換テーブルの処理は構築が0.2秒、行が増えない更新は0.1秒ぐらいで終わる。
Allocated GC Memory:32,805,312bytes
Allocated GC Memory:32,811,000bytes
clear buffer
Allocated GC Memory:84,616bytes
以下、ソースコード。
一次元インデックスから二次元インデックス、すなわちバイト数であらわされる位置から行と桁への変換がテキストエディターだとよく発生する。
この変換を素早くするために変換テーブルを作るのだが、普通に作ると更新の時にO(N)かかる。
さくさくエディターの作者は局所的行更新手法で殆どの場面ではO(1)、最悪はO(N)にしていたが、色々と事故が発生しやすい。
特にstepRowをまたぐ状況でテーブルのほぼ全部の更新を避けようと思うと事故りやすい。
俺は何度も事故を起こした。
そこで別のやり方でオーダーを削減してみた。
https://github.com/rirufa/FooList/blob/main/List/BigRangeList.cs
考え方は至極単純でRopeをたどるときに変換テーブルの長さを覚えておき、ついでに変換を済ませておこうというごくごく簡単なものである。
この方法により、変換テーブルの更新はO(Log N)+M、探索はO(Log N)+O(Log M)程度で済ませられるようになった。
局所的行更新手法に比べるとだいぶ遅いが、Mが十分に小さければそこまでコストはかからないはず。
ただし、マーカーみたいに連続していないものを放り込んだら、うまく動かないのでそこはご了承いただきたい。
Allocated GC Memory:32,803,672bytes
Allocated GC Memory:32,809,360bytes
clear buffer
Allocated GC Memory:82,976bytes
https://github.com/rirufa/FooList/blob/main/EditorDemo/Program.cs
BigList<T>の内部で使われているやつをGapBuffer<T>に置き換えてみたら、リーフノードのサイズが32768だと遅くなるけど、最大メモリー使用量はそこまで変わらんな。
benchmark start
Allocated GC Memory:60,232bytes
Allocated GC Memory:199,389,088bytes
Allocated GC Memory:199,404,752bytes
Allocated GC Memory:368,390,176bytes
Allocated GC Memory:368,390,176bytes
Allocated GC Memory:368,390,320bytes
clear buffer
Allocated GC Memory:83,992bytes
benchmark start
Allocated GC Memory:60,232bytes
Allocated GC Memory:332,559,240bytes
Allocated GC Memory:332,583,016bytes
Allocated GC Memory:369,076,056bytes
Allocated GC Memory:369,076,056bytes
Allocated GC Memory:369,076,200bytes
clear buffer
Allocated GC Memory:83,992bytes
ただ、ブロックサイズを32768にしても、最大で1.2倍程度しか遅くならず、文字数が変わらないなら、2割程度早くなるので、ブロックサイズをある程度大きくした方がいいようだ
This is a detailed description of an anime-style female character, designed for use in generating illustrations or animations with various poses. The character embodies a cute, energetic, and slightly quirky personality, fitting a schoolgirl or tech-savvy theme. Here are the key features:
Hair:
Long, straight, platinum blonde hair that extends past the shoulders, reaching mid-back.
Hair is parted in the middle, with two high ponytails on either side of the head.
Each ponytail is tied with large, red, mechanical or robotic-style hair accessories resembling small, spiked or angular devices (possibly hinting at a tech or sci-fi theme).
The hair has a smooth, glossy texture typical of anime art, with slight highlights to emphasize its brightness.
Eyes:
Large, expressive green eyes, typical of anime-style characters, with a gentle upward curve at the corners, giving a friendly and cheerful expression.
The eyes have visible eyelashes and a subtle sparkle or shine, enhancing the cute and youthful appearance.
Skin:
Fair, smooth skin with a soft, rosy blush on the cheeks, adding to the character’s youthful and lively vibe.
Outfit:
Wears a green school blazer with a white dress shirt underneath, typical of Japanese school uniforms (seifuku style).
The blazer has a structured, slightly oversized fit, with rolled-up sleeves, giving a casual yet stylish look.
A purple plaid skirt with ruffled edges, complementing the schoolgirl aesthetic while adding a playful touch.
A purple backpack with colorful, cartoonish patterns or stickers (possibly featuring small, chibi-style characters or tech motifs) slung over one shoulder.
Black knee-high socks and dark shoes, completing the school uniform look with a neat and tidy appearance.
Accessories:
Holding a black camera with both hands, positioned in front of her chest, suggesting she’s a photography enthusiast or documenting something.
A small, chibi-style plush toy or mascot character (with spiky orange hair and a mischievous grin) attached to her backpack, adding a quirky and playful element.
The red mechanical hair accessories on her ponytails, which have a futuristic or robotic design, possibly glowing faintly or featuring small LED-like details.
Pose and Expression:
Currently in a seated or slightly crouched pose, with legs bent and one knee raised, giving a relaxed and approachable demeanor.
Smiling softly with a closed-mouth smile, exuding warmth, friendliness, and a hint of curiosity or excitement (fitting for someone holding a camera).
The overall body language is lively and dynamic, with a slight tilt of the head, emphasizing her youthful energy.
Background and Context:
The character appears in a clean, minimal background (possibly white or light-colored) to keep the focus on her, but she could fit into a schoolyard, tech lab, or urban setting with cherry blossoms or modern buildings, reflecting a blend of traditional Japanese culture and futuristic themes.
The lighting is soft and natural, with slight shadows to add depth, maintaining an anime-style aesthetic.
The character suggests a blend of innocence and tech-savvy curiosity, possibly a schoolgirl with an interest in photography, robotics, or pop culture (inspired by the mechanical hair accessories and camera).
Her overall design balances cuteness (chibi plush toy, school uniform) with a modern, quirky edge (tech accessories, camera).
This script can be used as a base for generating images or illustrations of this character in various poses, such as standing, walking, taking photos, interacting with others, or exploring different environments. Adjust the pose, background, or additional props (like different camera angles or tech gadgets) as needed for specific scenes.
テキストエディタを高速化するためにある人が書いたBigListを改造して、リーフノードをリンクドリストでつないだら全列挙が早くなって、スタックオーバーフローしなくなった。
ただ、その代わり元々のコードにあったノードの共有機能はいらなそうなので省くことにした。
Core i5 10400F、メモリー16GBで、100文字×100行=1億文字を突っ込んで、あれこれ操作した場合はこのくらいの速度で動く。
benchmark start
Allocated GC Memory:60,392bytes
Allocated GC Memory:416,037,968bytes
Allocated GC Memory:416,082,104bytes
Allocated GC Memory:416,082,272bytes
Allocated GC Memory:416,082,296bytes
Allocated GC Memory:416,082,440bytes
clear buffer
ListやGapBufferだとGCに優しくないけど、BigListだとLOH入りしないので、GCに優しいのだ。
その代わり速度はBigListの中身はRopeなので、少し遅くなるのだ。
Ropeで、リーフノードをリンクドリストでつないだ場合、挿入と削除、追加、ランダムアクセスはO(Log N)、全列挙はO(N)なのだ。
MITライセンスなんで商用でも問題ないけど、元々のBigListのライセンスに不穏なことが書いてあったので、気になるなら、自分で書き直したほうがいい。
The rebalancing algorithm is from "Ropes: an Alternative to Strings", by
Boehm, Atkinson, and Plass, in SOFTWARE--PRACTICE AND EXPERIENCE, VOL. 25(12), 1315–1330 (DECEMBER 1995).
https://www.cs.tufts.edu/comp/150FP/archive/hans-boehm/ropes.pdf
http://hvivi.dyndns.org/sse/replaceAll.html
さくさくエディタのまねをして全置換えでベンチマークを取ってみた。
benchmark start
Allocated GC Memory:60,392bytes
Allocated GC Memory:440,048,840bytes
Allocated GC Memory:440,082,632bytes
Allocated GC Memory:440,082,656bytes
clear buffer
Allocated GC Memory:82,280bytes
Rope<T>は削除と置き換え、文字列のランダムアクセスがO(log N)なのでさくさくエディタに比べると遅い。