compileprincess/apple
0
1# -*- coding: utf-8 -*-2robe_version="1;;"3##import sys;import os;sys.path.append(os.environ["AlfiPython"]+r"\Mjmoji");from wr import * ;4##import mlwebOrWeb as ml5## wardrobe6 7import sys,os,re8import shutil9import inspect10import time11import traceback12import pprint13import functools14if "Byte":15 from io import StringIO, BytesIO16 17 18lf= "\n";lff=lf*2;sp=" ";lf2="\n";tab="\t";19def fpreturn(*_): return _[0]20def fpre(*_): return _21pr=print22tfolder="r:/temp"23if not os.path.exists(tfolder): tfolder=os.environ["tmp"]24if "cpa" in os.environ:25 cpy=os.path.abspath(__file__+"\\..\\..")26 cpw=os.path.abspath(__file__+"\\..")27 T45=os.environ["USERNAME"]28 cpa=os.environ["cpa"]29 ZVCherryPicker=cpy+"\\qt\\ZVCherryPicker.pyw"30 HeartNote=cpy+"\\qt\\HeartNote.pyw"31else:32 cpa=None33 34class p310:# require version35 def __getstate__(zl):return #pickle36def typeint(w):37 try:38 int(w)39 return True40 except:False41def typefn(fn,remove=0):42 if (re.search(r'["*/:<>?\\|]',(fn))):return43 if (".." in fn):return44 if len(fn)>255:return45 try:46 open(fn,"ab")47## if remove: os.remove(fn)48 return 149 except:False50def fpf(fn,fb="",tail=""):51 if not typefn(fn):52 if not fb:53 f,e=lfn.splitext(fn)54 fb=f[:200]+e55 fn=fb56 if tail: wfdb(fn+"_", putp(1,tail))57 return fn58def putp(fl,te):#,*w,**W):59 import pickle60 put=pickle.dumps61## print(te)62 if fl==1: te= put(te)63 if fl==2: te= pickle.loads(te)64 return te65def exrange(li,step=2):66 if len(li)/step < 0: return67 for x in range(0,len(li)//step):68 yield li[x*step:x*step+step]69def pr2(*a,**k): pass;70oriAB=lambda x: (print(x[:122],lf*2,x[-122:]))71ppf=pprint.pformat72def orib(lii, ix=-1,bound=4):73 "print(li[:4],li[-4:])"74 if(ix==-1):75 lambda x: (print(x[:4],lf*2,x[-4:]))76 else:77 lio=[lii[ix+n] for n in list(range(-bound,bound)) if(ix+n>0 and ix+n<len(lii)) ]78 for v in lio:79 if(v==lii[ix]):lio[lio.index(v)]="__"+v80## lio[ix]="__"+lio[ix]81 #lio[ix]+=lf82 print(lfjw(lio))83def printline(*a,**k):#X/ref84 f=inspect.currentframe()85 if(sys.version=='3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)]'):86 no=inspect.currentframe(1)87 elif(sys.hexversion>=0x030401F0):#'3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)]'):88 "c7 3.7.7 64bit -> 3.8.6"89 fb=f90 for _ in range(4):91 print(fb.f_lineno,fb.f_code.co_filename, fb.f_code.co_name)92 fb=fb.f_back93 if not fb:94 break95## print(" L-"+str(no),*a,**k)96def prfl(li):#prFirstLast97 print(li[0],lf,li[-1]);98def pren(v):99 print(list(enumerate(v)))100 101 102 103 104 105 106 107 108 109 110#mrk1------------file111def wfdb(filename,te):#writeFileDirectInBinaryMode112 f = open(filename,"wb")113 f.write(te)114def wfdt(filename,te):#text115 return wfd(filename).t(te)116def wfdt8L(filename,te):#textUni NewLine Unix Format117 f = open(filename,"wU",encoding="utf-8")118 f.write(te)119def wfd8(fn,te):120 wfd(fn).w(te,code="utf8",copy=0)121def afdt(filename,te):#textUni122 f = open(filename,"a+",encoding="utf-8")123 f.write(te)124write8dd=afdt125afdtu=afdt126def rfdb(fn):127 f = open(fn,"rb")128 te = f.read()129 return te130def rfdt(fn):return wfd(fn).r()131def rfdl(fn):132 f = open(fn,"r")133 te = f.readlines()134 return te135def rfdv0(fn,codeList=("cp932","utf-16","utf-8","eucjp"),lines=True):136 for c in codeList:137 f = open(fn,"r",encoding=c)138 try:139 te = f.readlines() if(lines)else f.read()140 break141 except UnicodeDecodeError as XP:142 continue;143 except UnicodeError as XP:144 continue;145 return te146def rfdlv(fn): return rfdv0(fn)147def rfdtv(fn): return rfdv0(fn,lines=False)148def rfdtu(fn):149 f = open(fn,"r",encoding="utf-8")150 te = f.read()151 return te152def vcs(bte,cs=("utf8","cp932","utf16","eucjp")):153 for c in cs:154 try: return bte.decode(c)155 except: continue156class wfd():#clWfd157 tab="\t"158 def __init__(zl,fn,region=(),ir=None,lf="\n"):159 zl.fn=fn160 zl.code="utf8"161 zl.lf=lf162 zl.ir=ir#163 zl.by=None164 def readtime(zl,mod=0):165 zl.ts=(lfn.getatime(zl.fn)+mod, mtime(zl.fn)+mod)166 return zl167## def restoretime(zl):168 def rfdv(zl):return zl.r(cs=("cp932","utf-16","utf-8","eucjp","mbcs"))#noMbcs)169## def mem(zl): zl.by=zl.rb(); return zl;170 def rb(zl): return open(zl.fn,"rb").read()171 def r(zl,cs=("utf8","cp932","utf16","eucjp"),lines=False,m=0,te=""):172 if te: e1=te173 else:174 with open(zl.fn,"rb") as f:175 e1 = f.read()176 for c in cs:177 try:178 t1=e1.decode(c)179 if("\r\n" in t1):180 #if(t1.count("\r")!=t1.count("\n")):return 0181 zl.lf="\r\n"182 elif("\n" in t1):zl.lf="\n"183 elif("\r" in t1):zl.lf="\r"184 else:#oneline185 pass186 if lines: te=t1.splitlines()187 else: te=t1188 #te=te.replace(zl.lf, "\n")189 zl.code=c190 break191 except (UnicodeDecodeError, UnicodeError) as e:192 zl.lastException=e193 continue;194 else:195 return 0196 if(zl.ir) and 0:197 te=zl.lte=findall(zl.ir,te)198 if m: #chk modified199 import hashlib200 zl.mtime=mtime(zl.fn)201 zl.sha=hashlib.sha256(te.encode()).digest()202 return te203 def csvr(zl,*aw,lf=None,tab=None,**kw):204 return list(csv.reader(StringIO(zl.r()), delimiter=tab or zl.tab))205 def w8(zl,te): return zl.w(te,code="utf8")206 def w16(zl,te): return zl.w(te,code="utf_16_LE")207 def wjis(zl,te): return zl.write8re(zl.fn,te,"cp932")208 def write8re(zl,fn,te,code="",lines=False,copy=True,lf=1,nbase=0,ts=0):209 if not code: code=zl.code210 dir = lfnd(fn)211 if dir: inidi(dir)212 if(ifexist(fn) and copy):213 dnRestore=f"{tfolder}/restore"214 inidi(dnRestore)215 zl.fnRestore=nxNumFull(dnRestore,"%s"+lfn.split(fn)[1],nZfill=2) if nbase else jofn(dnRestore,cfile(fn)+" "+tp())216 shutil.copy2(fn,zl.fnRestore)217## emove__218 rmbat(zl.fnRestore)219## if(type(te)!=str):return 0220 if 1:221 Lf=(zl.lf if lf==1 else lf)222 t1=jw(Lf,te) if lines else te223 #no t1=zl.CallBackCaller() if zl.ir else t1224 e1=t1225 if isinstance(e1, str): e1=e1.encode(code)226 try:227 with open(fn, 'wb') as fo:228 fo.write(e1)229 except Exception as e:230 #restore()231## zl.LastError=e232 open(r"r:\fail reason.txt","w").write(str(e))233 open(r"r:\fail "+tp()+".txt", "wb").write(e1)234 #with open(nxNumFull(r"r:","%s"+os.path.split(fn)[1],nZfill=2), 'wb') as fo:235 return 0236 if ts==1: os.utime(zl.fn, zl.ts)237## finally:238 if 0:239## t2=rfdtv(fn)240 fo=wfd(fn)241 t2=fo.r(cs=("utf8","utf16","eucjp","cp932"))242 print(fo.code,t2)243## print(fnRestore,t2)244 #diff()245 return 1246## def write8re(zl,fn,te,*aw,**kw):print("w;",fn,len(te), lf, dif32(zl.r(),te))247 def w(zl,te,*a,**k):return zl.write8re(zl.fn, te, *a, **k)248 def t(zl,te,*a,**k):249 rmbat(zl.fn,rembat="wf t.bat")250 return zl.write8re(zl.fn, te,copy=False *a, **k)251 def CallBackCaller(zl):252 te=zl.r((zl.code,))253 rnte=""254 l=0255 for n,ran in enumerate(zl.lte):#range list.appended(ire.search)256 rnte+=te[l:ran[0]]257 rnte+=zl.cb(n)258 l=ran[1]259 rnte+=te[l:]260 return rnte261def ornkf(byte,cs=("utf8","cp932","utf16","eucjp"),lines=False):262 return263 for c in csf:264 try:265 t1=e1.decode(c)266 if("\r\n" in t1):267 if(t1.count("\r")!=t1.count("\n")):return 0268 zl.lf="\r\n"269 elif("\n" in t1):zl.lf="\n"270 elif("\r" in t1):zl.lf="\r"271 else:#oneline272 pass273 if lines: te=t1.splitlines()274 else: te=t1.replace(zl.lf, "\n")275 zl.code=c276 break277 except UnicodeDecodeError as XP:278 continue;279 except UnicodeError as XP:280 continue;281 else:282 return 0283## with open(zl.fn, "rb", encoding=zl.code):284 return te285 286 287 288 289 290 291 292 293#----mrk1-----------294def line():295 return inspect.currentframe().f_back.f_lineno296def cmpd(te,tf):#cmpDokomade.Use for comic rename297 for n in range(999):298 if te[n] != tf[n]:299 return n300def cmpfs(li):301 "os.path.commonprefix(list)"302 ip=min(compd(li[0],f) for f in li)303 return ip304def wfy(li,ws=5):# windowfy function, window size305 for n,f in enumerate(li):306 yield li[n:n+5]307##def orin(te=" input"):308## print(te)309## input()310def owari():311 print("\nowari:");312 input("owari:")313 314 315from argparse import ArgumentParser316def arx(a=None):#Exe317 parser = ArgumentParser(description="command_error")318 parser.add_argument("-f",type=str)319 parser.add_argument("-re",type=str)320 parser.add_argument("fil",nargs="*")321 arps=parser.parse_args(a)322 return arps323def a2a(li):324 return jw(" ",('"{}"'.format(f) for f in li))325def chdir(x=0):326 os.chdir(lfnd(sys.argv[x]))327class pushd:328 def __init__(sl,dir):329 if 1: inidi(dir)330 sl.dL=os.getcwd()331 os.chdir(dir)332 def __enter__(sl):333 return 1334 def __exit__(sl, _type, value, traceback):335 os.chdir(sl.dL)336def chdirc(fil=0,idx=1):# mv to z droped file337 if not fil:fil=sys.argv[1:]338 if isinstance(fil,(hhwr)): fil=fil.fil339 if not fil:340 pr("please drop off the file");input("chdirc()");341 else:342 os.chdir(lfnd(fil[0]))343 return fil344 345def chdirm():# mv to z file own is in346 chdirc(args=sys.argv,idx=0)347 348def cdn(args = sys.argv):#ChDirNakereba 引数があればそのディレクトリに。なければスクリプトの349 if(len(args) == 1):350 lena=0;351 else:352 lena=1;353 argf= args[lena]354 d=re.match(r"(.+(?:\\|/))",argf).group(1)355 os.chdir(d)356# a=input(argf)357 return args[1:];358#r:\p\fi.mkv359#r:\p360#r:\p #fi361#fi.362#fi.mkv363#.mkv364#mkv365def cdir(fn):return lfnd(fn)366def cdiy(argf):#+yen367 return argf[:argf.rfind('\\')+1]#fail .-1+1=0 .""368def cfile(fn):return lfnb(lfn.splitext(fn)[0])369def cdotc(fn):return lfnb(fn)370def catsuff(fn,suf):#foo.mkv, mp4 >> foo.mp4371 tail=fn.rfind('.')372 if(tail==-1):tail=None373 fnre=fn[:tail]+"."+suf374 if(fnre==fn):375 return "onaji"376 return fnre377replaceSuffix=catsuff378def catpref(fn,prefix):379 "/foo.mkv, f2 >> /f2foo.mkv"380 yenpos=fn.rfind('\\')381 if(yenpos==-1):382 fnre=prefix+fn383 else:384 fnre=fn[:yenpos]+'\\'+prefix+fn[yenpos+1:]385 return fnre386def CatPS(fn,p,s):387 return catsuff(catpref(fn,p),s)388#389if "jwdir":390 def lgest(lis):391 l=lis[0]392 for l2 in lis:393 if l2>l: l=l2394 return l395 def notanybad(lis):396 for f in lis:397 if not f: return False398 return True399 #from jwdir import *400 jwdir=getattr(os.path,b'\x6A\x6F\x69\x6E'.decode())401 jofn=jwdir402 def jw(te,list):403 assert isinstance(te,(str,bytes))404 #assert 1==len(typ:=set(type(f) for f in [te,*list])), ["type not unique ",typ]405 assert hasattr(list,"__iter__")406 return getattr(te,b'\x6A\x6F\x69\x6E'.decode())(list)407 lfjw=functools.partial(jw, lf)408 _lfn="LibFileName"#="lfn"409 lfn=os.path410 lfnd=lfn.dirname411 lfndir=lfn.dirname412 lfnb=lfn.basename413 mtime=lfn.getmtime414 ctime=lfn.getctime415 n12=__builtins__[b'\x65\x6E\x75\x6D\x65\x72\x61\x74\x65'.decode()]416 def fpn1(lis):417 if isinstance(lis,(dict)): return getattr(lis,b'\x69\x74\x65\x6D\x73'.decode())()418 return n12(lis)419 sleep=getattr(time,b'\x73\x6C\x65\x65\x70'.decode())420 def shuttown(stdin,*w):421 assert hasattr(stdin, b'\x63\x6C\x6F\x73\x65'.decode())422 return getattr(stdin,b'\x63\x6C\x6F\x73\x65'.decode())(*w)423 424 425 426 427 428 429 430 431 432 433 434 435 436 437def dq(te):#double quote438 if(te[0] != '"' or te[-1] != '"'):439 return '"'+te+'"';440def prit(*w):441 te=jw(" ", [str(f) for f in w])+lf;442## print("exit-%d "%inspect.currentframe().f_back.f_lineno, end="");443 print("exit-")444 print(te, end="");445 if w[:1]==(1,):input("*")446 sys.exit();447prexit=prit448def inidi(pdir):449 if os.path.exists(pdir): return 1450 else:os.makedirs(pdir); return 0451def inidir(*dirlist):452 with pushd("."):453 for f in dirlist:454 assert type(f)==str, "inidir;"455 #f=os.path.abspath(f)456 if not f:457 os.chdir("..")458 continue459 p=os.path.split(f)460 if(p[0]):#"c:\dir\"461 if not lfn.exists(p[0]):os.makedirs(p[0])462 assert lfn.isdir(p[0])463 os.chdir(p[0])464 if(p[1]):#"c:\file" > ("c:\", "file")465 if not os.path.exists(f):wfdb(f,b"")466def isdir(fn):467 if os.path.isdir(fn): return fn;468 if os.path.isfile(fn): return 0;469 if os.path.islink(fn): return 0;470 471def isBound(length,index):472 if(length<0):473 index=abs(index+1)474 return bool(length>index)475def boundary(x,b):476 if b[0]>x:x=b[0];477 if b[1]<=x:x=b[1]-1478 return x479def ifexist(fn):#return True480 return lfn.exists(fn)481def AbImage1(fs,grouping=False):#連番を表示しない。冗長になるのを防ぐ482 lioView=[]483 DiNameTm=puni()484 for fn in fs:485 NameTm=re.sub(r"\d","5",fn)486 DiNameTm.up(NameTm,fn)487 #488 ireTailNm=re.compile(r"(\d+)")489 def fTailNm(fn):#return rearest number490 fn=re.sub(r"(mp4|mp3)","",fn)491 mo=ireTailNm.findall(fn)492 if mo:493 Nm=int(mo[-1])494 return Nm495 return 0496 if grouping:497 d2=list((k,sorted(v,key=lambda e: -fTailNm(e))) for k,v in DiNameTm.items())498 l1=[[" "+f[0]]+f[1:grouping] for k,f in d2]499 lioView=[f1 for f2 in l1 for f1 in f2]500 else:501 lioView=[max(v,key=fTailNm) for k,v in DiNameTm.items()]502 return lioView503def orror(*a,**k):504 te=jw(" ",(str(f)for f in a)) + lf;505 afdt("orror00.txt",te)506def orro2(*a,**k):507 te="";508 for f in a:509 ty=type(f);510 if(ty==int):511 ti=str(f);512 te= te+ti513 else:514 te+=f;515 te+=" ";516 te+=lf;517 afdt("orror00.txt",te)518def orro3(fn,te0=None,sp=" "):519 if(te0!=None):520 wfd(fn).w(te0,copy=False)521 def f(*a,**k):522 te=jw(sp,[str(t) for t in a]);523 afdt(fn,te+lf)524 return te525 return f;526 527def move2(src,dist, rec=0):528 if dist==src: return529 distdir=lfn.dirname(dist)530 if distdir and not(ifexist(distdir)): os.makedirs(distdir)531 if rec: afdt("r:\\temp\\rename.txt",dist+tab+src+lf);532 os.rename(src,dist);533##def move2(src,dist): move2(dist,src,0)534 535def rmbat(fns,rembat="rmbat.bat",tmd=tfolder):#jis only536 rembat=tmd+"/"+rembat537 if not ifexist(rembat): afdt(rembat, 'chcp 65001\r\n')538 for fn in fns if type(fns)!=str else [fns]: afdt(rembat,'del "{fn}"\r\n'.format(fn=lfn.abspath(fn)))539orRemove=rmbat540def remove(fn,add=1):541 if not ifexist(fn):return542 if add: afdt(r"r:\temp\rename.txt",":rm"+"\t"+fn+lf);543 os.chmod(fn,0o770)544 if lfn.isdir(fn):545 shutil.rmtree(fn)546 elif lfn.isfile(fn):547 os.remove(fn)548 return 1549def remo(fn): return remove(fn,add=0)550from uuid import uuid1551_perf_counter0=time.perf_counter()552def perf_counter():553 return time.perf_counter()-_perf_counter0554def timepref(w=5,n=2):# zero width, after z decimal point555 return time.strftime("%Y%m%d-%H%M%S")+"-{t:0{w}d}".format(w=w,t=time.perf_counter_ns()//(1000000000//10**n))556from datetime import datetime557_now=0558def tp(te="%Y%m%d-%H%M%S",n=2):#%f559 global _now560 while 1:561 ((t:=datetime.now()))562 now=t.strftime(te)563 if n:now+="-{}".format(f"{t.microsecond:06}"[:n])564 if _now!=now:break565 _now=now566 return now567 568def emove(src,timebase=True):569 src=os.path.abspath(src)570 c=os.path.splitdrive(src)[0]+os.path.sep #c:571 emo=jofn(c, "emove______")572 if not(os.path.exists(emo)): os.makedirs(emo)573 _id=tp() if timebase else str(uuid1(0))# None . getnode()574 #base="{} {}".format(os.path.basename(src), _id)575 base=_id576 dst=jofn(c, "emove______", base)577 afdt(jofn(emo,"wrld.txt"),src+"\t"+base+lf);578 os.rename(src,dst)579 return dst580def emrestore(fn="C"):581 if len(fn)==1:582 emo=jofn(fn[0]+":/", "emove______")583 else:emo=fn584 li=rcsr(jofn(emo,"wrld.txt"))585 return li586 return (li[-400:])587def fripfn(a,b):588 aff=a+"fripfn"589 os.rename(a,aff)590 os.rename(b,a)591 os.rename(aff,b)592#emove(r"r:\02zv.txt")593#2remove594def orsplit1(te,Threshold=1):595 return [j for j in te.splitlines() if len(j)>=Threshold and j[0]!="#"]596def orsplit(te,delimiter):597 t2=te.split(lf)598 t3=[j.split(delimiter) for j in t2 if len(j) > 0]599 return t3600def orsplit2(te,delimiter,threshold=5,strip=fpreturn):601 "VzComment"602 t2=te.splitlines()603 l1list=[[strip(f) for f in j.split(delimiter)] for j in t2 if len(j)>=threshold and j[0]!="#"]604 return l1list605def colonsplit(te): return orsplit2(te,":",strip= str.strip)606##def orsplit3(te,delimiter):607## "VzCommentCsv"608## t2=te.split(lf)609## l2list=[j.split(delimiter) for j in t2 if j[0]!="#"]610## return l2list611def orsub(map0,te):612 pat=jw("|",map(lambda e:re.escape(e),map0));613## pr(pat);614 irfinal=re.compile(pat)615 def f6(mo):616 mg= mo.group(0);#[0];617 if (mg in map0):618 mg=map0[mg];619 else:620 assert 0,("orsub");621 return mg;622 t2=irfinal.sub(f6,te);623 return t2;624def orsubne(map0,te):#NonEscape625 pat=jw("|",map0);626## pr(pat);627 irfinal=re.compile(pat)628## mapi={orsub({r"\[":"[",r"\]":"]",r"^":"","$":""},k):v for k,v in map0.items()}629 def f6(mo):630 mg= mo.group(0);#[0];631 li=[v for k,v in map0.items() if re.match(k,mg)]632 if li:pass633 else:634 assert 0,("orsub")635 return mg;636 t2=irfinal.sub(f6,te);637 return t2;638#639def findall(ire,te,rebuild=0):640 ire=re.compile(*ire) if not isinstance(ire,re.Pattern) else ire641 ran=(0,0)#range642 while 1:643 mo=ire.search(te,ran[1])644 if(mo):645## print(mo,mo.groups())646 if rebuild:647 yield (ran[1],mo.span()[0]), 0648 yield mo.span(), mo649 else: yield mo650 ran=mo.span()651 else:break652 if rebuild: yield (ran[1], len(te)), 0653#2regex654##prexit(findall(re.compile(r"(\d*) (?=<d>\d*)a"),"1 2a"))655##prexit(findall(re.compile(r"(\d)(?P<d2>2)?"),"123 1 12"))656##prexit(list(findall((r"('.+?')",),"1'2'3 '1' 12",rebuild=1)))657def dif1(prefix,pat="#mrk1"):658 ir1=compilev(pat)659 mo=ir1.findall(rfdtu(sys.argv[0]))660 for n,v in enumerate(mo):661 write8("r:\\"+prefix+"%d%d"%(n,len(v))+".txt",v)662def dif2(t1,t2):663 from difflib import HtmlDiff664 df = HtmlDiff()665 return df.make_file(t1,t2)666def charjunk(c):667 return c==" \t"668def dif3(t1,t2):669 import difflib as dif670 print=orro3(r"r:\tstDiff.txt")671 print("ndiff\n",lfjw(list(dif.ndiff(t1,t2))))672 dcd=dif.Differ().compare(t1,t2)673 print("compare",list(dcd))674 unif=list(dif.unified_diff(t1,t2))675 print("unified",lfjw(unif))676 #wel print("ndiff",list(dif.ndiff(t1,t2,charjunk=charjunk)))677 con=dif.context_diff(t1,t2)678 print("context",lfjw(con))679 ir1=dif.SequenceMatcher(None,t1,t2)680 print("opcodes ",ir1.ratio(),list(ir1.get_opcodes()))681 return jw(lf,unif)682 #683def dif3tst():684 import difflib as dif685 t1="am..==d"686 t2="pm..i=="687 l1=list(t1); l2=list(t2)688 ir1=dif.SequenceMatcher(None,t1,t2)689 mo=ir1.get_matching_blocks()690 print(ir1.ratio())#equal==1.0691 print(lf,t1,lf,t2,lf, list(mo))692 print(list(ir1.get_opcodes()))693 sys.exit()694def dif4(*T):695 import difflib as dif696 return lfjw(list(dif.unified_diff(*[t.splitlines() for t in T]))[2:])697def dif32(*T): return dif3(*[t.splitlines() for t in T])698def dif5(t1,t2, splitlines=str.splitlines):699 import difflib as dif700 f=(dif.SequenceMatcher(None,*[splitlines(t) for t in (t1,t2)]))701 return f.get_opcodes()702def difri(T,splitlines=fpreturn):703 import difflib as dif704 return (dif.SequenceMatcher(None,*[splitlines(t) for t in T]))705qfem="""706; ;;707: ;c708\\ ;y709/ ;l710" ;d711? ;q712< ;k713> ;r714| ;s715* ;a716"""#717q_fileEscapeMap={k:v for k,v in [k.split(" ") for k in qfem.split(lf) if k]}718##q_fileEscapeMap={";":";;",":":";c","\\":";y","/":";l",'"':";d","?":";q"}719def esfn(fn):#EscapeFileName;x/2720 return orsub(q_fileEscapeMap,fn );721def exfn(fn):#extract722 return orsub(puni(q_fileEscapeMap).tenchi(),fn);723time.perf_counter()724##def clock725def orbench(p):#BenchMark(Proc)K@milisecond726 t = time.perf_counter()727 tsai = time.perf_counter() - t728 t = time.perf_counter()729 rn=p()730 t = time.perf_counter() -t -tsai;731 return t,rn;732 733def cbbench(f):734## @functools.wraps(f)735 def cb(*a,**k):736 timeL=time.perf_counter()737 rn2=f(*a,**k)738 rn1=time.perf_counter()-timeL739 return rn1,rn2740 return cb741def timefor(cb,lis,to,start="start",logfile=""):742 def pr(te): return afdt(logfile or tfolder+"/log for time", te+lf)743 if start: pr(start)744 ti2pre=tia0=ti0=time.perf_counter()745 x9=len(lis)746 for x1,fn in enumerate(lis):747 et=cb(x1, fn, pr)748## if 1:749 ti2=time.perf_counter()750 eli=(ti2-ti0)751 x1p=x1+1752 ti9=eli/(x1p) * x9753 mean=eli/(x1p)754 one=ti2 - ti2pre755 ti2pre=ti2756 remain=ti9-eli757 if (ti2-tia0) > to[0]:758 te=et+f"({one:.1f}), {x1p}/{x9} , {eli:.1f} / {ti9:.1f}, {remain=:.1f}"759 print(te)760 pr(te)761 tia0=ti2762 if to[1] and eli > to[1]:return763 if et=="return": return et764 765#---------766def rnz(te,li,opt=re.S|re.I):767 for s,d in li:#src dist;768## pr(s,"__",d);769 ir=re.compile(s,opt);#DOTALL|IGNORE ##|re.X=VERBOSE770 te=ir.sub(d,te);771 return te772def rfor(url,li):773 for l in li:774 mo=re.match(l[0],url);775 if mo :return l[1]776 raise Exception ("no such url");777def sas(reg,te,bug=False,**ww):778 teli=[te]779 #reg=([(re.compile(f[0]),f[1]) for f in f2] for f2 in reg)780 reg=([re.compile(f,re.S) for f in f2] for f2 in reg)781 for ix,(ri,rx) in enumerate(reg):782 li2=[]783 for ta in teli:784 #li2.extend([f for f in ri[0].sub(lambda e:ri[0].sub(ri[1],e), ta) if f])785 li2.extend([f for f in ri.findall(ta) if f])786 teli=li2787 if bug: afdt(r"r:\fjpg-sas.txt","mrk{}\n".format(ix)+ppf(teli))788 return teli789def traverse(reg,te,bug=False,**ww):790 fn=reg; #fn.teli=[te]791 def fp1(fn,pare,F,after):792 if after:return793 fn.teli=[]794 for ta in pare.teli if pare else [te]:795 rin,rx1,rx2=fn.pat796 li=compilex(rin).findall(ta)797 for t1 in li:798 for rex in rx1:799 if rex.search(t1):continue800 fn.teli.append(t1)801 from mlwebOrWeb import webrap802## print(fn, f"{fn.flget=}")803 if fn.flget: #fn.teli=[ webrap().gtoff(f,"utf-8") for f in fn.teli]804 li=[]805 for n1,f in enumerate(fn.teli):806 print(f"download {n1+1} / {len(fn.teli)}")807 li.append(webrap().gtoff(f,"utf-8"))808 fn.teli=li809 def mimi(fn):return fn.mimi810 lamrec(fp1,fn, mimi,F=0,pare=None)811 return812if 0:813##class reg(re):814 def compile(me,*w):815 try:816 return re.compile(*w)817 except re.error as e:e818 def sub(me,*w):819 try:820 return me.sub(*w)821 except re.error as e:822 e823compilev=lambda e:re.compile(e,re.S|re.I|re.X|re.M)824compilevs=lambda e:re.compile(e.replace(" ","\\s*"),re.S|re.I)825compilex=lambda e:re.compile(e.replace(" ","\\s*"),re.S|re.I|re.X)826compiled=lambda e:re.compile(e,re.S|re.I)827compilefn=lambda e:re.compile(e,re.I)828irealpha=re.compile(r"[_\.a-zA-Z0-9]")829def adcompile(fp):830 if isinstance(fp,str): return compilevs(fp).search831 if isinstance(fp,re.Pattern): return fp.search832 return fp833 834 835 836# #-----------837def tae(p):#TryAndError例外で終了させずに表示する838 try:839 p()840 except Exception as e:841 orro4(e,lf,e.args,lf,type(e));842 return(e)843def t1t(p): return ttt(p,times=1)844def ttt(p,times=10,interval=4):# try ten times845 for n in range(times):846 try:847 return p()848 except Exception as e:849 if n+1 >= times: return e850 time.sleep(interval)851 continue852import th853cbTryLock=th.Lock()854def cbTry(f,ercb=None,lo=0,ww=(),pr=0):855## flq=1 if hasattr(f, "__self__") and isinstance(f.__self__, orq) else 0856## la=lambda e: a[1:]857 counter=0858 @functools.wraps(f)859 def cb(*a,**k):860 try:861 #return f(**k) if a[flq:] is (False,) else f(*a,**k)862## print("cb;", a,f,cb)863 #return f(**k) if not a[flq:] or a[flq] is False else f(*a,**k)864 if ww:865 wwa=ww[0]866 www=ww[1] if ww[1:] else {}867 if lo==1:lg("cb", f.__qualname__, a,k,ww)868 return f(*wwa,**k,**www) if not a or a[0] is False else f(*wwa, *a,**k,**www)#pass869 if lo==1:lg("cb", f.__qualname__, a,k)870 return f(**k) if not a or a[0] is False else f(*a,**k) #pass871 ##except: except2(0,find="p",edit="npp")872 except Exception as e: # exit is not exception873 #except:874 et=0875 cb.counter+=1876 if cb.counter>10:return877 if ercb: et=cbTry(ercb)(e)878 if et:return879 if pr: print(except2(0,find=""))880 else:881## with cbTryLock:#?882 except2(0,find="p",edit="note")883## e2=except2()884## Mini(te)885 cb.counter-=1886 cb.counter=0887 return cb888 889def edipt(te="",find="p",edit=0,fntbl=()):890 if edit:return edipt_edit(te,find,edit,fntbl)891 e2=te or traceback.format_exc()892 e2=e2.replace("Traceback (most recent call last):","-"*9)893 if find:894 if find=="p":895## mo=compiled((r'(?<= File ")(.*?)", line (\d+), in (.+?)\n(.*?)')).findall(e2)896 mo=compiled((r'(?<= File ")([^\n]+?)", line (\d+)(?:, in )?([^\n]*?)\n((?! File).*?(?=\n))?')).findall(e2)897 mo=[[fppmobile(f) for f in f2] for f2 in mo if not any(((compilex(r"/python|\\Python\\|importlib").search(f2[0])), ("#pass" in f2[-1]) )) ]898 return (fppmobile(omiterror(e2)),mo)899 if find=="node":900 mo=compiled(r'at ([\w\.]* )?\(?(C:.*?):(\d+):(\d+)').findall(e2)901 mo=[[fppmobile(f) for f in f2] for f2 in mo if not any(((compilex(r"/python|\\Python\\|importlib").search(f2[0])), ("//pass" in f2[-1]) )) ]902 mo=[[w[f] for f in (1,2,0,3)] for w in mo]903 return (fppmobile(omiterror(e2)),mo)904 if 0:905 mo=re.findall(r'"<string>", line (\d+)(), in <module>\n(.*)',e2)906 return mo907 return fppmobile(omiterror(e2))908except2=edipt909def edipt_edit(te,find,edit=0,fntbl=()):910 e2=edipt(te,find=find)911 t1=e2[0].splitlines().pop()912 if "dialog rejected;" in t1: return913 if "SystemExit" in t1: return914 from qNote1 import iniap, Mini, clhk915 from dialog_ import orDialog916 app=iniap()917 mono=orDialog()918 if not e2[1]: return Mini(e2)919 if find=="p":920 mo=[clhk(f, teh=(f"({cfile(f[0])}), {f[1]}, {f[2]}, \n{f[3]}")) for f in e2[1]]921 if find=="node":922 mo=[clhk(f, teh=(f"({cfile(f[0])}), {f[1]}, {f[2]}")) for f in e2[1]]923 if (mf:=re.search("AssertionError: (.*)", e2[0])): mo=[clhk("*", teh=mf.group(1))]+mo924 whw=[mo+[e2[0]]]925 mono.xch(whw)926 if not mono.fiFiles:return927 fn,*_=mono.pickupli()928 if type(fn)==str:return e2929 (fn,pos,mod,te)=fn930 if fn in fntbl: fn=fntbl[fn]931 print(fn,fntbl)932 #npp(fn,f"-n{pos}")933 orPOA([HeartNote, fn, "-pos",pos,"0"])934 return e2935def omiterror(e2):936 return rnz(e2,(937("NameError: name",""),938))939def mpvstring(e2):940 #t1=e2.splitlines().pop()941 e2=re.sub(r'Traceback .+?\n','',e2)942 e2=re.sub(r' File "C:\\cpy\\qt\\(?:clas\\)?(.+?)(?:\.pyw?)", line (\d+),',r'"\1",\2',e2)943 if "mpv property does not exist" in te:944 if(mo:=re.search(r"'(mpv property does not exist)',.*?b('.*?'),",te)): te=str(mo.groups())945 else: te="mpv not exist"946## te=rnz(te,(947## (r"'(mpv property does not exist)',.*?b('.*?'),",r"\1 \2"),948## (r"\d+",""),949## ))950def orpopen(mp3):951 import subprocess as p952 return p.Popen([mp3],shell=True);953def orPOA(cmd,shell=True):954 import subprocess as p955 return p.Popen(cmd,shell=shell);956def popen1(cmd,shell=True):957 import subprocess as p958 return p.Popen(cmd,shell=shell).wait()959##orPOA(r'start cmd /c "r:\c f.bat"')960def wiff(w):961 orPOA([ordiMdirs()["wiff"],*w])962def npp(*w):963 if not w: return ordiMdirs()["npp"]964 orPOA([ordiMdirs()["npp"],*w])965def nppw(lis,fn=tfolder+"/log"):966 wfd(fn).t(lis)967 npp(fn)968class puni(dict):969## def update(zl,k,v): dict.update(zl,[(k,v)])970 def ez(zl,k):#di.get()971 return zl[k] if(k in zl) else 0;972 def ud(zl,k,v):973 zl.update([(k,v)]);974 def up(zl,k,L):#update append975 if(k in zl):976 zl[k].append(L);977 else:978 zl.update([(k,[L])]);979 def uni(zl,k,L):#update append uni980 if(k in zl and L not in zl[k]):981 zl[k].append(L);982 else:983 zl.update([(k,[L])]);984 def setclr(zl,li,la):985 for nc,f in enumerate(li):986 k=la(f)987 zl.up(k,f)988 return zl989 def updateIncliment(zl,k):990 zl.ul(k,1)991 def ul(zl,k,L):#update vz Length992 if(k in zl):993 zl[k]+=L;994 else:995 zl[k]=L996 def us(zl,k):#文字ごとの生起確率997 for c in k:998 zl.ui(c);999 return zl;1000## def counter(zl,w):1001 def Clip(zl,count,regexpattern="."):1002 "Clip key less than count"1003 ire=re.compile(regexpattern)1004 return puni([(k,v) for k,v in zl.items() if(v>count)and(ire.match(k))])1005 def LetterFrequency(zl,te,llen=2):1006 for k in range(len(te)-llen+1):1007 zl.ui(te[k:k+llen])1008 return zl;1009 def sortedlist(zl):#oredered list by value;1010 return [[k,v] for k, v in sorted(zl.items(), key=lambda x:x[1])]1011 def olal(zl):#appended length1012 tl={k:len(v) for k,v in zl.items()}1013 return puni.ol(tl);1014 def ok(zl):#oredered list by key;1015 return [[k,v] for k, v in sorted(zl.items(), key=lambda x:x[0])]1016 def ovk(zl,valuekey):#sort by appended list1017 pass1018 def tenchi(zl):1019 li={v:k for k,v in zl.items()}1020## li=map(lambda x: x,li);1021 return li;1022 d=puni()1023 for k,v in zl.items():1024 d[v]=k;1025 return d;#X/21026 def xemj(zl,vn="v"):#moji for exec,Video1027 tef="";1028 for k in zl.keys():1029 tei="%s=%s[%s];"%(k,vn,repr(k));#tei=k+"="++";";1030 tef+=tei;1031 return tef;1032 def rms(zl,la):1033 pops={k:v for k,v in zl.items() if la(k,v)}1034 _=[zl.pop(k) for k in pops]1035 return zl,pops1036 #listDict1037 def lipop(zl,k,cb):1038 for k,v in zl.items():1039 for n,v1 in enumerate(v):1040 if(cb(v1)):return k,n1041 def lipop1(zl,f,te):1042 #{f,[[open,],[file,],[copy,],]};findcopy():lipop(f,"copy")1043 return zl.lipop(f,lambda e: e[0]==te)1044## def compres(zl,w0,fp=fpreturn,uni=0):1045## for f in w0:1046## zl.compresin(f,fp)1047## return zl1048 def compres(zl,f,fp=fpreturn,uni=0,te=""):#配列の長さは同じにする1049 z2=zl1050 if 1:1051 z2=zl1052 for w in f[:-1]:1053 w=fp(w)1054 if w not in z2: z2[w]=puni()1055 z2=z2[w]1056 assert isinstance(z2,puni), "not list len"#,f1057 if te:1058 assert f[-1] not in z2, "not list len. 123 12"#,f1059 z2[f[-1]]=te1060 else:1061 z2.ul(f[-1],1)1062 return z2[f[-1]]1063 def flat(zl):1064 li=[((x,),v) for x,v in zl.items()]1065 for p,v in li:1066 if isinstance(v,puni):1067 li.extend(((*p,p2),v2) for p2,v2 in v.items())1068 else:1069 yield (*p,v)1070class pini(puni):1071 def __init__(zl,d={},fn="pini00.ini"):1072 dict.__init__(zl,d);1073 zl.fn=lfn.abspath(fn);1074 if lfn.isfile(fn):1075 f=rfdv0(fn,["utf-8"])1076 for j in f:1077 a=j.split("\t");1078## try:1079## nm=float(a[1])1080## except:1081## pass;1082 if(len(a)== 2):1083## exete='zl["%s"]=' % a[0]#.replace("\\","\\\\");1084 exete='zl[%s]=' % a[0]#.replace("\\","\\\\");1085 et2= exete+a[1];1086 exec(et2);1087 else:1088 notTheFormat1089 def save(zl):1090 te="";1091 #print(os.getcwd())1092 for f,v in fpn1(zl):1093 ti= repr(f) +"\t" +repr(v)+"\n";1094 te+=ti;1095 wfd8(zl.fn,te);#Exceptions during cleanup are always ignored; see the object.__del__() documentation:1096## deli=__del__#for1097##class lazy:11098 ##diMdirs=None1099def ordiMdirs():# Dictionary of Directory1100 global diMdirs1101 diMdirs=globals().get("diMdirs") or dict([j.split("\t")[:2] for j in wfd(os.environ["cpa"]+r"\data\dirs-{}.txt".format(T45)).r(lines=True) if j[:2]])1102 return diMdirs1103def mdir(f): return ordiMdirs()[f]1104#1105def fFlat(li,lirn):1106 if(type(li)==list):1107 for j in li:1108 r1=fFlat(j,lirn)1109## lirn.extend(r1)1110 else:1111 r1=li1112 lirn.append(r1)1113 return lirn1114class List(list):1115 def rx(zl,te):1116 ir1=re.compile(te)1117 zl.res=[]1118 for i,j in enumerate(zl):1119 mo=ir1.search(j)1120 if mo:1121 zl.res.append(j)1122 return zl.res1123 def rxenu(zl,te):1124 ir1=re.compile(te)1125 zl.res=[]1126 for i,j in enumerate(zl):1127 mo=ir1.search(j)1128 if mo:1129 zl.res.append((i,j))1130 return zl.res1131 def __lt__(zl,f): return zl.append(f)1132 def __lshift__(zl,li): return zl.extend(li)1133 #def __getitem__(zl,f):1134 def getx(zl,f,v):1135 return zl.index(f) if f in zl else v1136 def u(zl,f,v):1137 zl[zl.index(f)]=v1138## def up(zl,v):1139orList=List1140class ListHash(List):#from collections import OrderedDict1141 def put(zl,k,v):#up1142 11143class orLiset(set):#unique list1144 pass1145 def cmp(zl,ot):1146 zl.cmp[x](zl[y],ot)1147## if(role=="cmp"):split(sel)1148 def get(zl,x,y,role="edit"):1149 return zl[y][x]1150class LastOperation(List):1151 def __init__(zl,li=(),threshold=30,wriIni=False,k="",uniq=True):1152 zl.threshold=threshold1153 zl.see=-11154 zl.uniq=uniq1155 if(wriIni):#dict.setdefault()1156 if(k in wriIni):1157 li=wriIni[k]1158 list.__init__(zl,li)1159 wriIni[k]=zl1160 else:1161 list.__init__(zl,li)1162 def rm(zl,te):1163 if zl.uniq and (te in zl):1164 zl.pop(zl.index(te))1165 def ap(zl,te):1166 if zl.uniq and (te in zl):1167 zl._ap(zl.pop(zl.index(te)))1168 else:1169 if(len(zl)>=zl.threshold):zl.pop()1170 zl._ap(te)1171 zl.see=01172 def aprx(zl,te):#Word completion1173 if zl.uniq and (zl.get(te)):1174 zl._ap(zl.pop(zl.res[0][0]))1175 else:1176 if(len(zl)>=zl.threshold):zl.pop()1177 zl._ap(te)1178 zl.see=01179## def _ap(zl,element):1180## zl.insert(0,element)1181 _ap=lambda zl,x:zl.insert(0,x)1182 def get(zl,te):1183 r=zl.rxenu(te)1184 return r[0]1185 def up(zl):1186 if(len(zl)-1>zl.see):1187 zl.see+=11188 return zl[zl.see]1189 def down(zl):1190 if(zl.see>0):1191 zl.see-=11192 return zl[zl.see]1193clHistry=LastOperation1194##class cycle():1195class orLog(LastOperation):1196 def __call__(zl,*w):1197 if(len(zl)>=zl.threshold):zl.pop(0)1198 zl.append((w[0],w[1:]))1199 return zl1200 def __repr__(zl):