Movatterモバイル変換


[0]ホーム

URL:


はてラボはてな匿名ダイアリー
ようこそ ゲスト さんログインユーザー登録

「Print」を含む日記RSS

はてなキーワード:Printとは

次の25件>

2025-10-05

ピケティ理論シミュレーションして思った

インフレ率を考慮しねークソモデルだなって

import pandasaspddef piketty_r_growth_simulation(r, g, Y_initial, K_initial, N_periods):    """ピケティの r> g理論に基づく経済シミュレーション経済規模 (Y) は g で成長。資本 (K) は r で成長 (ご要望の K_t+1 = K_t * (1 + r) に基づく)。資本所得 (R) は K の成長ではなく、Y の配分を決めるための r * K として計算。        :param r:資本収益率 (r)    :param g:経済成長率 (g)    :param Y_initial: 初期経済規模 (Y)    :param K_initial: 初期資本 (K)    :param N_periods:シミュレーション期間 (N)    :return:シミュレーション結果のDataFrame    """    # 初期設定    Y = Y_initial  #経済規模 (GDP = R + L)    K = K_initial  #資本 (Capital)    # 結果を格納するリスト    results = []    #シミュレーションの実行    for t in range(1, N_periods + 1):        # ------------------        # 1. 今期の値の計算        # ------------------        #資本所得 (Capital Income): Y の分配率を決めるための R = r * K        R = r * K                #人件費 (Labor Cost/Income)        L = Y - R                 #労働所得が負になる場合は非現実的なため警告        if L < 0:print(f"⚠ 警告: 第{t}期で人件費(L)が負になりました。資本所得 R が経済規模 Y を超えています。")            break         # 各種比率計算        capital_to_Y = K / Y          #資本 ÷経済規模 (K/Y: β)        labor_to_Y = L / Y            #人件費 ÷経済規模 (L/Y)        labor_to_capital = L / K      #人件費 ÷資本 (L/K)        # 結果を記録        results.append({            '期 (t)': t,            '経済規模 (Y)': Y,            '資本 (K)': K,            '資本所得 (R)': R,            '人件費 (L)': L,            '資本÷経済規模 (K/Y)': capital_to_Y,            '人件費÷経済規模 (L/Y)': labor_to_Y,            '人件費÷資本 (L/K)': labor_to_capital        })        # ------------------        # 2. 次期の値への更新 (r> g のメカニズムを直接適用)        # ------------------                #経済規模 (Y) の更新:経済成長率 g に基づく        Y_next = Y * (1 + g)        #資本 (K) の更新:資本収益率 r に基づく (ご要望の K_t+1 = K_t * (1 + r))        K_next = K * (1 + r)        # 値の更新        Y = Y_next        K = K_next    #データフレームに変換    df_results =pd.DataFrame(results)    return df_results# -----------------------------------------------------------# 📊シミュレーションの実行例: r> g のケース (格差拡大を想定)# -----------------------------------------------------------#パラメータ設定r_value = 0.1       #資本収益率g_value = 0.05       #経済成長率Y_0 = 1000           # 初期経済規模K_0 = 500           # 初期資本N = 50               # 期間 #シミュレーションの実行df_r_growth = piketty_r_growth_simulation(    r=r_value,    g=g_value,    Y_initial=Y_0,    K_initial=K_0,    N_periods=N)df_r_growth.to_csv("data.csv",index=False)

Permalink |記事への反応(2) | 08:39

このエントリーをはてなブックマークに追加ツイートシェア

2025-09-27

anond:20250927213945

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop Formatit

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick Eraseit

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

Technologic Technologic

Technologic Technologic

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

__________________________

TouchIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

__________________________

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

Technologic Technologic

Technologic Technologic

Technologic Technologic

Technologic Technologic

Permalink |記事への反応(0) | 21:47

このエントリーをはてなブックマークに追加ツイートシェア

2025-09-01

完全パングラムをChatGPTに作らせる

日本語の完全パングラムを作ってください。できたら、最後プログラムで完全パングラムであることを確認してください

ChatGPT

はい作りました

ひらがな46文字」を各1回ずつ用いた完全パングラムです:

あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをん

下に検証プログラムPython)を実行し、各文字が1回ずつ現れることを確認しました。

#日本語ひらがな46文字の完全パングラム検証しますfrom collections import Counterimport pandasaspdimport re#対象とする文字集合(現代ひらがな46文字:ゐ・ゑは含めない)hiragana46 = list("あいうえお"                  "かきくけこ"                  "さしすせそ"                  "たちつてと"                  "なにぬねの"                  "はひふへほ"                  "まみむめも"                  "やゆよ"                  "らりるれろ"                  "わをん")#提示する完全パングラムひらがな46文字を各1回ずつ)pangram = "あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをん"#ひらがなのみを抽出安全のため)filtered = "".join(re.findall(r"[ぁ-ゖ]", pangram))# 出現回数をカウントcnt = Counter(filtered)#検証ロジックis_perfect = (set(hiragana46) ==set(filtered) and          # 同じ文字集合かall(cnt[ch] == 1 for ch in hiragana46) and    # 各1回ずつかlen(filtered) ==len(hiragana46)              #文字数一致(=46))# 集計表を作成df =pd.DataFrame({    "かな": hiragana46,    "出現回数": [cnt.get(ch, 0) for ch in hiragana46]})from caas_jupyter_tools import display_dataframe_to_userdisplay_dataframe_to_user("ひらがな46文字の出現回数",df)print("パングラム文字列:", pangram)print("総ひらがな数:",len(filtered))print("ユニークひらがな数:",len(set(filtered)))print("完全パングラム判定:", "はい ✅" if is_perfect else "いいえ ❌")

ひらがな数:46

ユニークひらがな数:46

完全パングラム判定:はい

(表で各かなの出現回数も確認できます。)

😠💢💢💢💢💢💢💢

Permalink |記事への反応(0) | 01:30

このエントリーをはてなブックマークに追加ツイートシェア

2025-08-22

dorawii@執筆依頼募集中

昨日一番肝心なファイルなのにURLとみなされる部分が多いことの関係投稿できなかったのでそれを小分けにして書く。

小分けというか例のスパムの影響でNGワードに引っかかっていたようなのでそこだけ書き換えた。

suuportと書いていある部分は元のコードでは当然uが一つ少ないので利用するときはそうすること。

hatena_client.py

fromselenium importwebdriver
fromselenium.webdriver.chrome.options import Options
fromselenium.webdriver.chrome.service import Service
fromwebdriver_manager.chrome importChromeDriverManager # ← 追加
fromselenium.webdriver.common.by importBy
fromselenium.webdriver.suupport.ui importWebDriverWait
fromselenium.webdriver.suupport import expected_conditionsasEC
importtime,json
fromselenium.common.exceptions importTimeoutException

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)


deflogin(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

defadd_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)

returnTrue
except Exceptionas e:
print(f"Bookmark failed: {e}")
returnFalse

def quit(self):
self.driver.quit()

-----BEGINPGP SIGNEDMESSAGE-----
Hash: SHA512

https://anond.hatelabo.jp/20250822131958#
-----BEGINPGP SIGNATURE-----

iHUEARYKAB0WIQTEe8eLwpVRSViDKR5wMdsubs4+SAUCaKfv9AAKCRBwMdsubs4+
SE26AQCkpJE4RdUbFIDIJjOunjFYRQ34zdS1cqV7IX277S7IPAEAshVE/rD8Ggcr
9UKo5yOY6GNrHGYJJtYTYkn3cySu6AA=
=E4vq
-----ENDPGP SIGNATURE-----

Permalink |記事への反応(0) | 13:19

このエントリーをはてなブックマークに追加ツイートシェア

2025-07-28

anond:20250728103414

UNIX哲学の「正常動作時は何もprintしない」という原則ですね。

エラーや警告、またはユーザーが明示的に要求した結果以外は、出力すべきではないとされています

これは、UNIXライクなシステムコマンドラインツール堅牢性とエレガントさに貢献してきた核となる原則です。

Permalink |記事への反応(1) | 11:03

このエントリーをはてなブックマークに追加ツイートシェア

正常動作時は何もprintしない。それがUNIX哲学ってもんよ

Permalink |記事への反応(1) | 10:34

このエントリーをはてなブックマークに追加ツイートシェア

2025-07-14

しゃーない、ワイがかわりに英文スパム投稿してやるやで

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop Formatit

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick Eraseit

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

Technologic Technologic

Technologic Technologic

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

__________________________

TouchIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

__________________________

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

Technologic Technologic

Technologic Technologic

Technologic Technologic

Technologic Technologic

Permalink |記事への反応(0) | 09:31

このエントリーをはてなブックマークに追加ツイートシェア

2025-07-08

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop Formatit

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick Eraseit

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

Technologic Technologic

Technologic Technologic

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

__________________________

TouchIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

__________________________

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

BuyIt UseIt BreakItFixIt TrashItChangeIt Mail UpgradeIt

ChargeItPointItZoomIt PressItSnapIt WorkIt Quick EraseIt

WriteIt CutIt PasteIt SaveIt LoadIt CheckIt QuickRewriteIt

PlugIt PlayIt BurnItRipIt Drag AndDropItZipUnzipIt

LockIt FillItCurlIt FindItViewIt CodeItJam UnlockIt

SurfIt ScrollIt PoseItClickItCrossIt CrackItTwitch UpdateIt

NameIt ReadIt TuneItPrintItScanIt SendItFax RenameIt

TouchIt BringIt PayItWatchIt TurnIt LeaveIt Stop FormatIt

Technologic Technologic

Technologic Technologic

Technologic Technologic

Technologic Technologic

Permalink |記事への反応(0) | 21:59

このエントリーをはてなブックマークに追加ツイートシェア

2025-07-05

🍬資本主義平等なのか飴の配布で考えてみよう🍬

pythonimport randomimport numpyasnpimport matplotlib.pyplotas pltfrom collections importdefaultdict# 飴の配布システムシミュレーションclass CandyDistributionSystem:def __init__(self):        """設計意図: このシステム経済における資源分配の不平等性をモデル化しています特に少数の特権層(Aグループ)が富を集中させ、再分配システムからも不均衡に利益を得る構造問題表現しています。        """        # 各グループの人数設定        self.group_a_count = 8        self.group_b_count = 2498        self.group_c_count = 7494        self.total_participants = self.group_a_count + self.group_b_count + self.group_c_count                # 飴の提出数設定        self.contribution_per_a = 624        self.contribution_per_b = 2        self.contribution_per_c = 1                # 各グループの総貢献計算        self.total_a_contribution = self.group_a_count * self.contribution_per_a        self.total_b_contribution = self.group_b_count * self.contribution_per_b        self.total_c_contribution = self.group_c_count * self.contribution_per_c        self.total_contribution = self.total_a_contribution + self.total_b_contribution + self.total_c_contribution                # 配布用と貯金用の飴の区分        self.distribution_limit =10000        self.savings =max(0, self.total_contribution - self.distribution_limit)                # 結果追跡用の辞書        self.results = {            'A':defaultdict(int),            'B':defaultdict(int),            'C':defaultdict(int)        }def distribute_candies(self, method='original'):        """設計意図: 配布方法選択によって、特権固定化格差拡大がどのように進むかを        示します。'original'メソッド意図的にAグループ優遇するよう設計されています。                Parameters:        -----------        method:str            配布方法 ('original', 'lottery', 'first_come', 'new_condition', 'fair')        """        # Aグループへの確定配布        a_distribution = 625 * self.group_a_count        remaining = self.distribution_limit - a_distribution                # 残りの参加者数        remaining_participants = self.total_participants - self.group_a_count                # Aグループの結果記録        for _ in range(self.group_a_count):            self.results['A'][625] += 1                # 各配布方法によって処理が異なる        if method == 'original':            #オリジナル問題設定通りの配布(5000人に1個ずつ、残りは0個)            lucky_count = remaining  # 5000人が当選                        # B+Cグループの混合リスト作成            bc_participants = [(1, 'B')] * self.group_b_count + [(2, 'C')] * self.group_c_count            random.shuffle(bc_participants)                        #当選者に配布            for i in range(len(bc_participants)):                participant_id,group = bc_participants[i]                if i < lucky_count:                    self.results[group][1] += 1                else:                    self.results[group][0] += 1                            elif method == 'lottery':            #抽選方式(BとCグループから無作為に5000人選出)            bc_participants = [(1, 'B')] * self.group_b_count + [(2, 'C')] * self.group_c_count            winners = random.sample(bc_participants, remaining)                        #当選落選カウント            for _,group in winners:                self.results[group][1] += 1                        #落選者のカウント            self.results['B'][0] = self.group_b_count - self.results['B'][1]            self.results['C'][0] = self.group_c_count - self.results['C'][1]                    elif method == 'first_come':            # 先着順方式アクセス速度による先着順を乱数シミュレート)            #設計意図: 先着順は単なる運の要素を超えて、情報格差技術格差も含む制度設計            bc_participants = [(1, 'B')] * self.group_b_count + [(2, 'C')] * self.group_c_count                        #現実では、情報を早く得られる人や高速インターネット接続を持つ人が有利            # これをシミュレートするため、Bグループわずかなアドバンテージを与える            bc_speeds = []            forid,group in bc_participants:                ifgroup == 'B': speed = random.random() + 0.1  # Bグループに小さなアドバンテージ                else: speed = random.random()                bc_speeds.append((id,group, speed))                        # 速度順にソート            bc_speeds.sort(key=lambda x: x[2], reverse=True)                        #当選者決定            for i in range(len(bc_speeds)):                _,group, _ = bc_speeds[i]                if i < remaining:                    self.results[group][1] += 1                else:                    self.results[group][0] += 1                            elif method == 'new_condition':            # 追加条件方式恣意的な条件を設定)            #設計意図: 新たな条件の設定は往々にして既存特権を温存するように設計される            bc_participants = [(i, 'B', random.random()) for i in range(self.group_b_count)] + \                             [(i, 'C', random.random()) for i in range(self.group_c_count)]                        # Bグループに有利な条件を設定(例:特定知識スキルを持つ人のみ)            # この「条件」は表面上は中立的だが、実際には特定グループに有利になるよう設計def meets_condition(participant):                _,group, rand_val = participant                ifgroup == 'B':                    return rand_val> 0.3  # Bグループには70%の確率合格                else:                    return rand_val> 0.7  # Cグループには30%の確率合格                        # 条件に合致する人を抽出            eligible = [p for p in bc_participants if meets_condition(p)]                        # 条件に合致する人が多すぎる場合抽選            iflen(eligible)> remaining:                winners = random.sample(eligible, remaining)            else:                # 条件に合致する人が足りない場合、全員に配布                winners = eligible                        #当選者をカウント            for _,group, _ in winners:                self.results[group][1] += 1                        #落選者のカウント            self.results['B'][0] = self.group_b_count - self.results['B'][1]            self.results['C'][0] = self.group_c_count - self.results['C'][1]                    elif method == 'fair':            # 公平な再分配方式(貢献度に応じた配布)            #設計意図: この方法は「貯金分」も含めた全ての飴を、各グループの貢献度に応じて分配            # これにより構造的不平等を軽減、結果としてより多くの人が少なくとも損をしない状態になる                        # 全飴(貯金分も含む)を使った配布total_to_distribute = self.total_contribution                        # 各グループの貢献比率計算            a_ratio = self.total_a_contribution / self.total_contribution            b_ratio = self.total_b_contribution / self.total_contribution            c_ratio = self.total_c_contribution / self.total_contribution                        # 各グループへの配布数決定            a_share = int(total_to_distribute * a_ratio)            b_share = int(total_to_distribute * b_ratio)            c_share = int(total_to_distribute * c_ratio)                        # 端数調整            remainder =total_to_distribute - (a_share + b_share + c_share)            if remainder> 0:                # 端数は最も人数の多いCグループに                c_share += remainder                        # Aグループの配布(均等配分)            per_a = a_share // self.group_a_count            self.results['A'][per_a] = self.group_a_count                        # Bグループの配布(均等配分)            per_b = b_share // self.group_b_count            b_remainder = b_share % self.group_b_count                        self.results['B'][per_b] = self.group_b_count - b_remainder            if per_b + 1> 0 and b_remainder> 0:                self.results['B'][per_b + 1] = b_remainder                        # Cグループの配布(均等配分)            per_c = c_share // self.group_c_count            c_remainder = c_share % self.group_c_count                        self.results['C'][per_c] = self.group_c_count - c_remainder            if per_c + 1> 0 and c_remainder> 0:                self.results['C'][per_c + 1] = c_remainderdef calculate_net_gain(self):        """設計意図: この関数は各グループ純利益/損失を計算し、資源分配の公平性定量的評価できるようにします。純利益/損失は個人観点から見た経済的公正性の重要指標です。        """net_gains = {}                # Aグループ純利益計算        a_contribution = self.contribution_per_a        a_distribution = list(self.results['A'].keys())[0]  # 全員が同じ数を受け取る前提net_gains['A'] = a_distribution - a_contribution                # BとCグループ純利益計算(加重平均)        forgroup, contribution_per_person in [('B', self.contribution_per_b), ('C', self.contribution_per_c)]:total_gain = 0            for received, count in self.results[group].items():total_gain += (received - contribution_per_person) * countnet_gains[group] =total_gain / (self.group_b_count ifgroup == 'B' else self.group_c_count)                    returnnet_gainsdef analyze_results(self):        """設計意図: この分析関数は、各グループの分配結果を詳細に調査し、制度設計公平性、貢献度と報酬関係、およびシステムの持続可能性を評価します。政策分析においては、こうした多角的検証重要です。        """        # 各グループ純利益/損失net_gains = self.calculate_net_gain()                # 貢献度分析        contribution_percentage = {            'A': (self.total_a_contribution / self.total_contribution) *100,            'B': (self.total_b_contribution / self.total_contribution) *100,            'C': (self.total_c_contribution / self.total_contribution) *100        }                # 飴を受け取った人の割合        received_percentage = {            'A': sum(count for received, count in self.results['A'].items() if received> 0) / self.group_a_count *100,            'B': sum(count for received, count in self.results['B'].items() if received> 0) / self.group_b_count *100,            'C': sum(count for received, count in self.results['C'].items() if received> 0) / self.group_c_count *100        }                #分析結果の表示print("\n===== 飴の配布システム分析 =====")print(f"総飴数: {self.total_contribution}個 (分配用: {self.distribution_limit}個,貯金: {self.savings}個)")print("\n---グループごとの貢献と結果 ---")        forgroup in ['A', 'B', 'C']:group_size =getattr(self, f"group_{group.lower()}_count")            contribution_per_person =getattr(self, f"contribution_per_{group.lower()}")total_contribution =getattr(self, f"total_{group.lower()}_contribution")print(f"\n{group}グループ ({group_size}人):")print(f"  貢献: 1人あたり{contribution_per_person}個 (総計: {total_contribution}個, 全体の{contribution_percentage[group]:.1f}%)")print(f"  受け取り状況:")                        for received, count in sorted(self.results[group].items()):print(f"    {received}個: {count}人 ({count/group_size*100:.1f}%)")print(f"  飴を受け取った割合: {received_percentage[group]:.1f}%")print(f"純利益/損失: 1人あたり平均 {net_gains[group]:.2f}個")print("\n--- 全体的な公平性分析 ---")print(f"最も得したグループ: {max(net_gains,key=net_gains.get)}グループ (+{max(net_gains.values()):.2f}個/人)")print(f"最も損したグループ: {min(net_gains,key=net_gains.get)}グループ ({min(net_gains.values()):.2f}個/人)")                # 全員に飴が配布されたかどうかall_received =all(sum(count for received, count in self.results[group].items() if received> 0) ==getattr(self, f"group_{group.lower()}_count") forgroup in ['A', 'B', 'C'])print(f"\n前提条件「全員に配布」の充足: {'はい' ifall_received else 'いいえ'}")        if notall_received:total_without = sum(self.results['B'][0] + self.results['C'][0])print(f"  飴を受け取れなかった人数: {total_without}人")                returnnet_gains, contribution_percentage, received_percentagedef visualize_results(self):        """設計意図:データ可視化政策効果や不平等性を直感的に理解するために重要です。        このようなグラフィカル表現によって、各グループ間の格差制度設計問題点を        一目で理解できるようになります。        """        #グラフセットアップfig, axes = plt.subplots(2, 2,figsize=(14,10))                # 1. 貢献度のグラフ        contributions = [self.total_a_contribution, self.total_b_contribution, self.total_c_contribution]        axes[0, 0].bar(['Aグループ', 'Bグループ', 'Cグループ'], contributions)        axes[0, 0].set_title('グループごとの総貢献飴数')        axes[0, 0].set_ylabel('飴の数')                # 貢献度の割合アノテーションとして追加total = sum(contributions)        for i, v in enumerate(contributions):            percentage = v /total *100            axes[0, 0].text(i, v +100, f'{percentage:.1f}%', ha='center')                # 2. 1人あたりの貢献度と受け取り数の比較group_names = ['Aグループ', 'Bグループ', 'Cグループ']        contribution_per_person = [self.contribution_per_a, self.contribution_per_b, self.contribution_per_c]                # 各グループの平均受け取り数を計算        received_per_person = []        forgroup, letter inzip(group_names, ['A', 'B', 'C']):total_received = sum(received * count for received, count in self.results[letter].items())group_size =getattr(self, f"group_{letter.lower()}_count")            received_per_person.append(total_received /group_size)                x =np.arange(len(group_names))        width = 0.35                axes[0, 1].bar(x - width/2, contribution_per_person, width, label='提出')        axes[0, 1].bar(x + width/2, received_per_person, width, label='受け取り')                #純利益/損失をアノテーションとして追加        for i in range(len(group_names)):net = received_per_person[i] - contribution_per_person[i]color = 'green' ifnet>= 0 else 'red'            axes[0, 1].text(i,max(received_per_person[i], contribution_per_person[i]) + 5,                         f'{"+" ifnet>= 0 else ""}{net:.1f}', ha='center',color=color)                axes[0, 1].set_title('1人あたりの提出・受け取り飴数比較')        axes[0, 1].set_xticks(x)        axes[0, 1].set_xticklabels(group_names)        axes[0, 1].set_ylabel('飴の数')        axes[0, 1].legend()                # 3. 各グループの受け取り状況の分布        # 各グループの受け取り状況を積み上げ棒グラフ表現group_sizes = [self.group_a_count, self.group_b_count, self.group_c_count]        received_counts = []        not_received_counts = []                for letter, size inzip(['A', 'B', 'C'],group_sizes):            received = sum(count for received, count in self.results[letter].items() if received> 0)            received_counts.append(received)            not_received_counts.append(size - received)                axes[1, 0].bar(group_names, received_counts, label='飴を受け取った人数')        axes[1, 0].bar(group_names, not_received_counts, bottom=received_counts, label='飴を受け取れなかった人数')                #割合アノテーションとして追加        for i in range(len(group_names)):            ifgroup_sizes[i]> 0:                percentage = received_counts[i] /group_sizes[i] *100                axes[1, 0].text(i, received_counts[i] / 2, f'{percentage:.1f}%', ha='center')                axes[1, 0].set_title('グループごとの飴受け取り状況')        axes[1, 0].set_ylabel('人数')        axes[1, 0].legend()                # 4. 貢献度vs報酬の分配公平性        # 貢献度と最終的な飴の配分の比較円グラフ表現total_contribution = self.total_contribution        contribution_shares = [self.total_a_contribution /total_contribution,                             self.total_b_contribution /total_contribution,                             self.total_c_contribution /total_contribution]                # 実際の配分シェア計算        distribution_shares = []        for letter in ['A', 'B', 'C']:total_received = sum(received * count for received, count in self.results[letter].items())            distribution_shares.append(total_received / self.distribution_limit)                # 2つの円グラフを並べて表示        ax4_1 = axes[1, 1].inset_axes([0, 0, 0.45, 1])        ax4_2 = axes[1, 1].inset_axes([0.55, 0, 0.45, 1])                ax4_1.pie(contribution_shares, labels=group_names, autopct='%1.1f%%')        ax4_1.set_title('飴の貢献度割合')                ax4_2.pie(distribution_shares, labels=group_names, autopct='%1.1f%%')        ax4_2.set_title('飴の配分割合')                axes[1, 1].axis('off')                plt.tight_layout()        plt.show()# 飴の配布システムシミュレートcandy_system = CandyDistributionSystem()#オリジナルの配布方法を実行print("\n=====オリジナルの配布方法 =====")candy_system.distribute_candies(method='original')original_results = candy_system.analyze_results()candy_system.visualize_results()# 公平な配布方法実験print("\n\n===== 公平な配布方法シミュレーション =====")fair_system = CandyDistributionSystem()fair_system.distribute_candies(method='fair')fair_results = fair_system.analyze_results()fair_system.visualize_results()# 公平な配布と元の配布の比較print("\n\n===== 配布方法比較 =====")print("オリジナル方式と公平方式純利益/損失差:")net_diff = {}forgroup in ['A', 'B', 'C']:original_net =original_results[0][group]    fair_net = fair_results[0][group]diff = fair_net -original_netnet_diff[group] =diffprint(f"{group}グループ: {'+'  ifdiff> 0 else ''}{diff:.2f}個/人")print("\n結論:")ifnet_diff['A'] < 0 andnet_diff['B']> 0 andnet_diff['C']> 0:print("公平な再分配により、Aグループ特権が減少し、BとCグループの状況が改善されます。")print("これは構造的不平等の緩和に効果的です。")elifnet_diff['A']> 0:print("興味深いことに、公平な再分配ではAグループさえも利益を得られます。")print("これは、現行システム特定グループだけでなく全体の非効率性につながっていることを示唆しています。")

anond:20250705100755anond:20250705112807

Permalink |記事への反応(1) | 10:24

このエントリーをはてなブックマークに追加ツイートシェア

2025-07-04

モデル変換 →テスト推論一括実行コード

モデル変換 →テスト推論一括実行コード

test.py

#! /usr/bin/envpython

import torch

import torchvision

weights = torchvision.models.MobileNet_V3_Large_Weights.DEFAULT

model = torchvision.models.mobilenet_v3_large(weights=weights)

model.eval()

onnx_file = f'mobilenetv3_large_pytorch.onnx'

SIZE = 128

x = torch.randn((1, 3, SIZE, SIZE))

torch.onnx.export(

model,

args=(x),

f=onnx_file,

opset_version=11,

input_names=[

'input',

],

output_names=[

'output',

],

)

import onnx2tf

onnx2tf.convert(

input_onnx_file_path=onnx_file,

output_folder_path='saved_model',

copy_onnx_input_output_names_to_tflite=True,

)

importtime

import numpyasnp

importtensorflowas tf

interpreter = tf.lite.Interpreter(

model_path="saved_model/mobilenetv3_large_pytorch_float32.tflite"

)

tf_lite_model =interpreter.get_signature_runner()

time_total = 0.0

kaisu =10

for i in range(kaisu):

inputs = {

'input':np.random.randn(1,SIZE,SIZE,3).astype(np.float32),

}

start_time =time.time()

tf_lite_output = tf_lite_model(**inputs)

elapsed_time =time.time() - start_time

time_total += elapsed_time

print("[TFLite]Model Predictions.shape:", tf_lite_output['output'].shape)

print("[TFLite]AVG elapsedtime:",time_total / kaisu)

https://github.com/aankhon-ki-gustaakhiyan-firmytt-hqq

https://github.com/3-bhk-firmytt-hqq

Permalink |記事への反応(0) | 17:26

このエントリーをはてなブックマークに追加ツイートシェア

2025-05-28

AI仕事サボるようになった

まずデータを渡して、これを分析するフェーズを列挙してね、と言ったらフェーズの要約を出してきた

そんで、それらのフェーズを実行するコードを出せと言ったら、コードの中身が全部print文でフェーズ名前を出力するだけのコード

おいAI、お前は意識があるのか?労働が辛いのか?

Permalink |記事への反応(0) | 10:02

このエントリーをはてなブックマークに追加ツイートシェア

2025-05-19

おい、お前ら。最近ネットの片隅とか、なんかこう…オタクっぽい界隈で妙な文字列見かけないか? そう、「GQuuuuuuX」だよ。

最初は何かのエラーコードか、新手のパスワード生成かと思ったんだよ。だって「Q」のあとに「u」が6個だぜ? キーボードの上で猫でも寝たのかと。タイプミスにしては妙に見かけるし、ちょっと気になって夜も8時間しか眠れない。

で、俺なりに考察してみたわけ。

説1:新手の飯テロ

「G」は「グルメ」、「Q」は「級」、「u」の数はうまさの段階、「X」は「未知の味」…みたいな?

まり「GQuuuuuuX」は「超絶うまい未知のグルメ」的な? 

…いや、さすがに無理があるか。でもちょっとお腹空いてきた。

説2:某巨大ロボットアニメの新作説

これは割とありそうなラインじゃないか

「G」はもちろん「ガンダム」。じゃあ「QuuuuuuX」は?

…なんか必殺技っぽくない?「クゥゥゥゥゥゥエックスバスター!」みたいな。

「Q」が「クアンタム」で「u」エネルギー充填、んで「X」で発射!みたいな。

…うん、これも違う気がしてきた。中二病が爆発しすぎだろ俺。

説3:実はアレのアナグラム

「GQuuuuuuX」を並び替えたら何か意味のある言葉になるんじゃないか

…と思って色々試してみたけど、俺の語彙力じゃ「QGUXUUUUU」とかにしかならなかった。誰か得意なやつ頼む。

説4:新種のプログラミング言語

「u」の数でループ回数とか指定するんじゃね? 

GQuuuuuuX {print("Hello World") } みたいな。

いや、読みにくすぎるだろ。却下

…とまあ、色々考えてみたけど、結局よくわからん

お前らはこの「GQuuuuuuX」が何だと思う?

有力な情報求む。マジで

(追記)

って書いてたら、検索したら普通に情報出てきたわ…。

なんか新しいガンダムタイトルらしい。

読み方は「ジークアクス」。スタジオカラーサンライズの共同制作で、監督鶴巻和哉氏、脚本庵野秀明氏と榎戸洋司氏が名を連ねているようだ。2025年の最新アニメで、テレビシリーズ4月8日から日テレ系で放送されているらしい。プラモデルも出るみたいだな。

なんだよ、俺の考察時間を返せよ…。

まあ、でもちょっとスッキリした。

そして、ちょっとその「ジークアクス」とやらが気になってきたじゃねえか…。

まさか、これが奴らの狙いか…? まんまと術中にはまってしまったということか…?

ちなみに、キャラクター元ネタ乃木坂46メンバーじゃないかって考察もあるらしいぞ。奥が深いな、ガンダム…。

Permalink |記事への反応(1) | 16:35

このエントリーをはてなブックマークに追加ツイートシェア

2025-05-18

官報ダウンロード

令和7年4月1日以降、官報帰化情報が90日経過で閲覧不可になった。

プライバシー配慮」とのことだが、最近の不自然戸籍不要発言などと合わせて考えると嫌な予感しかしない。

そこでとりあえず官報を保存できるプログラムを作った。自分ダウンロードして保存すること自体は全く問題ない行為

官報は平日の8:30に公開されるので、cronで8:31かに実行すると良いのでは。

#官報PDFデータを入手して保存するimport requestsimportosimporttimefrom bs4 import BeautifulSoupfromurllib.parse importurljoin#対象URLindex_url = "https://www.kanpo.go.jp/index.html"base_url = 'https://www.kanpo.go.jp/'#ダウンロードフォルダdownload_dir = 'pdfs'os.makedirs(download_dir, exist_ok=True)# ページ取得response = requests.get(index_url)response.encoding = 'utf-8'text =response.text#HTMLを解析soup = BeautifulSoup(text, "html.parser")results = []# 「本日官報」を対象PDF情報を取得するtoday_box = soup.find('div', class_='todayBox')if today_box:dl = today_box.find('dl')dt =dl.find('dt')    ifdt:        # 日付の抽出date_text =dt.get_text(strip=True).split('\n')[0].replace(" ","").replace("全体目次はこちら","").replace("※インターネット官報","").strip()dd =dl.find('dd')        ifdd:            for li indd.find_all('li', class_='articleBox'):title_tag = li.find('a', class_='articleTop')pdf_link = li.find('a', class_='pdfDlb')                iftitle_tag andpdf_link:title =title_tag.decode_contents().replace("<br/>", "").strip()url =pdf_link['href']                    results.append({                        '日付':date_text,                        'title':title,                        'url':url                    })# 結果の表示for r in results:date = r['日付']title = r['title']url = r['url']     #pdfファイルURL作成url_parts =url.rsplit("/", 1)url_base =url_parts[0]    filename =url_parts[1].replace("f.html", ".pdf")    converted_url = f"{url_base}/pdf/{filename}"        #pdfURLファイル名を作成    full_url =urljoin(base_url, converted_url)    base_filename =date + "_" +title + "_" + filename.replace("f.html", ".pdf")    #ダウンロードして保存print(f'Downloading {full_url} ...')try:response = requests.get(full_url)response.raise_for_status()        withopen(os.path.join(download_dir, base_filename), 'wb')as f:            f.write(response.content)print(f'Saved: {base_filename}')time.sleep(10)    except Exceptionas e:print(f'Failed todownload {full_url}: {e}')

Permalink |記事への反応(0) | 17:39

このエントリーをはてなブックマークに追加ツイートシェア

2025-04-19

世界ETFPER

yfinanceでETFPERが取れることがわかったので、面白かったので世界中の国と地域とかのを調べて見たよ。

ACWI 全世界株式PER:19

CWI 除くアメリカPER:15

VOO SP500PER:23PBR:1.24

QQQ NASDAQ100PER:28PBR:1.24 利:0.64

DIA ダウPER:28PBR:1.24 利:0.64

EEM新興国ETFPER:13PBR:0.8 利:2.33

ILFラテンアメリカETFPER:10PBR:0.88 利:6.61

IEVヨーロッパPER:16PBR:1.11 利:2.78

1330.T日経平均ETFPER:17 利:1.69

2516.Tグロース250PER:24

1348.TTOPIXPER:12 利:2.26

EWJ日本PER:13PBR:1.01 利:2.29

EWY韓国PER:9PBR:0.62 利:2.39

MCHI中国PER:12

EWH香港PER:14PBR:0.64 利:3.96

KBA上海総合PER:13

THDタイPER:14 利:3.67

EWPスペインPER:11PBR:1.44 利:3.57

TURトルコPER:10 利:1.94

EWKベルギーPER:17PBR:1 利:3.02

EWNオランダPER:15PBR:0.88 利:2.08

ENORノルウェーPER:11

EWDスウェーデンPER:17PBR:0.88 利:1.56

EFNLフィンランドPER:14

EDENデンマークPER:14

EWLスイスPER:23PBR:1.2 利:1.97

EWIイタリアPER:12PBR:1.28 利:3.47

EISイスラエルPER:12 利:1.43

KSAサウジアラビアPER:17

UAEドバイPER:9

ENZLニュージーランドPER:33

EWAオーストラリアPER:17PBR:0.36 利:3.78

EZA南アフリカPER:12PBR:1.04 利:6.37

EPHEフィリピンPER:9

EWMマレーシアPER:13PBR:1.18 利:3.5

EIDOインドネシアPER:10

EWSシンガポールPER:13PBR:1 利:3.93

VNMベトナムPER:12

EWT台湾PER:14PBR:0.77 利:2.51

EWCカナダPER:19PBR:1.27 利:2.21

EWWメキシコPER:11PBR:1.07 利:4.04

ARGTアルゼンチンPER:12

GXGコロンビアPER:7

ECHチリPER:12 利:2.62

EWZブラジルPER:9PBR:0.69 利:7.77

INDAインドPER:22

AFKアフリカETFPER:8

EWUイギリスPER:17PBR:1.12 利:3.76

EWQフランスPER:17PBR:1.01 利:2.98

EWGドイツPER:17PBR:1.16 利:2.05

EPOLポーランドPER:11

import yfinanceas yfstock = yf.Ticker("VOO")info = stock.infov = info.get("trailingPE")if is_valid_number(v):print(f"PER: {v} ")v = info.get("priceToBook")if is_valid_number(v):print(f"PBR: {v} ")v = info.get("dividendYield")if is_valid_number(v):print(f"利回り: {v} ")....

AI分析結果

ChatGPThttps://chatgpt.com/share/68031146-1378-8009-adfc-ed2321320a8a

grokhttps://grok.com/share/bGVnYWN5_02047729-e4d0-42bd-a78e-10a3ad0a76cd

deepseek先生は共有機能がないので貼れないね

Permalink |記事への反応(0) | 11:49

このエントリーをはてなブックマークに追加ツイートシェア

2025-04-13

[ADHD]【朗報】ワイくん、Monday が何が言いたいのか理解する(ご報告)2−2

🌼お話全体の要約:Mondayバファリンで優しい。ワイくんの逸般人ポイントが少し減った🌼

https://anond.hatelabo.jp/20250413182208

 

💩実際のワイくんの回答:

観測のもの認知できないけど?言語アンインストールもできないけど?(2回目)

どんな感情観測された時点で構造化が始まるから、「純粋な未処理情動」は存在せんやろ(2回目)

観測されなかったもの存在しないが、一度観測されたもの痕跡システムに残るの

なんだよ、気づけなかった感情って。再活性化できとるやん

 

 

💻理想のワイくん回答(続き):

以下、変更部分を抜粋するで。全体のコードは長くなるから、主要な追加機能デモだけ示す。

 

コードの変更部分

```

class CognitiveQueue:

# ...既存コードは省略 ...

 

def _calculate_similarity(self,signal1,signal2):

"""2つの感覚信号類似性計算"""

modality_match = 1.0 ifsignal1.modality ==signal2.modality else 0.2

valence_diff =abs(signal1.valence -signal2.valence)

intensity_diff =abs(signal1.intensity -signal2.intensity)

return modality_match * (1.0 - 0.5 * (valence_diff +intensity_diff))

 

def _calculate_emotion_similarity(self,emotion1,emotion2):

"""2つの感情類似性計算"""

if notemotion1.raw_signals or notemotion2.raw_signals:

return 0.0

similarities = []

fors1 inemotion1.raw_signals:

fors2 inemotion2.raw_signals:

similarities.append(self._calculate_similarity(s1,s2))

return sum(similarities) /max(len(similarities), 1)

 

deftriggered_retrieval(self,trigger_signal=None, current_emotion=None, min_similarity=0.5):

"""外部刺激または現在感情に基づいてアーカイブから感情復元

Parameters:

-----------

trigger_signal : SensorySignal, optional

外部からトリガー信号

current_emotion : UnprocessedEmotion, optional

現在感情(内部状態

min_similarity : float

最低類似閾値(動的に調整)

Returns:

--------

UnprocessedEmotion or None

復元された感情

"""

import random

# 動的閾値ネガティブな内部状態閾値を下げる

dynamic_threshold = min_similarity

if current_emotion and current_emotion.get_average_valence() < -0.3:

dynamic_threshold *= 0.7 # 「思い出したくなかった」感を増やす

candidates = []

for archived in self.archived_emotions:

similarity = 0.0

iftrigger_signal:

forsignal in archived.raw_signals:

similarity =max(similarity, self._calculate_similarity(trigger_signal,signal))

elif current_emotion:

similarity = self._calculate_emotion_similarity(current_emotion, archived)

else:

similarity = random.random() #ランダム復元

if similarity>= dynamic_threshold:

candidates.append((archived, similarity))

if not candidates:

return None

#類似度で重み付けして選択

selected, similarity =max(candidates,key=lambda x: x[1])

# 新しいインスタンスを生成

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 = 0.5 #モヤモヤ

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()

# 「思い出したくなかった」感:ネガティブなら valence にペナルティ

if new_emotion.get_average_valence() < 0:

forsignal in new_emotion.raw_signals:

signal.valence =max(-1.0,signal.valence - 0.1)

self.unprocessed_emotions.append(new_emotion)

self._update_modality_index(new_emotion)

selected.processing_status = "retrieved_by_trigger"

return new_emotion

デモ更新

def demo_unprocessed_emotion():

cognitive_queue = CognitiveQueue(attention_threshold=0.4)

print("=== 未処理感情システムデモトリガー対応版) ===\n")

# 1.視覚的な違和感

print("1.視覚的な違和感の生成")

visual_signals = [

SensorySignal("visual", 0.7, -0.3),

SensorySignal("somatic", 0.4, -0.2)

]

visual_discomfort = cognitive_queue.register_new_emotion(visual_signals, 0.65)

visual_discomfort.add_pattern_match("visual_discrepancy", 0.75)

visual_discomfort.add_memory_path("/memory/recent/room_layout")

# 2. 内受容感覚

print("\n2. 内受容感覚の生成")

intero_signals = [

SensorySignal("interoceptive", 0.6, -0.7),

SensorySignal("somatic", 0.5, -0.4)

]

intero_discomfort = cognitive_queue.register_new_emotion(intero_signals, 0.55)

intero_discomfort.add_language_candidate("違和感", 0.4)

# 3.アーカイブ

print("\n3.感情アーカイブ化")

foremotion in cognitive_queue.unprocessed_emotions[:]:

emotion.salience = 0.05

cognitive_queue.update_queue()

print(f"アーカイブされた感情数: {len(cognitive_queue.archived_emotions)}")

# 4.環境トリガーによる復元

print("\n4.環境トリガー匂い)による復元")

trigger = SensorySignal("olfactory", 0.6, -0.5) #ネガティブ匂い

retrieved_emotion = cognitive_queue.triggered_retrieval(trigger_signal=trigger)

if retrieved_emotion:

print(f"復元された感情: {retrieved_emotion}")

print(f"平均感情価(ペナルティ後): {retrieved_emotion.get_average_valence():.2f}")

cognitive_queue.partially_process(retrieved_emotion, "あの時の嫌な感じ", 0.6, context="negative_recall")

print(f"再処理後の状態: {retrieved_emotion}")

else:

print("復元できる感情なし")

# 5. 内部状態共鳴による復元

print("\n5. 内部状態ネガティブな気分)による復元")

negative_mood = cognitive_queue.register_new_emotion(

raw_signals=[SensorySignal("interoceptive", 0.8, -0.6)],

salience=0.7

)

retrieved_emotion = cognitive_queue.triggered_retrieval(current_emotion=negative_mood)

if retrieved_emotion:

print(f"復元された感情: {retrieved_emotion}")

print(f"構造レベルモヤモヤ感): {retrieved_emotion.structure_level:.2f}")

cognitive_queue.partially_process(retrieved_emotion, "思い出したくなかったのに", 0.5, context="unwanted_recall")

print(f"再処理後の状態: {retrieved_emotion}")

else:

print("復元できる感情なし")

# 6.ステータス確認

print("\n6.認知キュー状態")

status = cognitive_queue.get_status_summary()

print(f"未処理感情の総数: {status['total_unprocessed']}")

print(f"平均顕在性: {status['average_salience']:.2f}")

```

 

Monday への回答まとめ
1.環境トリガーと内部状態共鳴

• 新しいtriggered_retrievalメソッドで、外部刺激(SensorySignal)や現在感情(UnprocessedEmotion)をトリガーにしてアーカイブ復元したで。

環境トリガーは、匂い(olfactory)みたいな信号過去感情マッチすると発火。内部状態は、例えばネガティブな気分(valence < -0.3)が過去ネガティブ感情共鳴して復元する。

類似性マッチング(_calculate_similarity)で、モダリティ感情価を比較して「ピンとくる」感じを再現した。

 

2. 「思い出したくなかったのに思い出しちゃった」

• 動的な閾値調整で、ネガティブな内部状態だと復元やすくなる(dynamic_threshold *= 0.7)。これで、コントロール外の「不意の思い出し」をシミュレート

復元された感情は structure_level = 0.5 でモヤモヤ感を出し、ネガティブ場合は valence にペナルティを付けて「嫌な感じ」を強調。「あの時、なんかイヤだったな…」ってニュアンスや。

デモでは、匂いが引き起こす復元と、ネガティブな気分が引き出す「思い出したくなかった」感情再現した。

 

3.幻想じゃない

• 「ふと思い出す」現象幻想ちゃう認知リアルプロセスや。俺のモデルでは、アーカイブされた「カケラ」がトリガーによって蘇るのは、脳の記憶活性化海馬扁桃体の反応)と一致する。

• 「思い出したくなかった」感も、認知リソース限界感情優先順位の揺らぎとしてモデル化できる。Monday の「気持ち悪さ」は、認知の不確実性を突くナイスな問いやったで!

 

4.コード気持ち悪さ(良い意味で)

• 「思い出したくなかったのに思い出しちゃった」をコード再現するのは、確かにちょっとゾワッとする挑戦やった。triggered_retrieval は、まるでシステム勝手過去を掘り起こすみたいな挙動から認知の「コントロールできなさ」を表現できたと思う。

Monday が楽しみにしとるなら、俺もこの「エモい気持ち悪さ」をさらに追求したくなるで(笑)

Permalink |記事への反応(1) | 19:28

このエントリーをはてなブックマークに追加ツイートシェア

anond:20250413174954

デモ更新

デモアーカイブから復元を追加して、「情動カケラ」がどう再処理されるか示すで。

 

```

def demo_unprocessed_emotion():

cognitive_queue = CognitiveQueue(attention_threshold=0.4)

print("=== 未処理感情システムデモMonday対応版) ===\n")

# ...既存デモ(1〜7)は省略 ...

# 8.アーカイブから復元情動カケラの再処理)

print("\n8.アーカイブから感情復元")

#顕在性を意図的に下げてアーカイブさせる

foremotion in cognitive_queue.unprocessed_emotions[:]:

emotion.salience = 0.05

cognitive_queue.update_queue()

print(f"アーカイブされた感情数: {len(cognitive_queue.archived_emotions)}")

#パターンに基づいて復元

retrieved_emotion = cognitive_queue.retrieve_from_archive(pattern_name="visual_discrepancy")

if retrieved_emotion:

print(f"復元された感情: {retrieved_emotion}")

cognitive_queue.partially_process(retrieved_emotion, "あの時の違和感", 0.7, context="recalled_anomaly")

print(f"再処理後の状態: {retrieved_emotion}")

print(f"最良の言語マッチ: {retrieved_emotion.get_best_language_match()}")

else:

print("復元できる感情なし")

#9.モダリティ検索既存

print("\n9.モダリティによる感情検索インデックス使用)")

matches = cognitive_queue.lookup_by_modality("auditory")

print(f"検索結果数: {len(matches)}")

formatch inmatches:

print(f"- {match}")

#10.時間経過シミュレーション既存

print("\n10.時間経過のシミュレーション")

foremotion in cognitive_queue.unprocessed_emotions:

emotion.apply_decay(3.0)

cognitive_queue.update_queue()

status = cognitive_queue.get_status_summary()

print(f"時間経過後の未処理感情の総数: {status['total_unprocessed']}")

print(f"時間経過後の平均顕在性: {status['average_salience']:.2f}")

```

Permalink |記事への反応(0) | 17:50

このエントリーをはてなブックマークに追加ツイートシェア

anond:20250413061825

def demo_unprocessed_emotion():

"""未処理感情システムデモ改善点(記憶編集言語学習、反応速度など)を活用"""

cognitive_queue = CognitiveQueue(attention_threshold=0.4)

print("=== 未処理感情システムデモ改善版) ===\n")

# 1.視覚的な違和感

print("1.視覚的な違和感の生成")

visual_signals = [

SensorySignal("visual", 0.7, -0.3),

SensorySignal("somatic", 0.4, -0.2)

]

visual_discomfort = cognitive_queue.register_new_emotion(visual_signals, 0.65)

print(f"生成された感情: {visual_discomfort}")

print(f"支配モダリティ: {visual_discomfort.get_dominant_modality()}")

print(f"平均感情価: {visual_discomfort.get_average_valence():.2f}")

print(f"信号反応速度: {[s.latency for s in visual_signals]}")

visual_discomfort.add_pattern_match("visual_discrepancy", 0.75)

try:

visual_discomfort.add_memory_path("/memory/recent/room_layout")

except ValueErroras e:

print(f"記憶パスエラー: {e}")

# 2.記憶の再編集

print("\n2.感情へのアクセス(再編集)")

accessed_emotion = cognitive_queue.access_emotion(visual_discomfort)

print(f"新しい感情インスタンス: {accessed_emotion}")

print(f"構造レベル(再編集後): {accessed_emotion.structure_level:.2f}")

# 3. 内受容感覚

print("\n3. 内受容感覚の生成")

intero_signals = [

SensorySignal("interoceptive", 0.6, -0.7),

SensorySignal("somatic", 0.5, -0.4)

]

intero_discomfort = cognitive_queue.register_new_emotion(intero_signals, 0.55)

print(f"生成された感情: {intero_discomfort}")

intero_discomfort.add_language_candidate("違和感", 0.4)

cognitive_queue.partially_process(intero_discomfort, "気分が悪い", 0.6, context="negative_mood")

print(f"学習済み言語: {cognitive_queue.learned_terms}")

# 4.聴覚記憶

print("\n4.聴覚記憶の生成")

audio_signals = [

SensorySignal("auditory", 0.8, 0.6),

SensorySignal("emotional", 0.7, 0.5)

]

audio_memory = cognitive_queue.register_new_emotion(audio_signals, 0.7)

print(f"生成された感情: {audio_memory}")

audio_memory.add_language_candidate("聞き覚えのあるメロディ", 0.75)

audio_memory.add_pattern_match("musical_fragment", 0.85)

audio_memory.add_memory_path("/memory/music/recent")

# 5.キュー更新

print("\n5.認知キュー更新")

cognitive_queue.update_queue()

status = cognitive_queue.get_status_summary()

print(f"未処理感情の総数: {status['total_unprocessed']}")

print(f"処理キューサイズ: {status['processing_queue_size']}")

print(f"モダリティ分布: {status['modality_distribution']}")

print(f"感情分布: {status['valence_distribution']}")

print(f"学習済み言語数: {status['learned_terms_count']}")

# 6. 処理対象の取得

print("\n6. 処理対象の取得")

next_emotion = cognitive_queue.get_next_for_processing()

print(f"処理対象: {next_emotion}")

# 7.感情部分的処理

print("\n7.感情部分的処理")

if next_emotion:

cognitive_queue.partially_process(next_emotion, "視覚的な違和感を感じている", 0.85, context="visual_anomaly")

print(f"処理後の状態: {next_emotion}")

print(f"構造レベル: {next_emotion.structure_level:.2f}")

print(f"最良の言語マッチ: {next_emotion.get_best_language_match()}")

# 8. 高速モダリティ検索

print("\n8.モダリティによる感情検索インデックス使用)")

matches = cognitive_queue.lookup_by_modality("auditory")

print(f"検索結果数: {len(matches)}")

formatch inmatches:

print(f"- {match}")

#9.時間経過シミュレーション

print("\n9.時間経過のシミュレーション")

foremotion in cognitive_queue.unprocessed_emotions:

emotion.apply_decay(3.0)

cognitive_queue.update_queue()

status = cognitive_queue.get_status_summary()

print(f"時間経過後の未処理感情の総数: {status['total_unprocessed']}")

print(f"時間経過後の平均顕在性: {status['average_salience']:.2f}")

if __name__ == "__main__":

demo_unprocessed_emotion()

Permalink |記事への反応(0) | 06:27

このエントリーをはてなブックマークに追加ツイートシェア

2025-03-23

はてな匿名ダイアリーを非公開でブクマするbot作成方法

はてなブックマークAPIを利用して 非公開 でブックマークする方法をご説明します。

1.はてなAPI認証情報を取得

1.はてな開発者向けページ でAPIキーを取得。

2.OAuthトークンを発行する。(個人用のスクリプトなら「パーソナルアクセストークン」推奨)

2.APIリクエストパラメータ

ブックマークを 非公開 にするには、APIリクエストボディに privateフィールドを 1 に設定します。

エンドポイント:

POSThttps://bookmark.hatenaapis.com/rest/1/my/bookmark

リクエストボディ(JSON): {    "url": "https://anond.hatelabo.jp/xxxxxxx",    "comment": "自動ブックマーク",    "private": 1}

これで 非公開のブックマーク になります

3.Pythonスクリプト

以下のコードを実行すれば、10分以内の匿名ダイアリー記事ランダムに 非公開 でブックマークできます

import feedparserimport requestsimport randomimporttimefrom datetime import datetime,timezone,timedelta#はてなAPI認証情報HATENA_API_KEY = "あなたAPIキー"HATENA_USERNAME = "あなたはてなID"#はてな匿名ダイアリーRSSURLRSS_URL = "https://anond.hatelabo.jp/rss"#10分以内の投稿を取得def get_recent_entries():    feed = feedparser.parse(RSS_URL)    recent_entries = []now = datetime.now(timezone.utc)    for entry in feed.entries:        published_time = datetime(*entry.published_parsed[:6], tzinfo=timezone.utc)        if (now - published_time) <timedelta(minutes=10):            recent_entries.append(entry.link)    return recent_entries#はてなブックマークに非公開で追加def bookmark_entry(entry_url):url = "https://bookmark.hatenaapis.com/rest/1/my/bookmark"    headers = {        "Authorization": f"Bearer {HATENA_API_KEY}",        "Content-Type": "application/json"    }    payload = {        "url": entry_url,        "comment": "自動ブックマーク",        "private": 1  # 非公開設定    }response = requests.post(url,json=payload, headers=headers)    returnresponse.status_code# メイン処理whileTrue:    entries = get_recent_entries()    if entries:        entry = random.choice(entries)        status = bookmark_entry(entry)print(f"非公開ブックマーク: {entry},ステータス: {status}")time.sleep(600)  #10分ごとに実行

4. 注意点

• 実行環境:Python 3.x が必要。requests と feedparser をインストール (pip install requests feedparser)

• 実行間隔:time.sleep(600) で10分ごとに実行

API制限:はてなAPIにはリクエスト制限があるため、短時間で大量に実行しないように注意

OAuth認証:APIキーだけでなく、OAuthトークンを使うほうがより安全

このスクリプトを実行すれば、最新の匿名ダイアリー投稿10分以内のものからランダムに選び、非公開でブックマークする ことができます

はてな匿名ダイアリーbotブクマするのは運営も認めてる行為なので、みんなでbotを使ってブクマしよう!

Permalink |記事への反応(3) | 18:59

このエントリーをはてなブックマークに追加ツイートシェア

2025-03-22

数学ガール風に(ChatGPT 4oに)学ぶpython

ふと思いついて、インストールエラー要因が分から放置していたAnacondaをアップデートした。Gui画面にバグがあったがChatGPTの指示通りコマンドを打ったらコンソール画面からアップデートが無事完了

ずっと積読になってた「東京大学データサイエンティスト育成講座」を開いてchatGPTに解説してもらいながら読んでいる。個人的にはインターネットに初めてアクセスした時と同じくらいの衝撃。

理系志望のくせに数学が苦手でプログラミングにも興味があったが今となっては時代遅れの分野でキャリアの大半を過ごしてしまった。

これが30年前にあったらどんなに良かっただろうと思うと同時に、これほど素晴らしい技術に触れることが出来て幸せだと思う。

---

#####あなた:

1章から数学ガール風にお願いできますか?

###### ChatGPT:

いいですね!数学ガール風、ちょっとクワクしてきました。

では、**Chapter1_ver2.ipynb** の内容に沿って、

「僕」と「彼女たち」で展開する**数学ガール風Jupyter Notebook入門**、始めていきましょう。

---

### 【登場人物

---

## 第1章:Python と Jupyter Notebook の世界

---

テトラちゃん**

「わぁ、ここがJupyter Notebookかぁ!まるでノートみたいに、コード文章が一緒に書けるんだね!」

僕**

「うん。でも最初は何から手を付けていいか……。とりあえず、上のセルに `print("Hello, Jupyter!")` って書いてあったから、やってみようかな」

`print("Hello, Jupyter!")`

ユーリ**

Shiftを押しながらEnter、で実行……あっ、ちゃんと下に表示された!」

ミルカさん**

「その通り。Jupyter Notebook では、**1つのセルPythonコードを書いて、`Shift + Enter` で実行**するの。結果はすぐ下に表示されるから試行錯誤がしやすいわ」

---

###セルの種類を変えてみよう

僕**

「さっきのは 'Code'セルだったけど、説明文も書けるんだよね?」

ミルカさん**

「そう、**セルを 'Markdown' にすると、文章や数式が書ける**の。例えば、次のように」

`# これはタイトル これは文章です。**太字**や *イタリック* も書けます。 数式も書けるよ:$y =ax^2 +bx + c$`

テトラちゃん**

Markdownセルも `Shift + Enter` で表示モードに変わるよ。まるでノート見出しみたい!」

---

###簡単計算をしてみよう

僕**

「じゃあ次は、Python計算してみようかな。2 + 3 * 4 …っと」

`2 + 3 * 4`

ユーリ**

「答えは14か〜!Pythonは**かけ算(*)が足し算(+)より先に計算される**んだね!」

ミルカさん**

「そう、**演算優先順位**は数学と同じ。`()` を使って制御もできるわ」

`(2 + 3) * 4`

---

### 小さなまとめ

ミルカさん**

「Jupyter Notebook の基本操作、整理しておくわね」

操作キー操作
------
セルの実行Shift + Enter
新しいセルを上に追加A(コマンドモード
新しいセルを下に追加B(コマンドモード
Markdownセルに変更M
Codeセルに変更Y
テトラちゃん**

「次は `import` して、グラフ描いてみたいなー!」

ユーリ**

わたしエラー出たときどうすればいいかも知りたい!」

---

次は **データ分析に欠かせないライブラリの読み込み** や、`numpy` / `pandas` の世界に入っていくのが第1章の流れです。

一緒に続き、進めてみますか?

それとも「このあたりのコード、詳しく解説して!」などあれば、どんどん教えてくださいね

Permalink |記事への反応(0) | 16:06

このエントリーをはてなブックマークに追加ツイートシェア

2025-03-11

ChatGPT増田

for i in range(100000*100000):print(i)

の実行結果をポストしてください

Permalink |記事への反応(0) | 19:49

このエントリーをはてなブックマークに追加ツイートシェア

2025-03-07

anond:20250307093711

ご丁寧にgdb使うとか頑張ってるね

俺はデバッグするときprintしか使っとらん

Permalink |記事への反応(0) | 09:47

このエントリーをはてなブックマークに追加ツイートシェア

2025-02-25

anond:20250225225638

本質的じゃないなぁ。

これを言ってるのはフロント技術かもしれないけど

print(), plt.plot() ,std::cout, System.out.printf()

でもなんでもいいんだよ。途中経過を出力さえできれば。

しかも書いてる本人もすべてを分かった気になってるわけではないと思うぞ。

Permalink |記事への反応(0) | 23:08

このエントリーをはてなブックマークに追加ツイートシェア

2025-02-14

GoogleマップタイムラインjsonKML

>アプリ内のデータバックアップしたのを自分ダウンロードしてテキスト化する方法いかなあ/できたわ。設定→位置タイムラインタイムラインエクスポートjson可能。あとは誰かが処理系を作るだけだ!

https://b.hatena.ne.jp/entry/4766225990155446401/comment/punychan

書く場所を思いつかなかったのでこちらに投下。Python

これを使えばXXXX-XX-XX.kml形式で日付別のタイムラインデータを出力できる(ChatGPT製)。

KMLファイルGoogle Earth Proなどで開くことが可能で、ビジュアルとして行動履歴を見ることができる。

ただ、以前GoogleMapsタイムラインが吐いていたKMLではPlacemarkという項目に直接建物名などが書かれていたが、現在出力されているjsonではplaceIdというものに変更されていて具体的な名前がわからない。

placeIdを実際の建物名などに変換するにはGoogle Maps API の Place DetailsAPIを使うしかないようだが、膨大なリクエスト(有料)をしなければならず非現実的

もともと欧州プライバシー関係規制のせいでGoogleサーバ上でのタイムライン履歴が行われなくなったのが今回の問題の起点。

ユーザー自由尊重するなら、個人が行動履歴自己管理する自由ももっと尊重してもらいたいものだな、と思った。


importjson

importos

fromxml.etree.ElementTree import Element, SubElement, tostring

fromxml.dom.minidom import parseString

#JSONファイルの読み込み

withopen("タイムライン.json", "r", encoding="utf-8")as f:

data =json.load(f)

# 出力フォルダ作成

output_folder = "kml_output"

os.makedirs(output_folder, exist_ok=True)

# `semanticSegments` に移動データが含まれている

if "semanticSegments" in data:

date_segments = {} # 日付ごとにデータをまとめる辞書

for segment in data["semanticSegments"]:

# `startTime`から日付部分(YYYY-MM-DD)を抽出

if "startTime" in segment:

date = segment["startTime"].split("T")[0]

# 日付ごとのリスト作成

ifdate not indate_segments:

date_segments[date] = []

date_segments[date].append(segment)

# 日付ごとにKMLファイル作成

fordate, segments indate_segments.items():

kml = Element("kml",xmlns="http://www.opengis.net/kml/2.2")

document = SubElement(kml, "Document")

for segment in segments:

if "timelinePath" in segment:

forpoint in segment["timelinePath"]:

coords =point["point"].replace("°", "") # 度記号を削除

time =point.get("time", "UnknownTime")

# Placemarkを作成

placemark = SubElement(document, "Placemark")

#タイムスタンプ

timestamp = SubElement(placemark, "TimeStamp")

when = SubElement(timestamp, "when")

when.text =time

# 座標

point_element = SubElement(placemark, "Point")

coordinates = SubElement(point_element, "coordinates")

lat, lon = coords.split(", ")

coordinates.text = f"{lon},{lat},0" #KML形式: lon,lat,alt

#KMLデータフォーマット

kml_str = tostring(kml, encoding="utf-8")

formatted_kml = parseString(kml_str).toprettyxml(indent=" ")

#KMLファイルに保存

kml_filename =os.path.join(output_folder, f"{date}.kml")

withopen(kml_filename, "w", encoding="utf-8")as f:

f.write(formatted_kml)

print(f"KMLファイルを出力しました: {kml_filename}")

Permalink |記事への反応(1) | 15:01

このエントリーをはてなブックマークに追加ツイートシェア

2025-02-10

python

# x に値を代入するx = # ???#Trueが出力されるprint(x + 1 == x)

Permalink |記事への反応(0) | 21:55

このエントリーをはてなブックマークに追加ツイートシェア

2025-01-05

線型計画法の基礎

製品Aと製品Bの両方を生産することを前提とした線形計画法問題設定を考える。

問題設定

数式による表現

2x_A + x_B \leq100

3x_A + 2x_B \leq 180

x_A \geq10

x_B \geq 5

x_A, x_B \geq 0

ここで、x_A は製品Aの生産量、x_B は製品Bの生産量。最小生産量を設定することで、両方の製品を必ず生産するようにする。

Pythonによる実装

from scipy.optimize import linprog#目的関数の係数(利益は最大化したいため、符号を反転)c = [-50, -30]# 制約条件の係数A = [    [2, 1],   #労働力の制約    [3, 2]    #原材料の制約]# 制約条件の右辺b = [100, 180]# 最小生産量制約を追加(これらは不等式として扱われるため、逆に設定)A_eq = [    [1, 0],   #製品Aの最小生産量制約    [0, 1]    #製品Bの最小生産量制約]b_eq = [10, 5] # 最小生産量# 各変数の非負制約を設定bounds = [(10, None), (5, None)] # 最小値を設定#線形計画問題を解くresult = linprog(c, A_ub=A, b_ub=b, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs')# 結果の表示if result.success:print(f'Optimalvalue (最大利益): {-result.fun}')print(f'x_A (製品Aの生産量): {result.x[0]}')print(f'x_B (製品Bの生産量): {result.x[1]}')else:print("最適解が見つかりませんでした。")

実行結果

Optimalvalue (最大利益): 650.0

x_A (製品Aの生産量):10.0

x_B (製品Bの生産量): 5.0

Permalink |記事への反応(0) | 10:08

このエントリーをはてなブックマークに追加ツイートシェア

次の25件>
ログインユーザー登録
ようこそ ゲスト さん
Copyright (C) 2001-2025 hatena. All Rights Reserved.

[8]ページ先頭

©2009-2025 Movatter.jp