This blog is rated 🔞, viewer discretion is advised

快速入睡的技巧和原理

随着年龄的增长,加上工作和生活的恶习,睡眠越来越不好。很多时候躺在床上明明已经非常困了,但是大脑一不小心陷入胡思乱想,然后越想越睡不着。

很多人说把大脑放空就能睡着了,我也试过,放空是不可能的,大脑时时刻刻总得琢磨点什么;既然要琢磨点什么,那我们能否找一部分最容易睡着的来琢磨?这几年我倒琢磨出一个非常行之有效的方法用来入睡:

停止理性推演!强行带入感性的、放松、舒服的回忆体验占据大脑活动

具体展开,首先我这里对睡不着的「胡思乱想」作了一个二元分类:

  1. 一种是「理性」,逻辑推演:工作上的任务如何完成,生活中的矛盾如何化解,职业和家庭面对的困难,身边人群的压力,社会环境如何改进,民族国家的命运如何?电车会是能源革命吗?巴以冲突俄乌战争如何化解?等等,这类胡思乱想基本模式是「因果」:如果我做到A,那么B就会发生;如果我避免C,那么D这个糟糕的结果就能挽回。这类事,千万不要躺在床上想,否则越想越气。
  2. 另一种思绪我们称之为感性,温暖的阳光下微风吹过皮肤,恋人的手轻轻搂着你的腰,碧蓝的海平面上星星点点的船帆,你躺在椅子上无忧无虑的闭上眼睛享受这一切,只要把自己带入这种你亲身经历过的让你舒服,放松的体会中,假想你现在正在亲身经历这种愉快的事,那么你很快就能入睡。

或许,有人会说我命苦啊~没那么多享受可以回味。我之前也是这样,总觉得过得很匆匆没这么留下的美好回忆,有一次下班路过郊外,看到天边块落山的太阳,光线没那么刺眼,橙红色的余晖给白云描了个边,倒影在一处水塘里,没有了中午那么热的暴晒,微风刮过岸边那些稀稀拉拉的花朵和绿树。感受到美的瞬间迫使我立刻停下脚步,找个草坪坐下欣赏并且仔细观察,深怕错过任何一个细节,我当时决定把这个时刻深深记录在脑海里并反复加深印象,以备将来再也遇不到了。后来这个「场景」的确帮助我度过了很多个艰难的夜晚。

要训练这个区分能力没有想象那么难,但需要长期的刻意练习,大脑胡思乱想的时候很容易不自觉陷入「理性」部分,要想睡觉,就得避免。不要尝试去思考「why」。时刻对当前的大脑活动行为进行「鉴定」和归类。对事物分析、解释和总结类的事,躺着就不要去想;一旦躺下,就多回忆和假象一些「体会」和「感受」。需要额外注意,情感的大类里,有一种叫做「害怕」和「忧虑」的东西,也要特意避免,Zizek说过 “The only emotion that doesn't deceive is anxiety”,焦虑是惟一不骗人的情感,这句话的意思是,焦虑的本质是理性和归因分析,而不是情感,所以它很「真」而且很「重」。入睡这种事就不要当「真」啦,想点轻松愉快的骗骗自己做个美梦不好么。

对思绪的简单的二元分类并非我独创,Popper的第三世界《思考快与慢》里 I、II型系统都有类似的阐述。这个入睡方法是我无意中实践出来的,可能是早年无聊特别喜欢对思辨本身进行思辨,二分模式归类,睡不着是因为大脑老是琢磨事,我无聊得琢磨起琢磨本身(meta-琢磨?),于是逐渐琢磨出一个辅助入睡规律。

今天刚好看到另一个研究:德国蒂宾根大学发现,合理利用睡眠,可以提升一个人的决策能力

研究过程是,招募一群8到11岁的孩子,给他们看一组很吓人的照片,比如凶猛的动物之类。当时,几乎所有的孩子都被吓到了。之后,把这些孩子分成两组,第一组让他们回去睡一觉。第二组,让他们通宵玩游戏。
第二天,再给这些孩子看这些可怕的照片。结果发现,睡觉组的孩子,可以相对平静地观看照片。他们显得没那么害怕了。而通宵游戏组的孩子,被惊吓程度,跟前一天几乎没有区别。
研究人员认为,这就是睡眠的作用。睡眠就像一个过滤器。当我们面对一件事时,大脑的逻辑系统和情感系统,会同时运转。比如,看到一条毒蛇。你既会产生逻辑上的识别,记住这条蛇的基本特征。同时,你也会产生情感层面的反应,也就是害怕。
而睡眠的作用,就在于,过滤掉其中情感的部分,保留逻辑的部分。因此,睡觉的孩子再看到蛇时,他们就不会那么害怕,只会记得,这条蛇昨天见过。而通宵组的孩子,这个害怕的感觉还在,他们再看到蛇时,还会很害怕。
这也是为什么,很多人晚上一上秤,发现自己胖了,发誓第二天早上要起来跑步。但第二天却起不来。这就是因为,你立flag时的激情,被睡眠给过滤掉了。这也是为什么有人说,睡前千万不要立flag。
把这个结论再延伸一步,研究人员认为,假如你做一件事时,在很大程度上受到情绪干扰,那么你最好先去睡一会儿。这能帮助你更好地集中注意力。
比如,要不要创业?不创业,觉得有点虚度青春。创业,又有点患得患失。这就是受情绪干扰太多。按照这个研究,你就应该先去睡一觉。让你的情绪脑先冷却下来,睡醒之后,再用你的逻辑脑仔细想想。
其实,这个研究可以用一句话概括,不就是,一日之计在于晨吗?也就是,把需要动用逻辑思考,需要计算,需要做计划的事情,尽量放在一觉睡醒之后。

所以睡觉就睡觉,别想那么多。自然就能睡得着了。本文也用来回答V站题问《如何在睡觉的时候不胡思乱想》
。 转载请注明来自est的博客。

Posted

stdout

1900年居然不是闰年?

看HN讨论 昨天2024-02-29有哪些闰年的bug,有一个吃惊了

>>> datetime.datetime.strptime('Feb 29', '%b %d')
ValueError: day is out of range for month

python的 datetime() 默认 year=1900。但是心里想 1900 不应该也是闰年吗?

查了下还真不是。囧。一年有 365.242374 天:

  • 近似看成 365.25 天就是4年一润;
  • 剩余的精度 365.25-365.242374 == 0.0076 天
  • 而且,0.0076 ✖️ 400 == 3.0504,也就是每400年要少润3天
  • 结论就是每100年不润,但是每400年又要润
  • 比如 1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600 这些年都不是闰年。2000、2400是闰年。

真复杂!

Posted

stdout

穷人的supervisor OOM killer

厂里的docker上跑了个supervisord,用来把挂掉的进程拉起来。最近的问题不是进程挂掉,而是内存泄漏

跑着跑着内存爆了,然后宿主机OOM随机杀掉一个进程,结果占用内存最大的那个还活着,正常的进程反而gg,该漏的继续漏,然后反复OOM。想看下哪里漏了,--cap-add=SYS_PTRACE 也不给加,OOM策略也不给调,思来想去只能自己做防水补漏了。做起来也简单,supervisor再跑一套bash脚本即可:

while true; do
  p=`ps --no-headers  -xo rss,pid --sort=-rss | awk '{
    if($1 > 1000000){ print $2 }
  }'`
  kill $p 2>/dev/null || echo "everything fine";
  sleep 60;
done;

1000000 代表1G 内存。 sleep 60 表示 每60秒检查一次。

Posted

stdout

从 幻兽帕鲁 Palworld 设想一下未来的联机游戏

打开steam刷到一个新闻《Ten years of RimWorld》。啊?都十年了?回想起来最近非常爆火 幻兽帕鲁 Palworld ,被大家称为缝合怪,什么都缝了。细细盘点一下我对该类别游戏大杂烩的一个评价,以及我对未来游戏机制的一个YY。

Minecraft 挖矿争霸

我从这玩意还没中文名字的beta时代就开始玩(盗版),从山脚下一个 1x2 穴居的第一夜,挖到自己的第一铲煤,再到湖底水晶宫,然后修建自己的铁路在广袤的平原和山间品味那让人留连忘返 procedure generated terrain ,那个时候真的能给人一种激动。

后来搞的什么创造模式,各种复杂的机制和道具,没那个简单的快乐了。

Conan Exiles

和 minecraft 的 voxel 建筑风格相比,它的建筑是由正三角形、正方形构造出来的奇特镶嵌 。当然还有特色的 wheel of pain 驯奴系统,简直解放劳动力啊

Rimworld

这玩意好就好在它那套 story-teller 带来的调性,很有那个味。后来的其他作品比如 Stranded: Alien Down 虽然设施设备、机制都堆了,但是总给人一种单薄,后期没劲的感觉。Rimworld 的限制就在于 2D 而且固定尺寸地图,不是 open-world

Grand Theft Auto

这玩意当年从 GTA:SA 接触觉得简直是神作啊!无缝地图在当年看来就是魔法一般。而且迄今为止它也是没有太多科幻元素,完全以「现代」为题材的都市类游戏,国产的喜欢做三国、仙侠,国外的喜欢中世纪、废土和赛博。凸显了 GTA 的独特生态位。当然这玩意玩 online 就是纯纯的 grind,还好我早就通过外挂刷了几个亿,很轻松惬意。(声明:外挂只用来刷钱,并不具备其它不公平功能)。这玩意在我心目中是 open-world 当之无愧的开创者和王者。

Palworld

接触了一下这玩意,其实我对 pokemon 一直有耳闻但是完全不懂,现在看来有点类似收集+配种这样一个机制。想起来玩一些 MMORPG 比如 Black Desert 发现一个叫做 「family」的机制很有趣,你可以创建多个角色并切换,部分物品甚至是通用的。但是这玩意感觉除了对不同角色体验一番,并不能带来 1+1>2 的效果。我当时就非常希望同一个 family 的角色能相互配合,就像「Dragon Age: Origins」里一样,在行走和打架的时候能随时切换,不同的职业甚至能打出来一些配合,那该有多好。

缝合

游戏里最蛋痛的一点,对资源开采的大量需求,应该可以把玩家的角色托付给AI挂机,正如 Black Desert 的 auto-fishing 一样。Palworld 这一点就缝合的相当有趣了,原版的 pokemon 据说只能抓来打架,这里变成了还可以是生产力。比 Conan Exiles 里的奴隶机制更有意思。综合我前面的设想,我觉得以后的联机游戏,player-character 应该不是一个,而是一群。有血缘或者劳动附庸关系的「家族」。玩家应该有自由度选择控制其中一个或多个,玩家离线的时候这个「家族」应该也会按照设定进行生产和劳动。。。。甚至防御!

如果考虑死亡掉落机制,那么可以设计一套更有趣的系统:

  1. 捏脸不能全部自定义,而是类似 Red Dead Redemption 那样的双亲继承+微调
  2. 角色的职业,天赋点,也应该通过血缘获得,而不是生硬的数值
  3. 玩家控制角色可以重伤,甚至死亡。死了就真死透了。但是你可以多生育子女,选一个比如95%相似度的,继续玩。
  4. 玩家随身物品,如果掉落,需要家族里其他人去捞,或者发悬赏换回
  5. 子女太多可以交给社会化抚养,变成NPC。
  6. 付费玩家可以全价自定义投胎,免费玩家可以从弃养的NPC里挑选。
  7. 家族里其他角色可以随时控制,或者分配生产、战斗任务
  8. 有俘虏、雇佣,随从等「条约」系统支持跨血缘配合
  9. 都说文明周边会刷出来蛮族。蛮族哪里来的?超出承载能力的人口流亡出去的。一个「family」生育太多,养不起,可以放出去「自谋生路」,投靠别的部落。NPC杂兵不应该是无脑复制,而是每个角色都有个背景板。类似 Rimworld 里 colonist 被海盗抓走俘虏,颠破流离。

这样的体系下,说不定可以加入家族政治勾心斗角,最后演变成类似 十字军之王 一类的策略游戏?23333

在家族这样的设定下,还需要解决最后一个拼图:玩家终归是要时不时AFK的。那么玩家一定会需要据点。这类 base-building 游戏也烂大街了。但是最大的问题就是,一个服务器地图是有限的,好的建家点位就那么几个,目前联机游戏一般的做法是搞一套巨复杂的防御机制,高难度陷阱防止别的玩家抄家。实际上抄家和被抄家都挺难受的。

我的想法是,要不干脆把 base-building 改成关卡编辑器。把你基地当成Tower of Defense 的地牢来设计,家族成员通过占位和分工设计成闯关NPC,最后把你家族里战斗力最强的配置上最好的装备和武器设计成boss。然后拿一部分家产作为其他玩家闯关成功的奖励。别的玩家来闯关,是闯你家的副本,这样不完全破坏你的家,也可以让玩家发挥自己聪明才智,让别的玩家体会会被阴、被虐的乐趣。

有了「家族」和「关卡」两套机制,游戏的玩家也成了游戏机制进化的一部分,可以说病毒式传播,生生不息了。反正我又不做游戏,所以随便YY,不用关心可行性和成本,谁有兴趣请自行挪用,最好做出来能邀请我内测 :)

Posted

stdout

FastAPI/Starlette 长连接感知断开

之前写过如何 在服务器重启的时候感知长连接,最近发现折腾复杂了。

https://github.com/encode/starlette/discussions/1776

测试代码:

import asyncio

async def async_streamer():
    try:
        while True:
            yield b"--boundary\r\nContent-Type: text/plain\r\nContent-Length: 1\r\n\r\n1\r\n"
            await asyncio.sleep(0)
    except asyncio.CancelledError:
        print("caught cancelled error")

app = Starlette(routes=[
    Route('/async', async_endpoint),
])

跑起来: uvicorn stream:app

这段代码粗一看没啥大不了的,但是神奇的地方在于,如果去掉 try ... except asyncio.CancelledError ,代码也能正常跑


async def async_streamer():
    while True:
        yield b"--boundary\r\nContent-Type: text/plain\r\nContent-Length: 1\r\n\r\n1\r\n"
        await asyncio.sleep(0)

而且不会报错!最蛋痛的是,这玩意因为是个 while True,如果你里面有打开的数据库连接,是不会中断的,也不会回收的。因为这个 coroutine 没有继续 async for 来消费,就一直挂在进程里当僵尸了!

加上 try ... except asyncio.CancelledError,能捕获出错,也能处理善后了。

真是神奇啊。不知道是 uvicorn 的特性,还是 ASGI 都这样。

Posted

stdout

不能忘却的记忆

由于小爱同学不能导出就挨个手打出来。纪念这个日子。

一年前这几天,孩子和爱人相继病倒,我本来以为苟住了能以幸免结果在家人好转的时候一测体温发现偏高。于是赶紧洗了个澡,把小卧室腾出来,弄好电暖气、电吹风,装满开水壶,把mbp和其它个人物品搬进去,因为我知道接下来的日子将会无比煎熬。

date
2022-12-18 16:41 37.3
2022-12-18 16:43 37.3
2022-12-18 17.31 38.1
2022-12-18 17:46 38.3
2022-12-18 18:33 39.3
2022-12-18 18.41 38.7
2022-12-18 19:07 38.3
2022-12-18 19:15 38.7
2022-12-18 20:01 38.6
2022-12-18 21:11 39.5
2022-12-18 21:20 38.9
2022-12-18 21:26 39.1
2022-12-18 21:41 39.2
2022-12-18 23:30 38.4
2022-12-19 02:38 39.3
2022-12-19 02:48 38.3
2022-12-19 10:05 38.5
2022-12-19 10:12 37.9
2022-12-19 10:36 37.4
2022-12-19 11:19 37.7
2022-12-19 14:03 37.7
2022-12-19 14:29 37.0
2022-12-19 15:18 37.7
2022-12-19 16:33 37.6
2022-12-19 18:05 38.1
2022-12-19 18:44 37.8
2022-12-19 19:12 37.2
2022-12-19 19:47 37.8
2022-12-19 20:00 37.6
2022-12-19 21:09 37.2
2022-12-19 21:44 37.2
2022-12-19 22:57 36.9
2022-12-20 00:19 37.2
2022-12-20 06:55 37.1
2022-12-20 09:03 37.0
2022-12-20 09:34 37.0
2022-12-20 10:49 36.8
2022-12-20 11:41 38.0
2022-12-20 11:59 38.4
2022-12-20 14:47 38.6
2022-12-20 15:51 38.1
2022-12-20 16:32 38.0
2022-12-20 18:22 38.3
2022-12-20 22:31 38.4
2022-12-21 09:12 38.1
2022-12-21 09:59 38.2*
2022-12-21 11:57 38.2
2022-12-21 13:46 37.5
2022-12-21 15:10 37.5
2022-12-21 16.44 37.2
2022-12-21 17:07 37.0
2022-12-21 20:37 37.2
2022-12-21 20:54 37.7
2022-12-21 22:54 38.3
2022-12-21 23:05 38.4
2022-12-22 09:23 36.7
2022-12-22 09:43 37.3
2022-12-22 12:44 37.6

*: 布洛芬已用完

可能大家只是看到一串冷冰冰的数字,但是我打字都是颤抖的,每一刻时间和体温都是刻骨铭心的记忆。

NEVER FORGET!

Posted

stdout

京加高铁

今天了解到这么一件事,白令海峡原来也就 82.5km 宽,水深55米,对于现代工程技术来说修桥和隧道都不是问题。

如果中间那个岛做个中转站,那么两侧都各自30km左右。所以理论上从北京修一条到西雅图/加州的高铁完全没有问题。。

Posted

stdout

query git notes with Github GraphQL

git notes is an interesting feature, you can use it like

git notes add -m "hello test git notes"
git push origin 'refs/notes/*'

Github supported them back in 2010 then gave up LMAO.

If you need to retrive them with Github API, try GraphQL like this

  {
    repository(owner: "est", name: "snippets") {
      refs(refPrefix:"refs/notes/",first:1) {
        nodes{
          ... on Ref{
            target {
              oid
              ... on Commit{
                changedFilesIfAvailable
                message
                tree{
                  oid
                  entries{
                    oid
                    path
                    size
                    lineCount
                    mode
                    object{
                      ... on Blob{
                        byteSize
                        text
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

It will return something like:

  {
    "data": {
      "repository": {
        "refs": {
          "nodes": [
            {
              "target": {
                "oid": "bfdfda121f3d8a2d6aa399e3e8f0d58b3db0a543",
                "changedFilesIfAvailable": 1,
                "message": "Notes added by 'git notes add'",
                "tree": {
                  "oid": "2ab3e6a8b0dff6596fa60ecfb3c61bf91e5b4e1f",
                  "entries": [
                    {
                      "oid": "404d353a254ffbc97b2e16d17b8c100461aef586",
                      "path": "4fb1272f1e235580f87e3ec071984658de050dc9",
                      "size": 21,
                      "lineCount": 1,
                      "mode": 33188,
                      "object": {
                        "byteSize": 21,
                        "text": "hello test git notes\n"
                      }
                    }
                  ]
                }
              }
            }
          ]
        }
      }
    }
  }

Here "path": "4fb1272f1e235580f87e3ec071984658de050dc9" is the commit SHA.

If you add more filter parameters in refs() you can fetch all the notes.

Posted

stdout

VPS推荐:Hosteon

继续上次 Racknerd 之后发现这家还行。写了个爬虫扒了一下各色配置,独立服除外,有需要的自取

pid spec Disk Bandwidth Annual $
1 1C512M 5GB 100Mbps $27.00
7 6C8G 100GB 100Mbps $270.00
77 1C1G 10GB 1Tbps $21.00
78 2C1.5G 20GB 2Tbps $36.00
79 2C2G 25GB 3Tbps $45.00
80 2C2.5G 30GB 4Tbps $54.00
81 3C3G 40GB 5Tbps $63.00
83 3C5G 50GB 8Tbps $90.00
84 6C10G 120GB 12Tbps $180.00
85 10C12G 150GB 15Tbps $270.00
86 14C20G 200GB 20Tbps $450.00
87 20C30G 300GB 30Tbps $675.00
110 1C1G 15GB 2Tbps $21.00
111 2C2G 20GB 4Tbps $39.99
112 3C3G 30GB 6Tbps $49.50
113 4C4G 40GB 8Tbps $59.99
119 1C512M 10GB 500Gbps $24.00
120 1C1G 15GB 1Tbps $36.00
121 2C2G 30GB 2Tbps $72.00
122 2C3G 50GB 3Tbps $108.00
123 2C4G 70GB 4Tbps $144.00
124 4C5G 90GB 5Tbps $180.00
126 6C6G 100GB 6Tbps $216.00
127 6C7G 120GB 7Tbps $252.00
128 8C8G 140GB 8Tbps $288.00
129 8C9G 150GB 9Tbps $324.00
130 10C10G 170GB 10Tbps $360.00
131 10C11G 180GB 11Tbps $396.00
132 12C12G 200GB 12Tbps $432.00
154 1C1G 20GB 4Tbps $33.00
155 2C2G 30GB 6Tbps $40.00
156 3C3G 40GB 8Tbps $60.00
157 4C4G 50GB 10Tbps $84.00
158 5C5G 60GB 12Tbps $105.00
159 6C6G 70GB 14Tbps $130.00
160 7C7G 80GB 16Tbps $145.00
161 8C8G 90GB 18Tbps $170.00
162 9C9G 100GB 20Tbps $190.00
163 10C10G 110GB 22Tbps $210.00
164 11C11G 120GB 24Tbps $240.00
165 12C12G 130GB 26Tbps $260.00
166 8C8G 50GB 30Tbps $98.99
167 4C4G 25GB 15Tbps $56.99
168 4C4G 25GB 15Tbps $79.00
169 8C8G 50GB 30Tbps $158.00
170 12C12G 75GB 30Tbps $235.00
171 16C16G 100GB 30Tbps $318.00
172 20C20G 125GB 30Tbps $399.00
173 24C24G 150GB 30Tbps $480.00
174 28C28G 175GB 30Tbps $575.00
175 32C32G 200GB 30Tbps $660.00
176 36C36G 225GB 30Tbps $730.00
177 40C40G 250GB 30Tbps $810.00
178 1C1G 20GB 2Tbps $21.00
179 32C32G 1TB 1Gbps $540.00
180 64C64G 1TB 1Gbps $725.00
181 128C128G 2x 1Gbps $1850.00

Posted

stdout

太阳系天体的 unicode 符号

发现Astronomical symbolsPlanet symbols
Alchemical symbol

IAU 七金 符号 name 星期 七曜 备注
☉︎ 太阳 Sun 星期天 日曜
月球 Moon 星期一 月曜 也可以画成 ☽︎
或者月相 🌑︎🌒︎🌓︎🌔︎🌕︎🌖︎🌗︎🌘︎,🌚︎🌛︎︎🌝︎︎🌜︎︎
H 水星 Mercury 星期三 水曜 赫耳墨斯(Hermes),罗马人称 Mercury
现代人称「爱马仕」的双盘蛇带翼权杖 Caduceus
V 金星 Venus 星期五 金曜 维纳斯
E 🜨 地球 Earch Bible 里说的四条河把地球分成四洲
另外的符号是 ♁ 表示十字架钉个球 globus cruciger
M 火星 Mars 星期二 火曜 符号是战神盾牌和长矛
J 木星 Jupiter 星期四 木曜 字母 Zeta(大写Ζ小写ζ)加一杠,代表宙斯/朱庇特
S 土星 Saturn 星期六 土曜 字母 kappa-rho ,表示 Kronos 加一杠
泰坦 克罗诺斯,宙斯他爹
U 天王星 Uranus
N 海王星 Neptune

几点:

  • 其中 金星/火星 符号被拿来代表 女/男 是1750年代Carl Linnaeus干的。
  • 冥王星 Pluto 发现的晚,占星术还没来得及改版就惨遭除名成矮行星。
  • 星期和对应的天体意义,全世界惊人的一致

其它各种卫星,小行星的名字就懒得贴了。

有了这些符号,我们可以画一个比如托勒密的简化版太阳系模型:

本文源自《哥白尼、伽利略、开普勒都是脱离证据拍脑袋撕逼》一文。HN

Posted

stdout

Getting started blogging on Win10

I am planning to setup by blogging environment on my Windows PC.

  • OS: Windows 10
  • Shell: Bash on WSL1
  • Program: pelican on Miniconda3 with Python 3.11

My objective today is get rid of the static/js/core.js from aether-pelican theme and replace it with a simple CSS, and it turns out quite challenging.

WSL1 and file system

As it turns out, the installed Ubuntu root filesystem on WSL1 is located here:

%localappdata%\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs

I plan to move my home dir (at least) to another SSD on my PC, as the C:\ drive is an old SanDisk Plus240, which is unforgivablly slow these days. I tried to mv ~ /mnt/d/home, ok but the permission gets weird.

So I tried to copy the folder on Windows to D:\home, and mklink back. I tried both mklink /D and mklink /J ( the /D switch works on a remote drive whereas the /J junction works on local NTFS disks only) and they both failed be recognized by WSL1. The bash yields Broken stdout/stdin upon launch

So OK, default home dir then. Bad luck for me.

Ubuntu 22

I just found out my cat /etc/lsb-release shows Ubuntu 18, which is the default distro installed on WSL1 I assume. I tried to install Ubuntu 22 from the Microsoft Store, after several wasted minutes (curse the slow Internet in Mainland!) it turns out for WSL2 only. Luckily the Windows Subsystem for Linux was successfully upgraded to latest version:

C:\> wsl --version
WSL version: 1.2.5.0
Kernel version: 5.15.90.1
WSLg version: 1.0.51
MSRDC version: 1.2.3770
Direct3D version: 1.608.2-61064218
DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version: 10.0.19045.3570

the wsl --list --online commands stuck for a total of 10 minutes and returns nothing (curse the AS4134 163NET!)

Getting Python, Miniconda and Pelican

So linux distro setup was back to where started, I only have Python to mess with. Miniconda3 gets insalled easily, now that's a some progress. The static site generator I am using pip install pelican[markdown] finishes ok, the pypi was not blocked? Keke.

Then I typed make. It was not part of WSL1? Blaspheme!

Manually running python -m pelican.server, and voila! The Windows asks for firewall listening permission, granted, open up browser, BAM! My blog setup process is done and now I can write and tweak it on Windows.

Oh, and there's git config core.fileMode false needs to be checked!

Posted

stdout

火星上怎么结算工资

看到个段子

突然让我想起个事,如果去火星打工,薪资该怎么计算?摘录 wikipedia

火星的恒星时长 24小时37分钟22.663秒,而太阳日则长 24小时39分钟35.24409 秒。而地球的恒星时和太阳日则分别是 23小时56分钟4.0916秒24小时。在比较之下,一火星太阳日等于1.027491地球太阳日,即比地球太阳日长2.7%。

怎么有两个天?继续搜

太阳日(英语:solar day)是依据太阳运动,所定义的时间,可以分为视觉太阳日和平均太阳日。一太阳日传统称为一“日”、一“天”或一“昼夜”。

英语里把火星的一天叫做一个 Sol。一个火星年在英文的 wikipedia 有讲

sidereal year ... is about 686.98 Earth solar days (≈ 1.88 Earth years), or 668.5991 sols 。也就是说火星一年有 668.5991 火星天。。。

火星因为有25.19°的自转倾角,跟地球相近,所以也可以划分四季。但问题是,火星的轨道长这样:

所以如果按照四个季节划分,最长的季节有 194 个 Martian Sols,最短的 142 Martian sols

那么问题来了。在火星上怎么算工资呢?我觉得得安天结了。还有,假如亲爱的读者小伙伴将来到火星务工,应聘的时候一定确认好是按地球年结算还是火星年哦。谨防火星历诈骗!

Posted

stdout

FastAPI/Starlette graceful shutdown server-sent events

缘起

假如你用 FastAPI/Starlette框架,写了一段 Server-sent Events

@app.get('/api/my_stream')
async def api_stream():
  async def gen():
    while 1:
      yield "data: {}\n\n"
      await asyncio.sleep(1.0)

  return StreamingResponse(gen, media_type="text/event-stream", headers={
    'X-Accel-Buffering': 'no',
    'Cache-Control': "no-cache",
    'Connection': "keep-alive",
  })

FastAPI 事件

然后你重启了服务器,比如 gunicorn+uvicorn,你会发现这个连接不会断开,一直输出结果。直到 worker 进程超过配置里的 timeout 参数(默认60秒),被 master 强行杀死然后重启。

一开始尝试了 FastAPI 官方的 shutdown 事件,再在代码的 while 1 加一个 if 判断。发现不管用

@app.on_event('shutdown')
def on_server_shutdown():
    app.state.running = False

发现这段代码执行是执行了,但是是在杀死worker的时候生效的。得更加提前。用ASGI推荐的lifespanhttp.disconnect 太复杂,放弃。

Linux signal

尝试暴力监听 worker signal

import signal
signal.signal(signal.SIGINT, on_server_shutdown)  # ctrl+c
signal.signal(signal.SIGUSR2, on_server_shutdown)
signal.signal(signal.SIGTERM, on_server_shutdown)
signal.signal(signal.SIGWINCH, on_server_shutdown)
signal.signal(signal.SIGHUP, on_server_shutdown)
signal.signal(signal.SIGQUIT, on_server_shutdown)

发现也不管用。研究了半天,似乎是 UvicornWorker.init_signals 的时候signal.SIG_DFL。无语ing

uvicorn shutdown 流程

看gunicorn日志:

[2023-11-02 09:50:38 +0800] [25918] [INFO] Shutting down
[2023-11-02 09:50:38 +0800] [25918] [INFO] Waiting for application shutdown.
[2023-11-02 09:50:38 +0800] [25918] [INFO] Waiting for connections to close. (CTRL+C to force quit)
....
[2023-11-02 09:51:18 +0800] [25918] [INFO] Application shutdown complete.
[2023-11-02 09:51:18 +0800] [25918] [INFO] Finished server process [25918]
[2023-11-02 09:51:18 +0800] [25918] [INFO] Worker exiting (pid: 25918)

观察到 Waiting for connections to close 之后卡住。

属于 uvicorn 的 Server.shutdown() 方法

这个方法调用链:

  1. Server.install_signal_handlers 里注册 signal
  2. Server.handle_exit 里设置 Server.should_exit = True
  3. 每秒一次的 Server.on_tick 就会打断 Server.main_loop() 死循环
  4. 调用 Server.shutdown

如果能拿到 Server.should_exit 自行判断就好了,但是 ASGI 是容器无感的,只继续研究

断开http连接

上面日志有一个比较关键:

# Request shutdown on all existing connections.
for connection in list(self.server_state.connections):
    connection.shutdown()
    await asyncio.sleep(0.1)

其http连接关闭方法实现为:

def shutdown(self):
    """
    Called by the server to commence a graceful shutdown.
    """
    if self.cycle is None or self.cycle.response_complete:
        self.transport.close()
    else:
        self.cycle.keep_alive = False

这里应该走的是 else 分支。所以解决方法就是去代码里拿到 cycle.keep_alive 这个属性。

ASGI 接口

跟了一会儿,发现ASGI 在 starlette 里如下流程:

  1. Route() 初始化 self.app = request_response(endpoint)
  2. Route().handle() 的时候会调用 self.app(scope, receive, send)
  3. unicornrun_asgiresult = await app(self.scope, self.receive, self.send) 。其中 app 就是 starlette 的 Route() 实例

所以解决方案逐渐明朗了

黎明的前夜

通过 FastAPI/Starlette 请求的 .receive 属性的 __self__ 拿到 unicorn 的 cycle 实例,然后定时判断上面 shutdown 赋值的 self.cycle.keep_alive = False

@app.get('/api/my_stream')
async def api_stream(req: Request):
  async def gen():
    while 1:
      yield "data: {}\n\n"
      await asyncio.sleep(1.0)
      if getattr(req.receive.__self__, 'keep_alive', None) is False:
        break

  return StreamingResponse(...

这里用了个 getattr() 是保证这个 hack 在非 unicorn 下代码也能正常跑

git commit . -m "haha" 上机联调,发现坑了。。。我特么。。。。这个 cycle.keep_alive 默认就是 False

扭转 keep_alive

这玩意一直为 False 的原因是,unicorn 的 HttpToolsProtocol.on_headers_complete 赋值过程:

self.cycle = RequestResponseCycle(..., keep_alive=http_version != "1.0")

这里 http_version 可以通过 req.scope['http_version'] 得到,打印了一下,你猜怎么着,还真tm是。。。原因就是厂里反代 nginx的proxy_http_version没配置。这里是个常见的坑,非常影响性能,因为每个请求会生成一个新的 http 连接。

但是也等不急SA去改配置了。于是直接在代码 async def gen(): 前面写死:

req.receive.__self__.keep_alive = True 。提交,再试。。。咦,怎么 keep_alive 依然为 False????明明刚刚赋值了?

继续读代码,发现第二个坑,发现 unicorn 的 RequestResponseCycle.send() 方法里,在构造返回的时候,有一句

for name, value in headers:
    elif name == b"connection" and value.lower() == b"close":
        self.keep_alive = False

好吧。。。那么解决方法就是,把 keep_alive = True 挪到返回内部。先完成返回构造,再强行改值。

最后的代码

@app.get('/api/my_stream')
async def api_stream(req: Request):
  # req.receive.__self__.keep_alive = True  # doesn't work here
  async def gen():
    req.receive.__self__.keep_alive = True  # works here
    while 1:
      yield "data: {}\n\n"
      await asyncio.sleep(1.0)
      if req.receive.__self__.keep_alive is False:
        break

  return StreamingResponse(gen, media_type="text/event-stream", headers={
    'X-Accel-Buffering': 'no',
    'Cache-Control': "no-cache",
    'Connection': "keep-alive",
  })

测试重启 worker,该连接在1秒后断开,worker平稳重启。完美。

苦逼撸业务的一天又开始了。

Posted

stdout

浏览器拉起钉钉客户端并跳转OA工单

又是 corporate software engineering 吃屎的一天。用户在内部系统走流程,厂里用的是钉钉自带的OA工单审批。已经接入了API创建、完成工单

问题在于发起工单之后,用户并没有感知,不知道工单去哪里了,流程就断了,向钉钉官方售后发起咨询,对方丢了一句:不支持。无语

只能自己鼓捣。已知工单链接,在钉钉聊天窗口内部的最短的网址为:

  https://aflow.dingtalk.com/dingtalk/mobile/homepage.htm?corpid=...&procInstId=...#approval

对方丢了一个 dingtalk:// 跳转协议

反复尝试,发现一个很有用:

桌面端打开URL
dingtalk://dingtalkclient/page/link
侧边栏: pc_slide=true
大容器(类似工作台容器)ddtab=true

于是构造一个试试:

  dingtalk://dingtalkclient/page/link?url=https%3A%2F%2Faflow.dingtalk.com%2Fdingtalk%2Fpc%2Fquery%2Fpchomepage.htm%3Fcorpid%3D...%26procInstId%3D...%23%2Fapproval

然后果然ok了。

钉钉给人的感觉就是各个部门 hack 强行揉合起来一个怪物。各种不完善、不一致的问题。有空写一下吐槽。

Posted

stdout

SVG放在 img 中不能加载图片/字体

最近想在 markdown 里搞图文混排,遇到一个大图把版面占完了,想缩小一些,由于 .md 渲染器安全限制,没法直接指定宽高

只能从图片本身想办法,首先最直接的手段就是服务器再缩放一次,但是蛋痛的问题是缩放之后文件怎么存,怎么给静态文件路由,怎么保障图片可用性,怎么兼容各种尺寸,想想都头大。

想到一个 hack,要不直接放一个 .svg 进去,因为 svg 支持加载位图资源,所以把 svg 位图缩小一点,让浏览器渲染 svg 不就行了。

没想到就被这个 hack 坑了。原因是 svg 如果被 <img> 标签渲染,那么禁止加载任何外部资源,脚本也禁止执行。

为了证明这个限制,我写了个 demo 放在 https://lab.est.im/shit_svg/

这个问题太隐蔽了。stackoverflow 上只有 Robert LongsonThangLeQuocTheHippo
的答案提到隐约线索:

后来搜了到 skychx 把这个问题研究透了。罪魁祸首 SVG Security

If an SVG file is fetched as image, then certain requirements apply to this document:

  • The SVG document is not allowed to fetch any resources. This also applies to scripts, stylesheets or images.
  • Fonts shouldn't be loaded as well. The situation in UAs seems to still be unclear though.
    Scripts must not be executed.
  • Event listeners must be disabled at all times.

浪费我好多时间。SVG2里把这个说得很明白了 https://www.w3.org/TR/SVG2/conform.html#processing-modes

When external references are disabled in an SVG document, any attempt to fetch a document through an external reference must instead be treated as if a network error occurred and no data was received.

不过查阅资料的时候发现个好玩的,SVG 1.1 支持 URL fragments

比如:

Posted

stdout

市以上行政区划去掉后缀

今天才知道,中国一共333个市一级行政单位。数据来源是 民政部首页 ➡ 民政数据

import re

def short_name(name):
    m = re.search(r'''
        (\S+?)
        (?:
            壮族|回族|维吾尔|省|自治区|特别|  # 省
            (?:侗|傈僳|傣|哈尼|回|土家|壮|布依|彝|景颇|朝鲜|白|羌|苗|藏)族|
            蒙古|柯尔克孜|哈萨克|
            地区|市|盟|自治州|自治县
        ).*$
    ''', name, re.VERBOSE)
    if m:
        return m.group(1)
    return name

这段代码的作用是把比如 "黔南布依族苗族自治州" 这样的名字,缩短成 "黔南"

有一个小坑是,市一级行政区包含 蒙古|柯尔克孜|哈萨克 这三个名字后面没有 字。

有一些 XX林区 XX矿区 什么的,我觉得保留比较好。

Python的 re.VERBOSE 真是好东西!

Posted

stdout

在py3里同步/异步混合使用 httpx 调用

比如开发需求是请求一个 http API,得到数据,解析一下返回,那么一般的做法是封装一个方法,比如

import httpx


def get_sth(p1, default=MY_VAL):
    # network
    r = httpx.get(API_URL, params={'t1': p1})
    # parsing
    res = r.json().get('my_key') or MY_VAL

但是如果想在 async/await 里用这段代码,就得改成

import httpx


async def get_sth(p1, default=MY_VAL):
    # network
    with http.AsyncClient() as client:
        r = await client.get(API_URL, params={'t1': p1})
    # parsing
    res = r.json().get('my_key') or MY_VAL

注意其中 def get_sth() 也必须改成 async def get_sth 。这就是所谓 async/await 传染性

这个时候,如果你想把这块代码抽象出来,让同步/异步的库都能调用,我在最近重构里找到一个最佳实践:

import httpx


def get_sth(p1, default=MY_VAL):
    r = httpx.Request('GET', API_URL, params={'t1': p1})
    r.parse = lambda x: (x.get('my_key') or MY_VAL)

# 同步调用:
with httpx.Client() as client:
    r = client.send(get_sth())
r.request.parse(r.json())

# 异步调用:
async with httpx.AsyncClient() as client:
    r = await client.send(get_sth())
r.request.parse(r.json())

思路是 逻辑和 transport解耦,也是某种意义上的 Sans-IO 了吧?

Posted

stdout

git切换马甲

如果你有多个 github、bitbucket、gitlab 账号需要来回切换,那么这个方法或许对你有用。

使用git你需要配置一个 ~/.ssh/id_rsa,如果你有多个身份就麻烦了。传统网上搜到的办法是编辑 ~/.ssh/config 然后加入个类似这样的配置:

  Host estgit
  HostName github.com
  Port 22
  User git
  IdentityFile ~/.ssh/est_github
  IdentitiesOnly yes

这样做也不是不行,就是你输入命令的时候得把主机名改了。比如

git clone git@github.com:est/aether-pelican.git

你需要改成

git@estgit:est/aether-pelican.git

当然这还不是最蛋痛的。最蛋痛的是如果你用了 git submodules 那么你切换马甲变得非常麻烦。因为别人用你的项目没法解析 git@estgit 这样的玩意。

我研究出来了一个hack,直接改repo的 .git/config 可以达到同样的效果。比如

  [core]
      sshCommand = /usr/bin/ssh -o IdentitiesOnly=yes -i ~/.ssh/est_github -a
  [user]
      name = est
      email = ...@...

这样你可以随意在不同的repo切换n个 ssh identity 身份。

Posted

stdout

Rimworld 1.4 Biotech Xenogene/Endogene code names

I found out the corresponding gene code by accident, for Yuran Race mod it's located under

~/Library/Application\ Support/Steam/SteamApps/workshop/content/*/2844129100/Bio1.4/Defs/YuranBioTitle.xml

So the official description can be found at (or wiki):

~/Library/Application\ Support/Steam/SteamApps/common/RimWorld/RimWorldMac.app/Data/Biotech/Defs/GeneDefs/

I need to use the dev tool to modify gene of my pawn, so here's the table:

import os
import xml.etree.ElementTree as ET
p = os.path.expanduser('~/Library/Application Support/Steam/SteamApps/common/RimWorld/RimWorldMac.app/Data/Biotech/Defs/GeneDefs/')
fields = 'defName label description biostatCpx biostatMet biostatArc'.split()
print('| %s |' % ' | '.join(fields))
print('|--------' * len(fields) + '|')
for f in os.listdir(p):
    root = ET.fromstring(open(p + f).read())
    for elem in root.findall('GeneDef'):
        vals = [t.text if isinstance(t:=elem.find(x), ET.Element) else '' for x in fields]
        if vals[0]:
            print('| %s |' % ' | '.join(vals))

The result is:

defName label description biostatCpx biostatMet biostatArc
Hair_BaldOnly no hair Carriers of this gene grow no hair on the head.
Hair_ShortOnly short-haired Carriers of this gene can only grow short hair.
Hair_LongOnly long-haired Carriers of this gene grow hair on the head very quickly.
Hair_Grayless grayless hair Carriers of this gene keep their natural hair color as they age.
Beard_BushyOnly only bushy beards Male carriers of this gene experience rapid beard growth and are uncomfortable cutting their beards.
Beard_NoBeardOnly beardless Carriers of this gene grow no facial hair.
Beard_Always unisex beards Carriers of this gene always have thick facial hair, even women.
Skin_InkBlack ink black skin Carriers of this gene produce a pigment that turns their skin a pale black color almost as dark as ink.
Skin_SlateGray slate gray skin Carriers of this gene produce a pigment that turns their skin slate gray.
Skin_LightGray light gray skin Carriers of this produce a light-gray pigment in their skin.
Skin_SheerWhite sheer white skin Carriers of this gene have sheer white skin, unlike natural skin tones, due to a special engineered reflective cell covering.
Skin_Blue blue skin Carriers of this gene produce a pigment that turns their skin a blue color.
Skin_Purple purple skin Carriers of this gene produce a pigment that gives their skin a purple color.
Skin_PaleRed pale red skin Carriers of this gene produce a pigment that turns their skin a moderate red color.
Skin_DeepRed deep red skin Carriers of this gene produce a deep-red pigment that gives their skin an almost bloody appearance.
Skin_PaleYellow pale yellow skin Carriers of this gene produce a pigment that turns their skin a grayish yellow color.
Skin_DeepYellow deep yellow skin Carriers of this gene produce a pigment that gives their skin a deep yellow color.
Skin_Orange orange skin Carriers of this gene produce a pigment that gives their skin an orange color.
Skin_Green green skin Carriers of this gene produce a pigment that gives their skin a green color.
Furskin furskin Carriers of this gene grow thick fur all over their body, which protects them from cold temperatures. 1 -1
Eyes_Red red eyes Carriers of this gene have deeply red-pigmented eyes.
Eyes_Gray gray eyes Carriers of this gene have pale white-gray eyes.
Brow_Heavy heavy brow Carriers of this gene have a prominent brow. 0
Tail_Furry furry tail Carriers of this gene grow a fluffy tail which partially protects them from cold temperatures. 1 -1
Tail_Smooth smooth tail Carriers of this gene grow a slender tail that can act as a dexterous fifth limb. 1 -1
FacialRidges facial ridges Carriers of this gene grow raised ridges of skin on their face. 0
MinTemp_SmallIncrease cold weakness Carriers of this gene are slightly less comfortable in cold temperatures. 1
MinTemp_SmallDecrease cold tolerant Carriers of this gene are slightly more comfortable in cold temperatures. -1
MinTemp_LargeDecrease cold super-tolerant Carriers of this gene are much more comfortable in cold temperatures. -2
MaxTemp_LargeIncrease heat super-tolerant Carriers of this gene are more comfortable in warm temperatures. -2
MaxTemp_SmallIncrease heat tolerant Carriers of this gene are slightly more comfortable in warm temperatures. -1
MaxTemp_SmallDecrease heat weakness Carriers of this gene are slightly less comfortable in warm temperatures. 1
PsychicAbility_Deaf psychically deaf Carriers of this gene are deaf to all psychic energy and influence outside their own minds. They cannot be affected by psychic influence, nor can they ever wield psychic power. 2
PsychicAbility_Dull psychically dull Carriers of this gene are less psychically-sensitive than others. 1
PsychicAbility_Enhanced psy-sensitive Carriers of this gene are more psychically-sensitive than average. -2
PsychicAbility_Extreme super psy-sensitive Carriers of this gene are much more psychically-sensitive than most. 2 -5
MoveSpeed_Slow slow runner Carriers of this gene move more slowly than normal. 3
MoveSpeed_Quick fast runner Carriers of this gene move more quickly than normal. -3
MoveSpeed_VeryQuick very fast runner Carriers of this gene move much more quickly than normal. -5
Beauty_VeryUgly very unattractive Carriers of this gene have misshapen, asymmetrical facial structures and blotchy skin. They're hard to look at. 2
Beauty_Ugly unattractive Carriers of this gene have exaggerated facial features and poor skin that are generally considered ugly. 1
Beauty_Pretty attractive Carriers of this gene have unusually symmetrical, balanced facial features and extra-clear skin which gives them a pleasing appearance. -1
Beauty_Beautiful very attractive Carriers of this gene have remarkably precise and symmetrical faces. Their features are distinctive and strong without being exaggerated, and their skin is nearly perfect. They are generally seen as beautiful. -2
Learning_Slow slow study Carriers of this gene have deficient long-term memories and don't understand new ideas quickly. They are slow at learning new skills and knowledge. 2
Learning_Fast quick study Carriers of this gene have excellent memories and grasp new ideas quickly. They learn faster than others. 2 -3
Mood_Depressive very unhappy Carriers of this gene are highly predisposed to negative emotion. They'll see the bad in every situation and have a much lower mood than others. 5
Mood_Pessimist unhappy Carriers of this gene are predisposed to pessimistic perceptions. They'll tend to interpret things negatively and have lower mood than others. 3
Mood_Optimist happy Carriers of this gene are predisposed to optimistic feelings. They'll have higher mood than others. 2 -1
Mood_Sanguine very happy Carriers of this gene are highly predisposed to optimism and not at all inclined to think negatively. They'll have much higher mood than others. 3 -2
ToxResist_Partial tox resistance Carriers of this gene are resistant to toxic buildup from any source. This includes pollution, toxic fallout, tox gas, and direct attacks with venom or injected poison. They'll gain half the amount of toxic buildup compared to others.\n\nCellular filters in the lung and skin reduce the dose of toxins entering the bloodstream. -2
ToxResist_Total tox immunity Carriers of this gene are totally immune to toxic buildup from all sources including polluted terrain, toxic fallout, tox gas, and direct attacks with venom or injected poison. They are also not bothered by acidic smog.\n\nThe carrier's biochemical pathways are modified to route around interference from nearly all known toxins. Along with enhancements to the kidneys and liver, this keeps carriers comfortable in even the most toxic of environments. 2 -4
Delicate delicate Carriers of this gene take greater injuries than others from the same damage. They have thin, brittle bones and less binding molecules in joints and flesh. 3
Robust robust Carriers of this gene take less injuries than others from the same damage. They have thickened, densified bones, nearly-solid ribcages, and strengthened binding factors in joints and flesh. -2
Pain_Reduced reduced pain Carriers of this gene feel half as much pain compared to a baseliner. Reduced neuron activity in the brain's nociception centers makes pain dull and faint. This can be advantageous sometimes, and dangerous other times. -1
Pain_Extra extra pain Carriers of this gene feel more pain than others given the same injuries. Neuron activity in the brain's nociception center is amplified, so pain feels extra-intense and fiery. This can be protective, but overall it's considered a negative and makes it hard to push through difficult situations. 2
Aggression_DeadCalm dead calm Carriers of this gene feel calm in every situation and have a very placid demeanor. They will never start social fights or have aggressive mental breaks. -1
Aggression_Aggressive aggressive Carriers of this gene are quick to anger. They are twice as likely to start social fights. When they have mental breaks, they are twice as likely to choose an aggressive kind of break. 2
Aggression_HyperAggressive hyper-aggressive Carriers of this gene are hormonally high-strung and very aggressive. They are three times as likely to start social fights. Any mental break they have will be of an aggressive type. 3
VerySleepy very sleepy Carriers of this gene get tired much faster than others. 4
Sleepy sleepy Carriers of this gene get tired somewhat faster than others. 2
LowSleep low sleep Carriers of this gene get tired less quickly than others. 2 -4
Neversleep never sleep Carriers of this gene have a unique metabolic process which allows clusters of neurons to sleep while the rest of the brain stays awake. They never need to sleep. 3 -6
MeleeDamage_Weak weak melee damage Carriers of this gene do less damage in close-quarters combat. Weak fast-twitch muscle fibers make their strikes shaky and weak. 1
MeleeDamage_Strong strong melee damage Carriers of this gene do more damage in close-quarters combat. Extra-strong fast-twitch muscle fibers make their strikes accurate and powerful. -2
UVSensitivity_Mild mild UV sensitivity Carriers of this gene have biological compounds in their skin that react painfully to UV radiation. They are unusually sensitive to sunlight. 3
UVSensitivity_Intense intense UV sensitivity Carriers of this gene have biological compounds in their skin that react dangerously to UV radiation. They are intensely sensitive to sunlight. 2 4
Libido_Low low libido Carriers of this gene are less likely to engage in lovin' with their partner.
Libido_High high libido Carriers of this gene are more likely to engage in lovin' with their partner.
FireSpew fire spew Carriers are able to spew flammable bile generated by a special organ in their neck. The bile sticks to anything in a small area and can ignite people, objects, and the ground. -2
FoamSpray foam spray Carriers grow glands in the neck that generate and store a fire-retardant foam. They can spew this foam over an area to extinguish fires. -2
LongjumpLegs longjump legs Carriers have special hemogen-powered muscle fibers in their legs which allow them to jump great distances. -2
AnimalWarcall animal warcall Carriers of this gene can perform an animal warcall, using a powerful bellow and psychic connection to call an animal to fight for them. 1 -3
Bloodfeeder bloodfeeder Carriers of this gene have small retractable fangs and an organ on the roof of the mouth which can extract hemogen from fresh warm blood. They can bite an unresisting person, suck the blood, and gain hemogen directly. -1
Coagulate coagulate Carriers of this gene have special glands on their hands and wrists, as well as a unique salivary compound that they can use to rapidly tend wounds. -1
XenogermReimplanter gene implanter Carriers of this gene can implant a copy of their xenogerm into another person through a somewhat gross-looking injector organ. Their own genetic material will then regrow very slowly. If they implant while their genes are regrowing, they will die. Germline genes will be unaffected. 3 1
PiercingSpine piercing spine Carriers grow an opening in their upper chest along with a quiver of keratin spines. Using a hemogen-powered chemical reaction, they can fire these spines at high speed at nearby targets with surprising accuracy. -1
AcidSpray acid spray Carriers grow glands in the neck that generate and store a sticky acid substance, along with acid-tolerant tissues in the mouth. They can spew this acid over an area, where it will stick to enemies and burn them over time. -2
Body_Fat fat body Carriers can have fat bodies. A person can have more than one body type gene; one body type will be chosen among those that are allowed.
Body_Thin thin body Carriers can have thin bodies. A person can have more than one body type gene; one body type will be chosen among those that are allowed.
Body_Hulk hulk body Carriers can have large bodies. A person can have more than one body type gene; one body type will be chosen among those that are allowed.
Body_Standard standard body Carriers can have average-shaped bodies. A person can have more than one body type gene; one body type will be chosen among those that are allowed.
Ears_Human human ears Carriers of this gene have regular human ears.
Ears_Pig pig ears Carriers of this gene will grow pointed pig-like ears.
Ears_Floppy floppy ears Carriers of this gene grow long, floppy hound-like ears.
Ears_Cat cat ears Carriers of this gene have cat-like ears.
Ears_Pointed pointed ears Carriers of this gene have pointed ears.
Nose_Human human nose Carriers of this gene have regular human noses.
Nose_Pig pig nose Carriers of this gene have pig-like snouts.
Jaw_Baseline human jaw Carriers of this gene have regularly-shaped jaws.
Jaw_Heavy heavy jaw Carriers of this gene have large jaws.
Head_Gaunt gaunt head Carriers of this gene have a pinched, gaunt appearance in their face and head.
Hands_Human human hands Carriers of this gene have regular human hands. 0
Hands_Pig trotter hands Carriers of this gene have hands that partially resemble pig trotters. This reduces their ability to manipulate objects. 1 1
ElongatedFingers elongated fingers Long, delicate fingers improve the carrier's manipulation capacity. This aids with many tasks, especially crafting and construction. 1 -1
Headbone_Human human headbone Carriers of this gene have regular human skulls.
Headbone_MiniHorns mini-horns Carriers of this gene grow two small horns protruding from the forehead.
Headbone_CenterHorn center-horn Carriers of this gene grow a single horn protruding from the center of the forehead.
Voice_Human human voice Carriers of this gene have regular human vocal chords.
VoicePig pig voice Carriers have a squealing voice like that of a pig.
VoiceRoar roar voice Carriers have an animal-like roaring voice.
Hemogenic hemogenic Carriers of this gene have a reserve of biological strength powered by a resource called hemogen. The resource can be gained and spent in various ways, all of which are unlocked by other genes.\n\nCarriers lose 2 hemogen per day from biological entropy. 1 1
HemogenDrain hemogen drain Carriers lose an additional 8 hemogen per day from biological entropy. 1 6
FireWeakness tinderskin Carriers have dry, thin skin which burns easily from fire, and their immune systems react very poorly to this kind of threat. Damage from fire is multiplied by 4. 2
FireTerror pyrophobia Carriers of this gene have an intense fear of fire. When fires are close, there is a chance they will have a mental breakdown at any moment. 4
PerfectImmunity perfect immunity Carriers of this gene have archite-enhanced immune systems which intelligently destroy invaders. They are totally immune to most normal illnesses. 3 1
DiseaseFree non-senescent Carriers of this gene do not go through senescence in the normal way. They never get chronic age-related diseases like cancer, bad back, cataracts, or dementia. 3 1
TotalHealing scarless Carriers of this gene have a special type of regenerator cell which can heal old wounds and chronic illnesses like bad back. 4 1
Deathrest deathrest Carriers of this gene must periodically regenerate themselves in a special coma called deathrest. Deathrest takes days, but can confer substantial bonuses. Deathrest can be accelerated and its effects enhanced by the use of a variety of special buildings and technologies.\n\nThose who put off deathresting will suffer from deathrest exhaustion. 6
Ageless ageless Carriers of this gene have archites in the bloodstream which continuously reverse the process of aging. Starting at the age of 13, carriers begin to biologically age slower. By 18, the aging process stops completely. 3 1
Deathless deathless Carriers of this gene have archites in the blood which will sustain their life processes no matter what. As long as the brain remains intact, a carrier of this gene will never die. 7 1
ArchiteMetabolism archite metabolism Carriers of this gene have special archites in their cells that facilitate and optimize metabolism. This improves overall genetic and metabolic quality. 6 6 2
WoundHealing_Slow slow wound healing Carriers of this gene heal from wounds half as fast as normal. 2
WoundHealing_Fast fast wound healing Carriers of this gene heal from wounds twice as fast as normal. -2
WoundHealing_SuperFast superfast wound healing Carriers of this gene heal from wounds four times as fast as normal. -3
Immunity_Weak weak immunity Carriers of this gene gain immunity to diseases more slowly than normal. They may die from infections that others would survive. 2
Immunity_Strong strong immunity Carriers of this gene gain immunity to diseases faster than normal. -1
Immunity_SuperStrong super immunity Carriers of this gene gain immunity to diseases considerably faster than normal. 2 -2
ToxicEnvironmentResistance_Partial partial antitoxic lungs Carriers of this gene are resistant to environmental toxins. They get less toxic buildup from tox gas, polluted terrain, and toxic fallout, but are still vulnerable to direct attacks with venom or injected poison. Additionally, they build up rot stink exposure slower. -1
ToxicEnvironmentResistance_Total total antitoxic lungs Carriers of this gene are immune to environmental toxins, but not from direct toxic attacks. They get no toxic buildup from tox gas, polluted terrain, or toxic fallout, and they are not bothered by acidic smog. They are still vulnerable to direct attacks like venom and injected poison. Additionally, they are immune to rot stink exposure. 2 -3
Sterile sterile Carriers of this gene cannot reproduce by natural means. 1
Fertile fertile Carriers of this gene have a higher chance of becoming pregnant or impregnating others.
Superclotting superclotting Carriers of this gene have extra-power coagulating factors in their blood, and will stop bleeding very quickly when wounded. -1
KindInstinct kind instinct Carriers of this gene are high in trait agreeableness and are very conscientious. They rarely insult others and will sometimes offer kind words to brighten the moods of those around them. They also never judge people by their appearance. -1
ViolenceDisabled violence disabled Carriers of this gene are emotionally and mentally incapable of engaging in violence. They are overwhelmingly resistant to and horrified by the idea of hurting another. 3
Nearsighted nearsighted Carriers of this gene have difficulty seeing at a distance. Their shooting accuracy at long ranges is reduced. 2
StrongStomach strong stomach Carriers of this gene have an extra toxin-filtering organ in their stomach and will never suffer from food poisoning even after eating rotten food. -1
DarkVision dark vision Carriers of this gene see well in low light and are unaffected by mood penalties related to darkness. They have a reflective layer behind the retina that amplifies their ability to see in the dark. -1
KillThirst kill thirst Carriers of this gene lust for the feeling of ending another's life. They will become irritated if they go for too long without killing someone in close combat. 4
FireResistant fire resistant Carriers of this gene have special fast-acting sweat glands and heat-resistant skin. They only take 25% of the normal damage from fire. The chance of them catching on fire is also drastically reduced. -2
Inbred inbred This genetic condition affects a person's fertility, immunity, and mental capacity. -2
RobustDigestion robust digestion Carriers of this gene grow a multi-fold stomach, allowing them to digest raw foods more efficiently than baseline humans. In general, they get the same nutrition from raw food as from if it is cooked. They also don't mind the taste of raw food at all. 2 -2
Instability_Mild mild cell instability Carriers of this gene need less metabolic energy to stay alive, at the cost of reduced stability in their cell-replication machinery. 2
Instability_Major major cell instability Carriers of this gene need much less metabolic energy to stay alive, at the cost of greatly-reduced stability in their cell-replication machinery. 4
PsychicBonding psychic bonding Carriers of this gene have a special neural organ that makes them psychically bond with a lover for life. As long as the lovers are together, they will be happy. If they are physically separated, they will be disturbed by the distance. If one dies, the other's mind will be badly disrupted. 1 -1
PollutionRush pollution stimulus Carriers of this gene get a chemical rush from being exposed to pollution. This makes them move faster and helps them think clearer. A similar gene is found in combat-engineered mega-insects. 1 -1
Unstoppable unstoppable Carriers of this gene are not slowed down when taking damage. 1 -2
NakedSpeed naked speed Carriers of this gene move slower while clothed, and faster while naked. 1 2

Posted

stdout

如何在出远门的时候关闭洗碗机定时启动

家里有个「美的」的某型号洗碗机,一般是积累了当天的碗筷餐具,每天23:00低谷电价之后自动开始定时洗碗。这个功能可以在app上设置实现,还可以设置烘干和通风保存,第二天就能拿出来洁净且干燥的碗筷使用,平时日常这样用起来挺不错。

但是这也导致一个问题,如果节假日出门旅行几天,这个洗碗机里即便没有碗筷,也会傻傻的启动浪费水电,所以需要禁用几天,我的操作流程是:

  1. 掏出手机,解锁屏幕,找到「美的美居」 app并打开
  2. 欣赏该厂家运营设置的精美开屏广告并等待
  3. 打开「场景」
  4. 找到自动化 - 已开启 列表里,关于洗碗机的部分
  5. 找到进入每天自动洗碗的选项,编辑,选择关闭
  6. 保存设置,退出 app
  7. 回到家,又需要按照上面的流程操作一番启用该流程

每次想起这个事,真是又繁琐又蛋痛。特别是回来如果忘记启用,第二天早上起来会发现一篮子未洗的碗筷傻眼。

这次五·一假,我压根忘记了禁用定时洗碗的事。但是回到家添加洗碗粉的时候发现,这几天洗碗机并未启动。问了下是我老婆操作的,她的流程是:

  1. 给洗碗机门板开一条缝

洗碗机不会在门没关严的情况下启动,所以。。。。

我问她这样做是故意的还是不小心的,她说故意不小心的。

Posted

stdout

当前版本gpt的根本弱点

下面的东西仅限当前,不是不可以解决的。

  1. gpt系列数学能力不行,是因为它把每一个数字当成一个整体在背加法表、乘法表。没理解到十进制的精髓

上图来自2020年 GPT-3 论文 22页。主要还是因为 BPE 太糙。

  1. gpt-4能通过一些文字材料和描述感知到每个字母大概长什么样,甚至知道一些简单汉字的结构,但是确切的书写结构它是不知道的。
    所以要避免你的想法被 gpt 感知学会,得考虑每个字的偏旁部首作文章,而且你的变形得很少见。估计这个技巧在将来被AI监视的生活里会被用得上。

  2. 还有一些语音漂移它知道概念但是因为没发音器官所以不能直接感知。但这也不是不能解决,只要语料够大也能摸到规律。相比英语等拼音文字而言,汉字这类表意但是又有同音的文字应该是文本类 AI 的普遍弱点。

如果你要秘密表达一些观点,可以通过描述发音、形状或者动作但是不直接写出来让对方领会。

Posted

stdout

Google 和 Facebook 为什么不行了

Google 最先搞出来 word2vec,最先搞出来transformer 和 BERT,最先搞出来被员工发现 sentient 的 LaMDA,被 ChatGPT 骑脸之后匆忙推出个半成品 Bard

这一切为啥呢?我觉得很可能是 Google的愿景

Google's mission is to organize the world's information and make it universally accessible and useful.

全世界的信息,可以说已经被 Google 成功的「组织」起来了。只不过很可惜,它并没有想要全部「理解」和「消化吸收」,把信息变成「通识」。ChatGPT 正在尝试做到这一点。

微软的愿景是什么呢?

  • "Be what's next." (2010-2012)
  • "Empowering us all"

所以它很快收购了 Skype 推出 Teams,收购 Github 然后投资 OpenAI,结合 Codex (code-davinci-002) 推出 Github Copilot,然后顺理成章搞出来 Office 系列的 Copilot。工具性拉满。

然后说下为啥 Facebook 要 All in metaverse。这个在 2015-06-22 有个 leaked memo 说得很清楚

Our vision is that VR / AR will be the next major computing platform after mobile in about 10 years. It can be even more ubiquitous than mobile – especially once we reach AR – since you can always have it on. It’s more natural than mobile since it uses our normal human visual and gestural systems. It can even be more economical, because once you have a good VR / AR system, you no longer need to buy phones or TV’s or many other physical objects – they can just become apps in a digital store. ... We are vulnerable on mobile to Google and Apple because they make major mobile platforms. We would like a stronger strategic position... We can achieve this only by building both a major platform as well as key apps.
我们的愿景是,在大约十年后,VR / AR将成为继移动设备之后的下一个主要计算平台。它甚至可以比移动设备更普及 - 特别是一旦我们达到AR - 因为您可以随时随地使用它。它比移动设备更自然,因为它使用我们正常的人类视觉和手势系统。它甚至可以更经济,因为一旦您拥有了一个好的VR / AR系统,您就不再需要购买手机、电视或许多其他物理物品 - 它们只能成为数字商店中的应用程序。我们在移动设备上对谷歌和苹果公司非常脆弱,因为它们制作了主要的移动平台。我们希望拥有更强大的战略地位... 我们只有通过建立一个主要平台和关键应用程序才能实现这一点。

问题是,VR/AR 并不是手机的下一代。

Posted

stdout

Play Cities:Skylines on Windows/MacOS without Paradox Launcher

Haven't played Cities: Skylines for ages, so I re-installed it on Steam, after some updates there's this new Paradox Launcher which serves no purpose but wasting time. So I decided to remove it, googled some guide and unfortunately it contains too many steps and some error occured while following it. Here's the simpler & correct step of what I did instead.

After the game is downloaded, open the Steam library, find the game, right click, choose Properties...

Next for the Launch Options, type

on Windows

cmd /c start cities.exe %command%

on MacOS

/Users/$USER/Library/Application\ Support/Steam/steamapps/common/Cities_Skylines/Cities.app/Contents/MacOS/Cities %command%

Make sure you replace $USER with your username

Then the game works like good o' times, straight to the menu.

Posted

stdout

《阿凡达2:水之道》是一部辱日片啊

昨天刚看完,整体感觉画面还是美轮美奂的。我没看出来有什么故弄玄虚的情节,也没觉得网上说那些故事性不行到底不行在哪里。不过有很多场面感觉不是怎么适合带娃去看,好多暴力、流血、残忍包括几十秒展示捏碎一个真正的骷髅等镜头。

在其中一个 Tulkun Hunting 大场面,一开始还对为啥找个东亚面孔扮演反派感到奇怪

avatar2 whaling crew

然后就出现了好几秒的「日捕」爆炸捕鲸叉的特写。这是把「日本捕鯨協会」写脑门上了啊。。。

日捕

截图来自tiktok不是很清晰。但是这妥妥辱日了吧。。。说阿凡达2不好看的,是不是拿了日本外务省的钱?233333

看完网上搜了下讨论,有人说这是 日浦 Hiura 的名字,但是这又不是一个常见的日本姓名 ,所以我觉得 James Cameron 这故意用个错别字避免刚正面。

现实中的日本捕鲸叉长这样

japanese whale harpoon

十分写实了。而且捕鲸一开始也是为了鱼油,而且日本捕鲸也是冒充科研用途,和电影里的情节不能说雷同只能说。。。一模一样?

Posted

stdout

文字的毒害

看到个号称不支持 css/js/wasm 和图片的浏览器 Kristall,觉得这玩意太蠢了。这让我
想起柏拉图的 Phaedrus 里讲了苏格拉底的一个段子,苏格拉底作为欧亚大陆的头号智慧导师,博学多才,却没留下传世著作。因为但是他老人家本身是反对文字和书写的,有这么几个原因:

第一条,文字伤害记忆和智慧。Letter is an aid not to memory, but to reminiscence, and you give your disciples not truth, but only the semblance of truth

首先值得注意的是,这里很有可能指的是拼音文字里的「字母」 而不是古埃及神 Theuth 创作的象形文字。我认为发音字母构成的书写体系肯定是对记忆有害的,文字上的词性和变位更是对视力和理解力的低效率的折磨。快速理解都会强调 Subvocalization 的重要性。汉字作为一个 ideogram 真是一个神发明。总体来说,这条道理是对的。文字只是记忆的粗略模拟和辅助,是真理的外表轮廓。

知识其实这玩意可以被大致分为两类:propositional knowledge 和 know-how。命题和过程知识。

什么是命题?比如「一只青蛙四条腿」就是典型的命题。人们可以根据生活经验获得大量命题;

过程知识就比较微妙了。人们可以通过文字获得过程知识,比如你可以通过学习五线谱了解乐谱如何和发音一一对应,观看钢琴视频得知乐器如何演奏,但是让你实际上手呢?依然不会。

文字就容易造成一个错觉,把结论和过程的「描述」记住了,不等于你获得了真实的知识。有的时候甚至你记下来的就是个结论,连它内在逻辑都无法知晓。孔老夫子就说过「学而不思则罔,思而不学则殆」。文字是有欺骗性的。很多时候你写下来了背下来了以为就记住了。实际上你只记住了一个表皮。

第二条,文字是固化的,死气沉沉的,不如口头语言丰富有活力,不如口传心授有感染力。这个理由,也有局限性。因为文字表达能力在苏格拉底的时候不行,但是这玩意可以进化的。几千年演化下来,文字的表达能力一点也不差。

第三条,文字使语言失控。苏格拉底的原话是这么说的:“一件事一旦被写下来,不论什么内容,到处都会流传的,既会传到能看懂的人的手里,同样也会传到无关的人手里。文字本身并不知道如何与正直的人说话,也不知道如何不与邪恶的人说话。因为文字没有自卫或自救的能力。” 这个道理其实非常值得深思。

书写不是真理的后代,而是真理的私生子。人们歪曲理解文字,就如同私生子受到欺负没有亲生父母帮忙一样。苏格拉底还说,智慧的语言是用来雕刻学习者的心智的。需要知道什么说什么话,什么时候闭嘴。知识是活的,有多面性,需要对听众定制诉说,而不是像一副绘画那样只从一个角度说明问题。理智的人说话就像在花园里埋下一颗种子,听者心里才会开花结果。而不是一味挖洞翻土。

道理讲了这么多,其实对我的启发就是传播思想。喊死板口号是绝对没有用的。必须得定制化、个性化传播。如同现在推荐系统一样,做到千人千面。真正厉害的营销和洗脑不是「羊羊羊」那样反复重复洗脑,而是静心巧妙的植入。

想到这里,我觉得,以前 PC 时代发布视频,是由少数精英团队的制作,通过 Flash/MPEG这种录制成视听作品或者节目,扩散式的单向散开传播;3G 4G 带来的高带宽普及,智能机带来的H.264专用处理芯片的普及,让人人拍视频成为了可能,让全球迎来了一个视频传播思想的时代。大家看不起的营销号洗稿行为,在我看来是一个极其合理必然。知识的传播,本来就应该自然发生变异,我们只是缺乏一个有效的优胜劣汰的定向过滤器。把一件事前因后果用文字写清楚的人不多,但是文盲都可以拿起手机录制一段讲话。所以在人人都能发视频的时代,打破了文字的垄断,带来大量的土味和「俗」味视频。因为媒介的改变,不仅是从文字到图片、视频的升级那么简单,而是人和人对话、交流、碰撞的一次彻底颠覆;以前的大道理、小道理是基于文字的浓缩,抽象成一个又一个的符号,比如国家,比如民族,比如儒家、清教徒这种门派。现在抛弃抽象,回归到具象。在文字的时代,搜索引擎为王。因为这种技术有一定门槛,而且当时互联网上全是「超文本」的海洋。高校的理论知识是网页,门户的新闻是大段文字,个体用户参与的 BBS 讨论也是文字。现在不一样了,学术报告是扫描版pdf,门户都是app里的walled-gargen,群众的议论全是长截图。文字沦为配角,作为字幕存在于某一帧配图的下方,或者是一个箭头指向的注解。最具冲击力的,往往是影像,比如唐山打人的监控 footage,再比如导致 BLM 的那张 Floyd 跪脖子的图片。

社会现代化意味着传统、稳定的社区纽带被打散,现代人的生活成为一场漫长的“流浪”,人们不断被抛入陌生的地点、陌生的群体、陌生的关系,“独自承受”一切挑战。这种原子化状态驱动着弗洛姆所说的“逃避自由”心理——人们试图在不断分崩离析的世界中抓住一点什么,哪怕抓住的仅仅是“想象的共同体”。

从这一点上来说,我们回到了千百年前那个知识以口口相传的时代。面对这样的历史巨变,我个人的见解是:

  1. 口头交流比任何一个时代都更加重要。中小学应该压缩文字书写的时间,改为制作 ppt 宣讲技能培训和口头辩论。
  2. 应该把音韵、对联、单押、双押、rap、music、的重要性提高。现在自媒体 BGM 水平太低,而且说服力和韵脚好坏成正比。
  3. ChatGPT 是一把双刃剑,既可以在一段文字里无缝植入商品广告,也可以解决苏格拉底反对 letters 提出的文字的种种缺点,把文字变成个性化、启发式学习一个利器。
  4. 下一代说服力工具,应该是类似 ChatGPT 但是作为虚拟形象对现实生活的再加工和演绎。技术侧需要有对图片和视频「表达的思想」的理解能力。

Posted

stdout

Jira里JQL实现查找上一个「工作日」的任务

厂里终于开始用笨拙的Jira了。总体用下来跟 Teambition 相比各有各的笨处。。。

默认的 board 过滤器有点不好用。本着为了stand-up meeting和周报快速检索上一个工作日和当周干了什么,找到一个 filter 写法:

JQL过滤上一个工作日干了啥:

(updatedDate < endofweek("-8d") AND updatedDate > startofday("-3d")) OR updatedDate > startofday("-1d")

这里不是简单的查昨天干了啥。比如周一需要看周五干了啥。所以有个 -8d-3d 的神奇操作。具体的逻辑自己琢磨

过滤本周干了啥

updatedDate >= startOfWeek(0)

Jira这种资本主义软件是没法适配我们社会主义法定节假日的设定。所以遇到非双休放假还是判断起来比较蛋痛。

其实我比较反感每天早上开站会。我比较推荐每天下班前最后10分钟开会。好处有:

  1. 当天干了什么记得很清楚。明天需要干什么也很显然。
  2. 如果谁拖堂,谁就承担对不起大家不能准时下班的道德压力
  3. 如果都开会了你事情都还没做完,要么你事情安排得太多,要么你完成能力不足,要么你时间安排有问题。

之前在两个公司这样执行过。结果被大老板强行改到早上开会了。无语。

Posted

stdout

Web Animation实现页面逐渐变灰

在2006年我开始网上留下印记的时候,写了一个 dHTML 特效模拟XP关机对话框变灰, 那个时候大行其道的还是IE6,用的还是微软特有的 filter:progid:DXImageTransform.Microsoft.Fade 叠加两个<div>实现。

今天(2022-11-30)恰好长者去逝,学习一下最新的css姿势再实现一次。本来想用 CSS Animation+Filter实现,还是比较麻烦。比如我参考的例子是模仿 Red Dead Redemption 2 照片效果css

  #invert{
    filter: invert(1.0) grayscale(1.0);
  }
  #photo{
    animation: blur 5s infinite alternate;
  }
  @keyframes blur{
    from{
      filter: blur(3px);
      opacity: 0;
    }
    to{
      filter: blur(0px);
      opacity: 1;
    }
  }

这个方式有个问题就是需要单独设置一个 <script> 元素。后来经过 @yuanchuan23 的指点发现可以通过 Web Animation 更简单的实现:

  document.body.animate([
    {filter: 'brightness(none) grayscale(0%)'},
    {filter: 'brightness(10) grayscale(10%)', offset: 0.2},
    {filter: 'brightness(1) grayscale(100%)'}
  ], {duration: 2000, fill: 'forwards'})

这样写比 css 方便多了。加一个类似照相机闪光灯过曝的效果。其中 fill: 'forwards' 可以让变灰之后停下来。

放一个 demo 在这里:https://lab.est.im/grayscale_animation 点一下可以再变一次

Posted

stdout

8行javascript录制屏幕

看到个骚操作,玩了一下,写了个 bookmarklet

navigator.mediaDevices.getDisplayMedia({video:true}).then(function(stream){
  const mr=new MediaRecorder(stream,{mimeType:"video/webm;codecs=h264,opus"});
  mr.ondataavailable=function(ev){
    const a=document.createElement('a');a.href=URL.createObjectURL(ev.data);
    a.download ='screen_capture.webm';a.click();
  }; // will be called when .stop() with ev.data as a Blob
  mr.start();
})

这段代码也是很多WebRTC共享白板的实现原理。看起来也很简单,而且不需要额外的权限确认。

如果不需要另存为一个名字,则可以直接 location.assign() 又节约几个字。不知道还有没有办法继续节约代码量?

有点很好奇为啥chrome不支持 .mp4 封装。偏袒自家的 webm ?

Posted

stdout

JS播放 DTMF

玩 WebRTC 的时候发现它居然内置支持了 DTMF 拨号音

这里就简单科普一下,DTMF 就是手机电话拨号音,数字按键按下去嘟嘟嘟响那个。具体就2个频率调谐:

DTMF 1209Hz 1336Hz 1477Hz 1633Hz
697Hz 1 2 3 A
770Hz 4 5 6 B
852Hz 7 8 9 C
941Hz * 0 # D

于是兴趣来了想做一个 demo 玩玩,写了半天调试不通,报错

VM987:1 Uncaught DOMException: Failed to execute 'insertDTMF' on 'RTCDTMFSender': The 'canInsertDTMF' attribute is false: this sender cannot send DTMF.

仔细研究了下这玩意,原来 WebRTC 不直接传音频,而是发一个控制信号,由接收方播放出音频,所以你需要本地创建一个真实的双工 RTC 并打开麦克风权限,才能播放DTMF音频。

WebRTC doesn't send DTMF codes as audio data. Instead, they're sent out-of-band, as RTP payloads. Note, however, that although it's possible to send DTMF using WebRTC, there is currently no way to detect or receive incoming DTMF. WebRTC currently ignores these payloads;

这样就走远了。于是又手痒用 AudioContext() 糊了一个。一共不到1000字节。

https://lab.est.im/dtmf 源码

嗯。就挺简单的。特别是那个 oscillator有个 .stop(0.2) 参数可以避免 setTimeout 的麻烦。网上很多教程整复杂了。

btw 把一些老脚本挂在 lab 域名下。
btw2 把 RSS 改成全文输出了。

Posted

stdout

Cloudflare worker 返回浏览器ip:端口

看到个贴 返回客户端连接用的 IP 和端口号,想起来也需要熟悉一下 Cloudflare worker,于是拿来练练手

  export default {
    async fetch(request, env) {
      return await handleRequest(request).catch(
        (err) => new Response(err.stack, { status: 500 })
      )
    }
  }

  async function handleRequest(request) {
    const { pathname } = new URL(request.url);

    if (pathname === "/ip") {
      const ip = request.headers.get('CF-Connecting-IP');
      return new Response(ip + '\n');
    }

    if (pathname === "/ip:port") {
      const ip = request.headers.get('CF-Connecting-IP');
      const port = request.headers.get('est-Connecting-Port') || '?'
      return new Response(ip + ':' + port + '\n');
    }

    return new Response('Tools:\n /ip\n/ip:port\n');
  }

遇到一个问题,Cloudflare 官方有提供浏览器客户端IP变量 CF-Connecting-IP 但是缺少端口,查了下可以自己通过 cf.edge.client_port 这个变量获得, 方法是在进入 CF网站管理 面板 → Rules → Transform Rules → HTTP Request Header Modification 里添加一条请求头规则。如图:

但是 header 不能以 CF- 开头,所以这里改成 est-Connecting-Port,就能获得客户端请求的 IP+端口 了

测试地址: t.本网站根域名/ip:port

目前还缺:IPv6 的正确表示。。。。

Posted

stdout

macOS动态定时弹提醒

上班地方有个付费计时,想在倒计时结束前在电脑弹个提醒,手动结束计费,趴下来API了。接下来就是如何弹窗了。

本来想用macOS自带的 UNUserNotificationCenter 通过 PyObjC 撸个弹窗,遇到两个问题:

  1. 系统自带的 PyObjC 太老了。还是Python2.7的。在/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
  2. 只能兼容旧款的 NSUserNotification,状态为 macOS 10.8–11.0 Deprecated
    新的API调用需要进程签名。
    codesign -dv --verbose=4 /usr/bin/python2.7

只有官方的python2.7签名了 anaconda/miniconda 的都没签名。算了。还是直接 AppleScript 走起

  osascript  -e 'display notification "还有1分钟到达时辰" with title "准时付费" sound name "Frog"'

想在这个提示里加一个 snooze 1分钟功能,但是好像无法支持。罢了。2333

Posted

stdout

终于吧 blog 的自动构建 pipeline 配置好了

目前博客是基于 pelican 的 static-site generator,一个 python 模块本地渲染成静态文件然后通过 github pages 发布。

源码放在 bitbucket,之前比较懒都是本地跑,一直想改成 CI/CD pipeline,今天终于配置好了。记录一些坑吧

  1. bitbucket pipeline 不同 step 之间数据是不共享的。本来想用 parallel 功能在下载 pip 模块和 git clone 皮肤做个并行,后来发现 artifact 拷贝速度还不如串行去跑。就所有操作一个 step 做完
  2. 博客源码和生成结果可以直接同步提交信息:

    msg=$(git log -1  --pretty=%B)
    cd output
    git config user.name est
    git config user.email 邮箱
    git add .
    git commit -m "$msg"
    git push
    
    1. 由于 pip 模块装了不知道在哪里,所以调试 pip 安装路径方法:

      python -c 'import site; print(*site.getsitepackages(), sep="\n")'

  3. pelican 默认居然没支持 Markdown 也是醉了

    python -m pip install pelican==4.8.0 Markdown
    
    1. 自定义皮肤依赖,由于 submodule 我没玩转,所以这样安装:

      git clone --depth=1 git@github.com:est/aether-pelican.git || (cd aether-pelican; git pull --rebase)

Bitbucket 每个月有50分钟的免费pipeline 时间,自己用下来差不多29秒 build & publish 一次。感觉每个月也写不了60篇,所以目前是够了。

接下来的优化:

  1. 新图片通过 squoosh 压缩优化
  2. 通过 cloudflare worker 替换掉 disqus 评论功能

Posted

stdout

袁亚湘院士数学不错,但是历史不行

网上看到一个院士的段子 1 2

搜了下,2020年3月14日,在中国工业与应用数学学会举办的网络科普活动中,中国科学院院士袁亚湘带来题为“数学漫谈”的主题报告

https://mp.weixin.qq.com/s/JllGeuveomjFDFg3C5r9FQ

关于π有很多神奇的故事。因为时间关系,我今天就讲其中的一个。不知道在座的观众有没有看过一个美剧叫做《疑犯追踪》。在第2季11集中,Harold Finch说过在π里面能够找到任意数列。当然这个东西数学家并没有证明,但是很多数学家认为可能是真的。
我试了试,我挑了我们建党的日子19210701,出现在π的第44,842,733位。如果输入去中华人民共和国成立之日,也就是19491001的话,就要往后很多,要到82,267,377位。开个玩笑,π都说明了要先有共产党才有新中国。
一个网友要求我要查一下1314,大家看到1314到3902位就找到了。所以各位观众,1314(一生一世)不是那么难啊。但是如果1314前面加个520(我爱你)的话,那就难多了。如果你要找5201314,那就要查到200多万位。所以同学们一定要记住啊,实际上爱情还是很艰难的。

这段话数学上来说是没问题的,但是院士可能没注意历史,建党的真正时间是一大正式召开的时间,1921年的7月23日

那么我们把两个时间再去看一下在 Pi 里的位置:

https://www.angio.net/pi/

  The string 19491001 occurs at position 82267377
  The string 19210723 occurs at position 101114100

所以这说明了啥?

Posted

stdout

Add UTF-8 BOM header to Flask-Admin export

A simple trick to add additional bytes prepending Flask's stream_with_context

  from flask_admin.contrib.sqla import ModelView
  from itertools import chain

  class MyAdminView(ModelView):
      can_export = True
      column_export_list = ['field1', 'field2']

      def _export_csv(self, return_url):
          r = super(MyAdminView, self)._export_csv(return_url)
          r.response = chain((b'\xef\xbb\xbf',), r.response)
          return r

I am still using Python2 and Flask-admin shit. It's a shame but anyway.

Posted

stdout

牛津树/Good English/典范英语里的宗教私货

牛津树 Oxford Reading Tree 是被国内咪蒙妈妈们吹得油爆爆的来自英国的少儿学习体系,Good English/典范英语 是中青出版社的部分摘录英语教材。

偶然发现这个 牛津树【4-29】Mosque School,讲了一个叫 Adam 的学龄前儿童机缘巧合进了经文学校的短故事。甚至如果这是从古兰经某个传教段子改编出来的我一点都不惊讶。

引起我注意的是小白帽的装束,以及牌子那几个字 Masjid-E-Noorul Islam

费了点心思搜了下,也拼为 Nurul IslamNur ul-Islam,意思是 light of Islam 伊斯兰之光

国内很多中专职高出来的英语老师可能没理解这里面的内涵。什么叫潜移默化植入意识形态啊?!当人们觉得这是文化「多样性」很正常?!以为清真学校就是普通的讲宗教的学校,其实经文学校传授的东西非常不简单。摘抄一些百科:

经文学校分为“地尼买克塔普”、“买德里斯”、“卡里哈纳”三种。
经文小学是中国伊斯兰教经堂教育建制之一。俗称“经学”。专为年满6~7岁的穆斯林儿童所设,多在清真寺内,少数系私人开办,在教师或师娘的住宅内。设在清真寺内的经文小学,教师皆由该寺教职人员担任。课程由认识、诵读、书写阿拉伯字母开始。待学会拼音之后便相继以《索尔夫》、《穆阿济》、《扎佳尼》、《阿瓦米勒》与《米苏巴哈》为教科书(俗称“连五本”)。进而开讲《亥听》(即《古兰经》选读本)、《古兰经》。经文小学的学童至10岁左右,率多辍学从事家庭生产劳动或参加社会职业,只有少数人转入经文大学,继续接受高一级的伊斯兰教经堂教育,被称为“满拉”或“海里凡”。经文小学没有严格的学籍管理,招生不定期,也不经过考试,辍学或退学甚为自由,没有班级排列。学童的进度不齐,故普遍采取复式教学法。另有伊斯兰教常识课程,每日放学前集体朗诵(系中国阿訇自编启蒙教材,俗称“杂学”)。“杂学”的内容包括沐浴、礼拜、斋戒、丧葬及游坟等宗教活动应念的都阿、苏赖。1911年辛亥革命成功后,一些设于清真寺内的经文小学开始聘请懂汉文的穆斯林给学童加授汉文启蒙性教科书。女童上经文小学率多在师娘私宅。学费没有定制,学童家长可量力向师傅(师娘)不定期地馈送海迪耶。

官方介绍可以参考 https://cati.nwupl.edu.cn/dtzx/hswx/10307.htm 中 「保守教派的兴起」 这一部分,维基百科 扎吉德 Jadid民间经文学校初步观察

如果你觉得这样的东西堂而皇之放在英语教材里没啥问题。。。我也没啥好说的。。。

其中这一段比较有趣:

情况与当时还属于苏联的中亚五国是一致的。这个过程中,瓦哈比派(Wahhabism)因为主张“回到《古兰经》中去”,注重个人对经典的领悟而非学者的解释,门槛很低,容易接受

这不王阳明心学么。。。。释经权的下放和离散化。。。这后果。。啧啧。。。。参考之前一篇《中世纪中国的宗教改革

Posted

stdout

徐州丰县,以及孝文化

抬一张地图出来,

鲁苏豫皖四省,如果让你选一个最乱的地,你可能选哪里呢?

说起来,徐州对我的印象,只是《三国演义》上一个模糊的地理概念,第一次稍微立体的感受徐州,还是在《睡前消息29 · 没有“淮海省”,徐州还是有当“省会”的命?》上看到,徐州是一个距离周边大城市都非常远的人口又比较密集的城市。

后来,从罗辑思维·启发俱乐部·第26期:显性力量越大,隐性麻烦越多》上扒到徐州周边刷过的历史人物,就更印象深刻了

这里是砀山,刘邦拔剑斩蛇起义的地方,它属于安徽省,但它同时被另外三个省包围,北部是山东,东部是江苏,西部是河南。
从这个地方向东北,开车不到一个小时,就能到达江苏省的丰县。刘邦就是丰县人。辅佐刘邦建立汉朝的很多人,像萧何、卢绾、王陵也是丰县人。
丰县的东边是沛县,刘邦集团的樊哙、曹参、周勃都是沛县人。你可能会说,刘邦搞事业,拉着乡亲入伙很正常啊。
从丰县县城向东南出发,一个半小时车程就会到达徐州。在秦代,这里叫彭城,项羽建立西楚,都城就是彭城。奇怪了,为什么项羽的都城离刘邦家这么近呢?
继续向东南驱车一个半小时,会到达今天的宿迁市,在秦代,这里叫下相,项羽的故乡。你看,连项羽家距离刘邦家好像都不是很远。
然后,从项羽的家乡向西出发,开车一个多小时,就会到达安徽省灵璧县,“霸王别姬”、“乌江自刎”的故事就发生在这附近。
踩着油门朝西北走,不到一个小时,我们来到安徽省宿州市。在秦代,这里沼泽遍地,名叫大泽乡。没错,陈涉吴广起义,就发生在这里。
是不是觉得有一个问题已经呼之欲出了?秦朝灭国的可是六国啊。齐楚燕赵魏韩,那么大一片地方啊。但是怎么在秦朝末年找麻烦的就集中在这么一小块地方呢?那么大片的地方不出事,偏偏就这里出事?
对,佐竹靖彦给这一小块地方起了个名字:“泗水系月牙形水乡山泽地带”。
在那个时代,这个地方是一片月牙形地带,泗水河川行而过,地势低、潮湿,形成了大量的水乡山泽。在秦代,这里有个地方叫大野泽。听这个名字,你就能感受到三个特点:水多、荒凉、面积大。后来随着大野泽不断缩小并且位移,到五代的时候,大野泽变成了梁山泊。
一听到梁山泊,你就明白这个地方的意义了。官兵到不了嘛。

另外,徐州还是汉帝国的掘墓者曹操起家之处,唐帝国覆灭者黄巢朱温老巢,巨盗宋江也就是在河北、河南、山东、江苏交接的地方来回变动

然后结合时事,为什么这里拐卖人口多?

很多摸鱼群的分析是孝文化,传宗接代的思想在作怪,什么养儿防老,养儿挣钱,但读到2020年这篇Yixi演讲的文章,我就不淡定了

吴心越:养老院调查真相,让老人恐惧,问题严重性超出你的想象!

小时候,父母对孩子通常都是很强势的。但是随着年龄增长,你会发现父母对你越来越弱势,其实就是这个原因。养老院里那些无儿无女的老人,其实和学校里面的“孤儿”没有本质的区别,都属于被欺负的对象。在学校,父母是孩子的依靠。在养老院,子女其实就是老人的依靠。
哪怕有些子女很混蛋,很不负责,但他是维权的直接受益人。也许子女没有孝顺的动力,但是却有替父母维权的动力。越是混蛋的子女,战斗力就越强,父母出了问题,他们能把养老院讹到破产!
就拿护工来说,知道你有哮喘,偏要把你安排在通风不好的地方;知道你和谁有矛盾,偏要把你俩安排在一个房间;知道你腿脚不利索,偏要把你安排在楼层较高的房间;故意把你安排给有传染病或者大小便失禁的老人一个房间.....这种情况,尤其是在养老行业,从来就不是个案,而是普遍性的现象。
如果找院方投诉,就相当于把护工得罪死了,只要护工不被开除,如果不换养老院,剩下的日子,老人的日子只会愈来愈难过。
如果老人在外面有子女,起码护工还会有所忌惮,知道他自己做的太过分,会有人来闹,就会有所收敛。
这个时候,老年人有子女的最大意义,就是出了问题,有人帮你喊冤,哪怕他仅仅是为了搞一笔钱。

所以现在突然明白,为啥乡土中国,熟人社会,有拼命生娃的做法,讲究「孝」道了。这TM的是生存的最低保障,战略威慑能力啊。。。

如果说大型中心省会城市代表秩序和文明,那么徐州周边的几百公里没有大城市的平原村落里,就是社会正义能延生到的末端,这个时候,基层秩序只能由血缘绑定。即便是贩卖人口交换来的亲人。

Posted

stdout

笑话了千年刻舟求剑,水面搜救的图案却叫Victor Sierra

今天的第一个收获,Victor Sierra这个搜救图案

来自 Why This Zig-Zag Coast Guard Search Pattern is Actually Genius - Smarter Every Day 268,是美国 coast guard 标准化的水面搜救路线之一。这种图案覆盖的面最大并且效率最高,而且最重要的一点,考虑到水是流动的,能够跟随一起漂流的相对速度去找到 PIW (person in water)

于是我就想起大家都熟悉的成语——「刻舟求剑」。这是2000多年前一个河南贩子吕不韦编的一个讥讽九头鸟的段子,由于这个成语太熟悉了,我甚至开始怀疑课本上是不是掐头去尾没讲完,跟之前那个「守株待兔」恶毒的政治隐喻一样,于是去翻了下原文。好家伙,不能说雷同,简直就是一模一样。它出自《吕氏春秋·察今

察今一共三段,第一段说,按着先人制度惯性因循守旧的人都是大沙雕;第二段说,荆州人拿了过期的水文资料强行过河结果沙币了。第三段说,好剑要的是锋利,不必是莫邪的名称;好马要的是能行千里,而不是骥骜的名称。成就功名的人,就是老板的好工具人。然后就抬出来了著名的讽刺湖北佬的段子:

楚人有涉江者,其剑自舟中坠于水,遽契其舟, 曰:「是吾剑之所从坠。」舟止,从其所契者入水求之。 舟已行矣,而剑不行,求剑若此,不亦惑乎? 以此故法为其国与此同。 时已徙矣,而法不徙,以此为治,岂不难哉? 有过于江上者,见人方引婴儿而欲投之江中, 婴儿啼,人问其故,曰:「此其父善游。」 其父虽善游,其子岂遽善游哉? 此任物亦必悖矣。荆国之为政,有似于此。

第二个收获就是,果不其然又是一个阴阳怪气讽刺朝政的段子。看来每一个成语背后都有一个键政的动机哎。

第三个收获,没想到刻舟求剑之后,还有个「其父善游」的更离谱段子卧槽。。。

然后突然就想到了近期第四个收获,王中林院士拓展麦克斯韦方程组,在渣乎上看的一路下来,无论是懂哥,还是路人,几乎全是在喷。但是恰好就在 HN 有人投递了一则如何通过伽利略旋转和洛伦兹旋转认识特种相对论的线串

https://twitter.com/MarkusDeserno/status/1482811504424542211

其中从 arctan(m12) = arctan(m1) + arctan(m2) 推到 tan(x+y) = [tan(x) + tan(y)] / [1 – tan(x)·tan(y)]

再到 m12 = [m1 + m2] / [1 – m1·m2]

好吧,我也假装我看懂了!

最后一个感触,大家都顾着去看2500年前楚国人和当今院士的笑话了,却很少有人正面分析一下问题。

Posted

stdout

python-phoenixdb 设置读取超时

PhoenixDB 居然是基于 requests + pb2 做的传输层协议。连接的是 queryserver 的 http 接口

avatica/client.py 源码 可以得知这玩意默认是不支持设置read timeout的。强行hack一个:

import phoenixdb
import functools
c = phoenixdb.connect('http://localhost:8765/', autocommit=True, auth="SPNEGO")
c._client.session.request = functools.partial(c._client.session.request, timeout=2)

partial 这个神奇的魔法可以设置一个默认参数。其它地方传入了别的timeout也可以自行覆盖,无缝兼容。

Posted

stdout

Microsoft 官网的 403 错误

$ curl -H "User-Agent: User-Agent: Mozilla/5" -kvs 'http://www.microsoft.com'
*   Trying 118.123.102.107...
* TCP_NODELAY set
* Connected to www.microsoft.com (118.123.102.107) port 80 (#0)
> GET / HTTP/1.1
> Host: www.microsoft.com
> Accept: */*
> User-Agent: User-Agent: Mozilla/5
>
< HTTP/1.1 403 Forbidden
< Server: GHost
< Content-Length: 306
< Content-Type: text/html
< Mime-Version: 1.0
< Expires: Wed, 29 Dec 2021 14:42:28 GMT
< Cache-Control: max-age=0, no-cache
< Pragma: no-cache
< Date: Wed, 29 Dec 2021 14:42:28 GMT
< Connection: keep-alive
<
<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>

You don't have permission to access "http&#58;&#47;&#47;mscom&#46;errorpage&#46;failover&#46;com&#47;403&#47;403&#46;htm&#63;" on this server.<P>
Reference&#32;&#35;18&#46;1c697b76&#46;1640788948&#46;3b971c1f
</BODY>
</HTML>
* Connection #0 to host www.microsoft.com left intact
* Closing connection 0

不知道为何会指向 http://mscom.errorpage.failover.com 这域名也不是微软的。

Posted

stdout

Chrome 阉割指南

不折腾不舒服。继之前 Edge调教 之后记录一下 Chrome V70怎么阉割。

下载:

win 32 | win 64 | Mac

上面的链接已经年久失修了,对比了一下获取最新版本的脚本发现 Google 已经不提供老链接了。

curl -vsk 'https://tools.google.com/service/update2' -HContent-Type:text/xml --data-binary "<?xml version='1.0' encoding='UTF-8'?>
<request protocol='3.0' sessionid='{est-blog}' installsource='ondemandcheckforupdate' dedup='cr'>
<os platform='mac' version='66.6.6666.66' arch='x64'/>
<app appid='com.google.Chrome' ap='' version='' nextversion='' lang='' brand='GGLS' client=''><updatecheck/></app>
</request>"

安装完毕之后

cd '/Applications/Google Chrome.app/Contents'
touch Frameworks
sudo chown root:wheel Frameworks
sudo chmod 000 Frameworks

cd ~/Library/Google
rm -rf GoogleSoftwareUpdate
touch GoogleSoftwareUpdate
sudo chown root:wheel GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate

Posted

stdout

认识「洋节」

都说 xmas eve 是洋节,我们就来数一数到底有哪些洋节

  1. 元旦1月1日。由北「洋」军阀袁世凯设立。依据是内务部总长朱启钤《定四季节假呈》,把原来农历(夏历)的正月初一的「元旦」挪用到了格里历一月一日。格里历(Gregorian calendar)引入中国是1912,元旦正式生效是1914年。
  2. 春节。严格的来说,传统春节是二十四节气中的“立春”,是太阳历。后来被袁世凯直接拍板成农历正月初一。而夏历正月初一一般被认为是最接近立春之朔日(月缺之日)。农历最后一次农历大改版为《授时历》,发生在崇祯二年(1629年)九月,由礼部左侍郎徐光启发起,编撰者:耶稣会的龙华民(西西里人)、罗雅谷(米兰人)、邓玉函(瑞士人)、汤若望(日耳曼人)。
  3. 生肖其实不跟农历绑定,而是跟 二十四节气绑定。二十四节气最后一次改版,也是上面那个《时宪历》那帮洋传教士定下来的。有意思的是,春分那一天恰好开始白羊座,其实我最近才知道二十四节气就约等于12星座,也就是黄道十二宫。如果要说农历《时宪历》含洋量太高,那么他之前的《授时历》编撰者是河北人郭守敬,生于元太宗(窝阔台)三年(1231年)于邢州,由他祖父郭荣(金国人)抚养成人,说起来这老兄甚至顺着蒙古人统治下的锡伯利亚去过北极科考,同一位尼泊尔建筑师阿尼哥合作搞过天文台,十分了得。
  4. 妇女节,全称为「“三八”国际劳动妇女节」。1857年3月8日,美国纽约的制衣和纺织女工走上街头,抗议恶劣的工作条件和低薪。尽管后来当局出动警察攻击并驱散了抗议人群,但这次抗议活动促成了两年后的3月第一个工会组织的建立。1917年3月8日,在俄罗斯帝国首都彼得格勒,纺织女工举行罢工及游行,遍及整个城市,也导致俄罗斯革命的开始。
  5. 清明节,二十四节气之一。太阳到达黄经15°
  6. 劳动节,1884年,劳动骑士团 Knights of Labor 倡导「8小时工作制」;10月,行会与工会联盟召开大会确定1886年5月1日为要求八小时工作制成为标准的日期,美国工会准备举行总罢工支援;1886年5月1日,数千名参加罢工和参加全美各地举行的集会的工人唱起了《八小时》(Eight Hour)一歌;接下来发生干草市场屠杀(Haymarket affair)。
  7. 端午节,据传是为了纪念恨国诗人屈原,来自「蛮夷」楚国
  8. 儿童节。1949年11月国际民主妇女联合会在苏联莫斯科所召开的执行委员会议,会上为纪念悼念1942年捷克利迪策村对儿童的屠杀及伤害,以及全世界所有在法西斯侵略战争中死难的儿童,为保障世界各国儿童的生存权、保健权和受教育权及改善儿童的生活,决议以6月1日为国际儿童节。1949年12月23中央人民政府政务院第十二次政务会议于日通过了《全国年节及纪念日放假办法》,其中规定6月1日为儿童节。
  9. 建军节,由 契丹苏维埃共和国 (Kitajskaja Sovetskaja Respublika, Кита́йская Сове́тская Респу́блика) 于1933年6月决定,将8月1日定为中国工农红军的建军节。
  10. 圣纪节,穆罕默德的诞辰与逝世恰巧都在伊斯兰教历三月十二日,回回三大节之一。

再说一下真正被 appropriation 的「洋节」

  1. 圣诞节。异教徒的节日,四舍五入冬至日,古埃及太阳神 Ra 的节日,被(东)罗马帝国拿来宣传成中东人耶稣的生日。。。摊手。。。比如犹太人就不过圣诞节,但是他们在这一天吃中餐
  2. 母亲节,由12岁女孩安娜·贾维斯(Anna Jarvis)发起,被商家利用,安娜用下半辈子反对母亲节
  3. 父亲节:抄袭母亲节。

Posted

stdout

如何可视化跟踪分析 Python import 耗时

首先在本地安装 pip install tuna

然后跑个分,需要 CPython >= 3.7,输入

PYTHONPROFILEIMPORTTIME=1 python3 myscript.py 2>1.log

tuna

然后 tuna 1.log ,会自动打开浏览器围观 import 耗时分布。

Posted

stdout

FastAPI/Starlette支持静态文件支持SPA

FastAPI 官方支持 from fastapi.staticfiles import StaticFiles 充当一个静态文件服务器

其实实现是 starlette。这玩意可以在 directory 下放一个 404.html,恰好单页应用也需要用 index.html 充当所有 javascript 框架注册的 router

只是有一个毛病,这货返回的 HTTP status code 是 404。用起来没啥大毛病,但是就是浏览器不会记录网址,导致没法匹配浏览历史快速找到之前访问过的页面。

拿来改改继续用

  from starlette.staticfiles import StaticFiles, Scope, Headers, Response, FileResponse

  class StaticFilesWithout404(StaticFiles):
      async def get_response(self, path: str, scope: Scope) -> Response:
          r = await super().get_response(path, scope)
          h = Headers(scope=scope)
          full_path, stat_result = await self.lookup_path('404.html')
          if isinstance(r, FileResponse) and r.path == full_path:
              if 'text/html' in (h.get('accept') or ''):
                  r.status_code = 200
              else:
                  return Response('', status_code=404)
          return r

  app.mount("/frontend", StaticFilesWithout404(directory="frontend", html=True), name="static")

这段代码大概是起到了类似 nginx try_files 的作用。默认静态文件映射一个目录,但是如果找不到就按根目录的 index.html 输出。这里还判断了请求的 accept 头,如果是 xhr/Fetch 就会直接返回一个0字节长度无MIME的404。

由此我想到了一个学究式的 leaky abstraction。众所周知,如果一个URL不存在,那么服务器应该返回404

但是现在都是 SPA 单页应用,都是先 200 返回 index.html 的内容,再由 javascript 的 router 去决定是否正常显示还是404 。所以返回 200 但是显示 404 就破坏了这个语义。如果要精确匹配SPA里的router如果不存在由服务器返回404,第一是搞 SSR,把前端那一坨代码跑在服务器端,第二种办法是 npm build 的时候输出一个可路由URL列表,然后部署的时候导入静态文件服务器更新。这个具体实现就留作homework由读者自行解决了。

Posted

stdout

人工构造Flask session模拟cookie登陆

有没有好奇为什么 Flask 配置必须要求一个 SECRET_KEY,然后就可以在浏览器保存一个 session 状态读写数据。

这里记一下它的底层实现,其实需要依赖的包是 itsdangerous

  import hashlib
  from itsdangerous import URLSafeTimedSerializer
  URLSafeTimedSerializer(
          'YOUR_SECRET_KEY',  # flask SECRET_KEY
          'cookie-session',  # from flask.sessions.SecureCookieSessionInterface.salt
          # serializer=TaggedJSONSerializer(),
          signer_kwargs={'key_derivation': 'hmac', 'digest_method': hashlib.sha1}
  ).dumps({
      "your_key": "your_value"
  })

别人如果拿到你的 SECRET_KEY 就可以伪造任意 session cookie 了

Posted

stdout

Python 3.X ctypes 和 greenlet size changed 坑三则

安装 setup.py 的时候 No module named '_ctypes' 报错

  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "/usr/local/python3/lib/python3.9/site-packages/setuptools/__init__.py", line 18, in <module>
      from setuptools.dist import Distribution
    File "/usr/local/python3/lib/python3.9/site-packages/setuptools/dist.py", line 34, in <module>
      from setuptools import windows_support
    File "/usr/local/python3/lib/python3.9/site-packages/setuptools/windows_support.py", line 2, in <module>
      import ctypes
    File "/usr/local/python3/lib/python3.9/ctypes/__init__.py", line 8, in <module>
      from _ctypes import Union, Structure, Array
  ModuleNotFoundError: No module named '_ctypes'

解决办法是不要用 3.9。

如果实在要用,则自己编译前需要加上 yum install libffi-devel 或者 sudo apt-get install libffi-dev

来自SO

greenlet.greenlet size changed 然后出错

/usr/local/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144 from C header, got 152 from PyObject
  return f(*args, **kwds)
/usr/local/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144 from C header, got 152 from PyObject
  return f(*args, **kwds)

Segmentation fault (core dumped)

这个摘自官方 iseue

On Python 3.7 and higher, gevent 20.9.0 is required to use (a standard build of) greenlet 0.4.17.

解决办法:pip install gevent==20.9.0 pip install greenlet==0.4.17

SQLAlchemy 1.4 大战 greenlet 0.4.17

sqlalchemy changelog

to accommodate for the handling of Python contextvars (introduced in Python 3.7) for greenlet versions greater than 0.4.17. Greenlet version 0.4.17 added automatic handling of contextvars in a backwards-incompatible way; we’ve coordinated with the greenlet authors to add a preferred API for this in versions subsequent to 0.4.17 which is now supported by SQLAlchemy’s greenlet integration. For greenlet versions prior to 0.4.17 no behavioral change is needed, version 0.4.17 itself is blocked from the dependencies.

然后就直接在 setup.cfg里greenlet != 0.4.17了。

神仙打架,不听不听,和尚念经,果断 sqlalchemy==1.3.24 降级。

Posted

stdout

Edge调教指南——如何设置本地PAC代理和首页天气

之前一直用的chrome v70,为什么呢?

第一是这个老版本允许 --proxy-pac-url="file:///Users/me/1.pac 这样设置,但是Chromium项目的大爷们觉得你本地的.pac不够安全,要网上的.pac才安全,所以一刀切给禁了。当然有热心人士觉得这没啥大不了的。不外乎装个插件就可以切PAC。但是chrome插件其实会有一个fingerprint。Extension一启用,隔壁老王都知道你开代理了。

第二,也是最重要的原因,这是最后一个chrome版本支持 about://net-internals 在本地查看浏览器底层网络请求。现在无论是 Edge 还是 Chrome 都必须把 .json 文件从 https://netlog-viewer.appspot.com/ 加载才能看了。很尼玛保护了隐私有没有啊。

但是坚持老版本,也付出了巨大的代价。很多新的 ES 语法不支持,比如说 Grafana 最新版 login 都进不去。这就尴尬了。只能被自愿升级了。

既然升级是必选项,那么就换 Edge 试试。

第一就是得解决这个本地 .pac 问题,其实从上面第二个工具里才能知道,PAC加载失败有个返回 ERR_DISALLOWED_URL_SCHEME。stackoverflow 上找到个奇技淫巧

open "/Applications/Microsoft Edge.app" --args --proxy-pac-url='data:application/x-javascript-config;base64,'$(base64 -i /Users/me/2.pac)

还能这样玩?双击666。

第二个把该禁用的禁用了,首页只留一个搜索框一个天气。但是这天气就特么定位到坡县了。而且下拉框点不出来啊。F12打开 devtool 一看,我尼玛好家伙 https://www.bing.com/api/v6/Places/AutoSuggest 被 Bing China 的网管给一把梭302到 https://cn.bing.com/api/v6/Places/AutoSuggest 了。然后就特么 CORS 给拦截,js读取不到列表。。。

最后怎么办?点那个天气图标,进入到 https://www.msn.com/en-sg/weather/today/weather-today/we-city

然后找那个地图,手动选择自己所在城市,设置为 Home 。等 cookie 写入生效了,打开edge新tab就ok了

这年头上个网真鸡儿累。

btw 设置M$账号同步的时候,发现账号所在国家可以选很多不是国家的地方,但是时区就不能随便选了。F12改了也没用。微软的后台开发做的过滤还挺细致的。

btw2 发现一个很干净的启动页: chrome-search://local-ntp/local-ntp.html 或者直接在 hosts 里把 ntp.msn.com 干掉,有奇效。

Posted

stdout

TiDB不支持JSON字段默认值

继前面的日期不兼容坑,又发现一个

The BLOB, TEXT, and JSON columns cannot be assigned a default value.

虽然 MySQL 5.7 也是这么说的:

A JSON column cannot have a non-NULL default value.

但是 MySQL 8.0.13 就支持指定默认值

Prior to MySQL 8.0.13, a JSON column cannot have a non-NULL default value.
The default value specified in a DEFAULT clause can be a literal constant or an expression. With one exception, enclose expression default values within parentheses to distinguish them from literal constant default values. Examples:

虽然语法很丑但是很实用啊。

所以这种语句

  ALTER TABLE mytable MODIFY COLUMN my_json JSON DEFAULT (json_object());

在 TiDB 里就没法支持。这也带来一个问题,就是要 upsert 这个 字段的时候,写起来就很拧巴,以 peewee 这个ORM为例:

  MyTable.update({
      'my_json' = fn.json_set(
          fn.COALESCE(MyTable.my_json, Cast('{}', 'JSON')),
          '%.some_key', 'some_value',
  )})

必须用 COALESCE 预防默认值为 NULL 的情况。太麻烦了。

btw 玩MySQL/TiDB的 JSON 有个坑的,那就是 json 的 null 是有值的,和 sql 的 NULL 是不同的。

也就是说

  select json_extract('{}', '$.hey') IS NULL;
  select json_extract('{"hey": null}', '$.hey') = Cast('null' as JSON);

要注意。

btw2 MySQL的JSON数据抽取 ->> 是返回真正的值,等价于TiDB里的 json_unquote(json_extract(t.json_field, '$.key1.key2'))

Posted

stdout

Chrome 指定域名解析,绕过 hosts

看到 V站有人问这个,随手一记

可以参考源码里的注释文档

--host-resolver-rules=rules

Like --host-rules but these rules only apply to the host resolver.
A comma-separated list of rules that control how hostnames are mapped.
For example:
- MAP * 127.0.0.1 Forces all hostnames to be mapped to 127.0.0.1
- MAP *.google.com proxy Forces all google.com subdomains to be resolved to proxy.
- MAP test.com [::1]:77 Forces test.com to resolve to IPv6 loopback. Will also force the port of the resulting socket address to be 77.
- MAP * baz, EXCLUDE www.google.com Remaps everything to baz, except for www.google.com.

These mappings apply to the endpoint host in a net request (the TCP connect and host resolver in a direct connection, and the CONNECT in an HTTP proxy connection, and the endpoint host in a SOCKS proxy connection).

官方文档有语焉不详的提到过

https://chromium.googlesource.com/chromium/src/+/refs/heads/main/net/dns/README.md

Starting Chrome with --host-resolver-rules="MAP the.hostname.com [dead::beef]" where the.hostname.com is the hostname to allow resolving and dead::beef is the IPv6 address to resolve it to. net::MappedHostResolver acts at a level before IPv6 connectivity checks, and if a hostname is remapped to an IP literal, connectivity checks do not apply.

还有很多 proxy的参数

curl 的参数

也顺便贴一下。调试的时候用得上

参数:

  • -4, --ipv4
  • -6, --ipv6
  • --dns-interface <interface>
  • --dns-ipv4-addr <ip-address> Tell curl to bind to <ip-address> when making IPv4 DNS requests
  • --dns-ipv6-addr <ip-address> Tell curl to bind to <ip-address> when making IPv6 DNS requests
  • --dns-servers <ip-address,ip-address> Set the list of DNS servers to be used instead of the system default. The list of IP addresses should be separated with commas. Port numbers may also optionally be given as :<port-number> after each IP address.
  • --resolve <host:port:address> Make the curl requests(s) use a specified address and prevent the otherwise normally resolved address to be used. Consider it a sort of /etc/hosts alternative provided on the command line. The port number should be the number used for the specific protocol the host will be used for. It means you need several entries if you want to provide address for the same host but different ports. This option can be used many times to add many host names to resolve. (Added in 7.21.3)

最后一个很有用 😹

Posted

stdout

reverse proxy FastCGI (fcgi) with uWSGI

People are still using FastCGI, and it's hard. I used uWSGI to convert FCGI traffic to regular http/1.0 so I can keep my existing http service running without apache mod_fcgi shit.

CGI environ variables

This is some ancient knowledge, better keep them noted

KEY description
AUTH_TYPE ignore this
REMOTE_IDENT The user making the request.
REMOTE_USER The authenticated name of the user making the query.
CONTENT_LENGTH byte length of body
CONTENT_TYPE MIME such as text/html, without the charset shit
DOCUMENT_ROOT NEW. The directory from which web documents are served.
REQUEST_URI NEW. confusing shit similar with PATH_INFO
HTTP_* HTTP headers
PATH_INFO like /a/b/c
PATH_TRANSLATED not really used
QUERY_STRING the part after ? in an URL
REMOTE_ADDR client IP
REMOTE_HOST client host name by lookup ip
REQUEST_METHOD GET/POST
SCRIPT_NAME The virtual path (e.g., /cgi-bin/program.pl) of the script being executed.
SCRIPT_FILENAME confusing shit similar with SCRIPT_NAME
SERVER_NAME The server's hostname or IP address.
SERVER_PORT The port number of the host on which the server is running.
SERVER_PROTOCOL The name and revision number of the server protocol.

reverse proxy FastCGI with uWSGI

slap this into my_conf.ini

  [uwsgi]
  my_port = 9000  # can be set otherwise
  route-run = addvar:SERVER_NAME=%h
  route-run = addvar:SERVER_PORT=%(my_port)
  route-if  = empty:${REQUEST_METHOD} addvar:REQUEST_METHOD=GET
  route-if  = empty:${HTTP_HOST} addvar:HTTP_HOST=%h:%(my_port)
  route-run = seturi:/fcgi-proxy${PATH_INFO}
  route-run = http:127.0.0.1:9527
  fastcgi-socket = 0.0.0.0:%(my_port)
  http-socket = 0.0.0.0:8000  # for testing purpose.

Install uWSGI, install the binary from pypi wheels instead of compiling uwsgi.c shit

  pip install pyuwsgi

Run it

  uwsgi --ini my_conf.ini

Now you can run your regular http service behind 127.0.0.1:9527, while serving fcgi on 127.0.0.1:9000

Requests like fcgi://127.0.0.1:9000/hello will be fowwarded to http://127.0.0.1:9527/fcgi-proxy/hello

You may ask why adding a /fcgi-proxy in path? Because there's a gotcha.

fuckedup FastCGI requests

Learned this from some php-fpm tutorial, first install the standard fcgi client tool because curl doesn't speak fcgi.

  apt-get install libfcgi0ldbl
  yum --enablerepo=epel install fcgi
  SCRIPT_NAME=/ping SCRIPT_FILENAME=/ping REQUEST_METHOD=GET cgi-fcgi -bind -connect 127.0.0.1:9000

You can observe from uWSGI logs that cgi-fcgi command sends flawed requests, the PATH_INFO was unset.

After hours wasted, I came up with a clever hack to force uWSGI's internal router to force seturi with a path prefix

ToDo

There are further problems that can be improved, for example, my http service is running uvicorn, it can not guess the client ip:port infor from its stupid get_remote_addr

what's worse, the uWSGI addheader directive are for responses, so I can't add request headers like x-forwared-for.

Also the reverse proxy is HTTP/1.0 only. to make the Connection: Keep-alive happen needs some further investigation.

Q&A

Thanks for reading my shitpost. Questions?

Posted

stdout

淘宝同一手机最多绑定6个小号

总结一些没用的知识

  1. 淘宝/阿里账号,可以一个手机最多绑定6个账号。淘宝注册的时候点击「企业注册」然后用邮箱注册,最后用同一个手机验证即可

  2. 「支付宝」在淘宝/阿里系里app里是和「账号」一一绑定的,这就产生了很多冲突。比如你一个第三方外卖app,支付的时候可以选择 微信/支付宝,一般不会限制下单手机号和支付手机号是否一样,你甚至可以帮别人支付订单,但是淘宝/阿里的app不一样,只能自己账号支付自己账号的订单。如果你有两个手机号和两个支付宝账号,那么没法交叉支付。

还有一个想不起了,想起了再补充。2333

Posted

stdout