repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
snabbnfv-goodies/snabbswitch
lib/luajit/src/jit/dis_x86.lua
61
29376
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM) -- instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. -- * The public API may change when more architectures are added. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep local bit = require("bit") local tohex = bit.tohex -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrm|movupdXrm|movsdXrm", "movupsXmr|movssXmr|movupdXmr|movsdXmr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrm||unpcklpdXrm", "unpckhpsXrm||unpckhpdXrm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm", "andpsXrm||andpdXrm","andnpsXrm||andnpdXrm", "orpsXrm||orpdXrm","xorpsXrm||xorpdXrm", "addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm", "cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm", "divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm", --6x "punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm", "pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm", "punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm", "||punpcklqdqXrm","||punpckhqdqXrm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu", "pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu", "pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|", "pinsrwPrWmu","pextrwDrPmu", "shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm", "paddqPrm","pmullwPrm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrm","psubuswPrm","pminubPrm","pandPrm", "paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm", --Ex "pavgbPrm","psrawPrm","psradPrm","pavgwPrm", "pmulhuwPrm","pmulhwPrm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrm","psubswPrm","pminswPrm","porPrm", "paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm", --Fx "|||lddquXrm","psllwPrm","pslldPrm","psllqPrm", "pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$", "psubbPrm","psubwPrm","psubdPrm","psubqPrm", "paddbPrm","paddwPrm","padddPrm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm", "pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm", "psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm", nil,nil,nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm", nil,nil,nil,nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm", nil,nil,nil,nil, --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm", "||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm", "||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm", --4x "||pmulddXrm","||phminposuwXrm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]=nil,nil,nil,nil,nil,nil,nil,nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu", "||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", nil,nil,nil,nil,nil,nil,nil,nil, --2x "||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil, --4x [0x40] = "||dppsXrmu", [0x41] = "||dppdXrmu", [0x42] = "||mpsadbwXrmu", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "") if t ~= "" then text = "rex."..t.." "..text end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop = ctx.code, ctx.pos, ctx.stop -- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXFG]") then sz = p regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = "0x"..tohex(imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = true end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") end, } ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = (addr or 0) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64(code, addr, out) local ctx = create(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end local function disass64(code, addr, out) create64(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. return { create = create, create64 = create64, disass = disass, disass64 = disass64, regname = regname, regname64 = regname64 }
apache-2.0
BrasileiroGamer/TrineEE_TranslationTools
translations/portuguese/lua/data/locale/gui/pt/menu/mainmenu/achievementsmenu.lua
1
15841
-- /data/locale/gui/$$/menu/mainmenu/achievementsmenu.lua headerAchievements = "Conquistas" titlesurf = " Surfboard Master" titlehazard = " I Didn't Do It" titlesolo = " Flying Solo" titlecarni = " A Floral Feast" titleshatter = " Icebreaker" titlehammer = " Hammer Havoc" titlefriendly_fire = " Dirty Tactics" titlebounce = " Bouncy Bouncy" titlearrow = " A Hail Of Arrows" titletower = " High Rise" titlerope = " Cirque de Zoya" titlebubble = " This Wasn't the Plan" titleplatinum = " Trine Hard" titlegame_completed = " I want more!" titlelevel1_completed = " Into the Story" titlelevel2_completed = " Wild in Wilderness" titlelevel3_completed = " Mudproof Hero" titlelevel4_completed = " March Through the Marsh" titlelevel5_completed = " Treehouse Adventure" titlelevel6_completed = " No More Lizard Soup" titlelevel7_completed = " Hostile Gardening" titlelevel8_completed = " Funs with Fungi" titlelevel9_completed = " Shrooms and Glooms" titlelevel10_completed = " Pearl Diver" titlelevel11_completed = " Sinister Plumbing" titlelevel12_completed = " Hot and Cold" titlelevel13_completed = " Through Dangers Untold" titlelevel1_exp = " The Story Begins Collector" titlelevel2_exp = " Forlorn Wilderness Collector" titlelevel3_exp = " Mudwater Dale Collector" titlelevel4_exp = " Mosslight Marsh Collector" titlelevel5_exp = " Petrified Tree Collector" titlelevel6_exp = " Shadowed Halls Collector" titlelevel7_exp = " Hushing Grove Collector" titlelevel8_exp = " Mushroom Caves Collector" titlelevel9_exp = " Mushroom Murk Collector" titlelevel10_exp = " Searock Castle Collector" titlelevel11_exp = " Eldritch Passages Collector" titlelevel12_exp = " Icewarden Keep Collector" titlelevel1_chest = " Introductory Secrets" titlelevel2_chest = " Secrets of Forlorn Wilderness" titlelevel3_chest = " Secrets of Mudwater Dale" titlelevel4_chest = " Secrets of Mosslight Marsh" titlelevel5_chest = " Secrets of Petrified Tree" titlelevel6_chest = " Secrets of Shadowed Halls" titlelevel7_chest = " Secrets of Hushing Grove" titlelevel8_chest = " Secrets of Mushroom Caves" titlelevel9_chest = " Secrets of Mushroom Murk" titlelevel10_chest = " Secrets of Searock Castle" titlelevel11_chest = " Secrets of Eldritch Passages" titlelevel12_chest = " Secrets of Icewarden Keep" titlelevel13_chest = " Rosabel's Secrets" titleexpbottle = " Sharp-Eyed" titleallexp = " Master Collector" titleallchest = " Lost and Found" titlefrozen_tower = " Snowman" titlehard_hc = " Challenge is My Middle Name" titleallhc = " Walk in the Park" titlesolo_amadeus = " O Solo Mio" titlesolo_zoya = " Like a Shadow" titlesolo_pontius = " Alone and Mighty" titlesolo_all = " Trine Kaput?" titlecharge = " Catch This!" titleno_damage = " All Too Easy!" titlepontiustower = " The Leaning Tower of Pontius" titlelevel14_completed = " No Time to Change Clothes" titlelevel15_completed = " Sunstroke" titlelevel16_completed = " Indigestion" titlelevel17_completed = " Grand Theft Aviation" titlelevel18_completed = " I'm Walking in the Air" titlelevel19_completed = " Happy Reunion" titlelevel14_exp = " The Heroes Return Collector" titlelevel15_exp = " Deadly Dustland Collector" titlelevel16_exp = " Belly of the Beast Collector" titlelevel17_exp = " Brackenridge Rise Collector" titlelevel18_exp = " Cloudy Isles Collector" titlelevel14_chest = " Secrets of the Heroes Return" titlelevel15_chest = " Secrets of Deadly Dustland" titlelevel16_chest = " Secrets of Belly of the Beast" titlelevel17_chest = " Secrets of Brackenridge Rise" titlelevel18_chest = " Secrets of Cloudy Isles" titleallchest_dlc = " The Treasurer" titleexpbottle_dlc = " Sharpeyed II (Complete Story)" titleallexp_dlc = " Complete Story Collector" titleplatinum_dlc = " Trine Hard II (Complete Story)" titletrapstack = " Wicked Collection" titleallexp_both = " Grand Collector" titlegrenade = " Cannonball Rebound" titlesandworm = " Mutually Assured Destruction" titleair_hammer = " Pontius Baseball" titlehard_hc_dlc = " Rise to the Challenge" titlesolo_dlc_levels = " Trine Kaput For Good?" titleallhc_dlc = " Easy as Pie" titlecatch = " Play Catch" titleraft = " Rafting" titlepontiusglide = " Pontius Transportation Company" titlepit = " This is Trine!" titlecatapult = " Off You Go" descsurf = "Fique em uma prancha flutuando em um único fluxo de ar por quatro segundos" deschazard = "Faça os goblins morrerem de três perigos ambientais diferentes em um único nível" descsolo = "Completa um nível inteiro jogando apenas com um personagem" desccarni = "Alimente plantas carnívoras com três ou mais tipos diferentes de alimentos" descshatter = "Destrua três inimigos congelados dentro de um segundo" deschammer = "Mate um inimigo com um martelo lançado quicando pelo menos uma vez antes de matar" descfriendly_fire = "Obtenha 10 inimigos mortos por ações de outros inimigos em um único nível" descbounce = "Fique em uma caixa conjurada saltando em qualquer superfície saltadora por 10 segundos" descarrow = "Atire três flechas no ar e pegue todas elas com o escudo do Cavaleiro" desctower = "Construa uma torre feita de oito objetos e fique em cima dela" descrope = "Usando o gancho, balance em torno de um objeto e agarre-se novamente com o gancho sem tocar em qualquer superfície" descbubble = "Faça uma pia de bolha por três segundos" descplatinum = "Consiga todas as Conquistas em Trine" descgame_completed = "Complete the game" desclevel1_completed = "Complete The Story Begins" desclevel2_completed = "Complete Forlorn Wilderness" desclevel3_completed = "Complete Mudwater Dale" desclevel4_completed = "Complete Mosslight Marsh" desclevel5_completed = "Complete Petrified Tree" desclevel6_completed = "Complete Shadowed Halls" desclevel7_completed = "Complete Hushing Grove" desclevel8_completed = "Complete Mushroom Caves" desclevel9_completed = "Complete Mushroom Murk" desclevel10_completed = "Complete Searock Castle" desclevel11_completed = "Complete Eldritch Passages" desclevel12_completed = "Complete Icewarden Keep" desclevel13_completed = "Complete The Final Chapter" desclevel1_exp = "Collect all level experience in The Story Begins" desclevel2_exp = "Collect all level experience in Forlorn Wilderness" desclevel3_exp = "Collect all level experience in Mudwater Dale" desclevel4_exp = "Collect all level experience in Mosslight Marsh" desclevel5_exp = "Collect all level experience in Petrified Tree" desclevel6_exp = "Collect all level experience in Shadowed Halls" desclevel7_exp = "Collect all level experience in Hushing Grove" desclevel8_exp = "Collect all level experience in Mushroom Caves" desclevel9_exp = "Collect all level experience in Mushroom Murk" desclevel10_exp = "Collect all level experience in Searock Castle" desclevel11_exp = "Collect all level experience in Eldritch Passages" desclevel12_exp = "Collect all level experience in Icewarden Keep" desclevel13_exp = "Collect all level experience in The Final Chapter" desclevel2_chest = "Find all chests in Forlorn Wilderness" desclevel3_chest = "Find all chests in Mudwater Dale" desclevel4_chest = "Find all chests in Mosslight Marsh" desclevel5_chest = "Find all chests in Petrified Tree" desclevel6_chest = "Find all chests in Shadowed Halls" desclevel7_chest = "Find all chests in Hushing Grove" desclevel8_chest = "Find all chests in Mushroom Caves" desclevel9_chest = "Find all chests in Mushroom Murk" desclevel10_chest = "Find all chests in Searock Castle" desclevel11_chest = "Find all chests in Eldritch Passages" desclevel12_chest = "Find all chests in Icewarden Keep" desclevel13_chest = "Find all chests in The Final Chapter" descexpbottle = "Collect all level experience in any level" descallexp = "Collect all level experience in the game" descallchest = "Find all chests in the game" descfrozen_tower = "Freeze two enemies and stack them on top of each other" deschard_hc = "Complete any level with hardcore mode on and difficulty set to hard" descallhc = "Complete the game on hard using hardcore mode" descsolo_amadeus = "Complete a level with only Amadeus" descsolo_zoya = "Complete a level with only Zoya" descsolo_pontius = "Complete a level with only Pontius" descsolo_all = "Complete a level with only Amadeus, a level with only Zoya and a level with only Pontius" desccharge = "Kill an enemy with an airborne object tossed with the Knight's charge" descno_damage = "Finish a level without taking any damage (except in the Story Begins)" descpontiustower = "Build a three-piece or three-character tower where lowest part is Pontius and his shield, tower must stand at least five seconds" desclevel14_completed = "Complete The Heroes Return" desclevel15_completed = "Complete Deadly Dustland" desclevel16_completed = "Complete Belly of the Beast" desclevel17_completed = "Complete Brackenridge Rise" desclevel18_completed = "Complete Cloudy Isles" desclevel19_completed = "Complete Goblin Machinations" desclevel14_exp = "Collect all level experience in The Heroes Return" desclevel15_exp = "Collect all level experience in Deadly Dustland" desclevel16_exp = "Collect all level experience in Belly of the Beast" desclevel17_exp = "Collect all level experience in Brackenridge Rise" desclevel18_exp = "Collect all level experience in Cloudy Isles" desclevel14_chest = "Find all secret chests in The Heroes Return" desclevel15_chest = "Find all secret chests in Deadly Dustland" desclevel16_chest = "Find all secret chests in Belly of the Beast" desclevel17_chest = "Find all secret chests in Brackenridge Rise" desclevel18_chest = "Find all secret chests in Cloudy Isles" descallchest_dlc = "Find all chests in the Complete Story levels" descexpbottle_dlc = "Find all level experience in any of the Complete Story levels" descallexp_dlc = "Collect all level experience in the Complete Story levels" descplatinum_dlc = "Earn all Achievements in Trine: Complete Story levels" desctrapstack = "Capture three different types of enemies inside boxes and stack them on top of another" descallexp_both = "Collect all experience pickups in both the main game and the Complete Story levels" descgrenade = "Kill a grenadier goblin with its own cannonball" descsandworm = "Make a sandworm kill another sandworm" descair_hammer = "Launch an object with Knight's magnetic shield and break it with hammer before the object touches the ground" deschard_hc_dlc = "Complete any Complete Story level with hardcore mode on and difficulty set to hard" descsolo_dlc_levels = "Complete Complete Story levels using only one character" descallhc_dlc = "Complete the Complete Story levels on hard using hardcore mode" desccatch = "Throw a box with Pontius' magnetic shield and catch it or have another player catch it" descraft = "Create a makeshift raft of three separate parts and have a goblin sail it for five seconds" descpontiusglide = "Glide for five seconds with Kitesail Shield while having an object or character on top of the shield" descpit = "Kick five enemies of the same kind into a bottomless pit with the Thief's grappling hook kick or the Knight's Kitesail Shield glide kick" desccatapult = "Capture a goblin in a Monster Prison and then launch it with a catapult" titlecomplete_tutorial_level = " Astral Introduction" titlecollect_shards_tutorial1 = " Academy Master" titlecollect_shards_castle1 = " Hallways Master" titlecollect_shards_courtyard1 = " Wolvercote Master" titlecollect_shards_cemetery1 = " Graveyard Master" titlecollect_shards_crypt1 = " Caverns Master" titlecollect_shards_darkcrypt1 = " Crypt Master" titlecollect_shards_castle2 = " Dungeon Master" titlecollect_shards_castle3 = " Castle Master" titlecollect_shards_forest1 = " Forest Master" titlecollect_shards_darkforest1 = " Thicket Master" titlecollect_shards_forest2 = " Ruins Master" titlecollect_shards_mines1 = " Mines Master" titlecollect_shards_village1 = " Village Master" titlecollect_shards_castle5 = " Forge Master" titlecollect_shards_bossarea = " Tower Master" titlecollect_shards_all = " Master Collector" titlecomplete_boss_level = " Completed" titlecomplete_game_in_very_hard = " What's next?" titlefind_all_secrets = " Treasure Hunter" titlebuild_tower = " What a view!" titlethrow_kill_combo = " Whoops!" titlecomplete_boss_level_without_deaths_in_very_hard = " Better Than Developers!" titlekill_with_many_styles = " The Cool Way" titlecomplete_level_no_damage = " Survivalist" titlecomplete_level_many_deaths = " Dead on Arrival" titlecreate_many_objects = " Still no fireball" titlecomplete_level_no_kills = " Undead have rights, too!" titleskeleton_jumping = " Spring master" titleall_complete = " Way Out of the Trine" titlepro_diving = " Summer Dip" titlepresent = " Winter Secrets" titleenchanted = " Enchanted" desccomplete_tutorial_level = "Complete Astral Academy" desccollect_shards_tutorial1 = "Collect all experience in Astral Academy" desccollect_shards_castle1 = "Collect all experience in Academy Hallways" desccollect_shards_courtyard1 = "Collect all experience in Wolvercote Catacombs" desccollect_shards_cemetery1 = "Collect all experience in Dragon Graveyard" desccollect_shards_crypt1 = "Collect all experience in Crystal Caverns" desccollect_shards_darkcrypt1 = "Collect all experience in Crypt of the Damned" desccollect_shards_castle2 = "Collect all experience in Forsaken Dungeons" desccollect_shards_castle3 = "Collect all experience in Throne of the Lost" desccollect_shards_forest1 = "Collect all experience in Fangle Forest" desccollect_shards_darkforest1 = "Collect all experience in Shadowthorn Thicket" desccollect_shards_forest2 = "Collect all experience in Ruins of the Perished" desccollect_shards_mines1 = "Collect all experience in Heartland Mines" desccollect_shards_village1 = "Collect all experience in Bramblestoke Village" desccollect_shards_castle5 = "Collect all experience in Iron Forge" desccollect_shards_bossarea = "Collect all experience in Tower of Sarek" desccollect_shards_all = "Collect all experience in the game" desccomplete_boss_level = "Complete the entire game" desccomplete_game_in_very_hard = "Complete the entire game on hardest difficulty (Hardcore mode not required)" descfind_all_secrets = "Find all secret items in every level" descbuild_tower = "Build a tower with at least 12 Wizard-created objects and stand on top of the tower without collapsing it" descthrow_kill_combo = "Kill 3 monsters with a single physical object drop or throw" desccomplete_boss_level_without_deaths_in_very_hard = "Complete Tower of Sarek without any deaths on hardest difficulty (Hardcore mode not required)" desckill_with_many_styles = "In a single level, kill one monster by jumping on it with the Knight, one with the Wizard's abilities and one with the Thief's grappling hook kick" desccomplete_level_no_damage = "Survive a level other than Astral Academy without any damage" desccomplete_level_many_deaths = "Complete a level with 25 or more character deaths" desccreate_many_objects = "Conjure 200 objects in a single level" desccomplete_level_no_kills = "Complete a level other than Astral Academy without directly killing any enemies" descskeleton_jumping = "Complete at least 3 jumps in a row on different skeletons without touching the ground" descall_complete = "Earn all Achievements in Trine" descpro_diving = "Stay underwater for more than 20 seconds without taking damage" descpresent = "Find the Academic, Bony and Crystalline holiday secret gifts" descenchanted = "Launch the Enchanted Edition of the game"
gpl-3.0
hnyman/luci
applications/luci-app-splash/luasrc/model/cbi/splash/splash.lua
10
3006
-- Licensed to the public under the Apache License 2.0. require("luci.model.uci") m = Map("luci_splash", translate("Client-Splash"), translate("Client-Splash is a hotspot authentication system for wireless mesh networks.")) s = m:section(NamedSection, "general", "core", translate("General")) s.addremove = false s:option(Value, "leasetime", translate("Clearance time"), translate("Clients that have accepted the splash are allowed to use the network for that many hours.")) local redir = s:option(Value, "redirect_url", translate("Redirect target"), translate("Clients are redirected to this page after they have accepted the splash. If this is left empty they are redirected to the page they had requested.")) redir.rmempty = true s:option(Value, "limit_up", translate("Upload limit"), translate("Clients upload speed is limited to this value (kbyte/s)")) s:option(Value, "limit_down", translate("Download limit"), translate("Clients download speed is limited to this value (kbyte/s)")) s:option(DummyValue, "_tmp", "", translate("Bandwidth limit for clients is only activated when both up- and download limit are set. " .. "Use a value of 0 here to completely disable this limitation. Whitelisted clients are not limited.")) s = m:section(TypedSection, "iface", translate("Interfaces"), translate("Interfaces that are used for Splash.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true local uci = luci.model.uci.cursor() zone = s:option(ListValue, "zone", translate("Firewall zone"), translate("Splash rules are integrated in this firewall zone")) uci:foreach("firewall", "zone", function (section) zone:value(section.name) end) iface = s:option(ListValue, "network", translate("Network"), translate("Intercept client traffic on this Interface")) uci:foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface:value(section[".name"]) end end) uci:foreach("network", "alias", function (section) iface:value(section[".name"]) end) s = m:section(TypedSection, "whitelist", translate("Whitelist"), translate("MAC addresses of whitelisted clients. These do not need to accept the splash and are not bandwidth limited.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s:option(Value, "mac", translate ("MAC Address")) s = m:section(TypedSection, "blacklist", translate("Blacklist"), translate("MAC addresses in this list are blocked.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s:option(Value, "mac", translate ("MAC Address")) s = m:section(TypedSection, "subnet", translate("Allowed hosts/subnets"), translate("Destination hosts and networks that are excluded from splashing, i.e. they are always allowed.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s:option(Value, "ipaddr", translate("IP Address")) s:option(Value, "netmask", translate("Netmask"), translate("optional when using host addresses")).rmempty = true return m
apache-2.0
rrze-likwid/likwid
src/applications/likwid-genTopoCfg.lua
1
6123
#!<INSTALLED_BINPREFIX>/likwid-lua --[[ * ======================================================================================= * * Filename: likwid-genTopoCfg.lua * * Description: A application to create a file of the underlying system configuration * that is used by likwid to avoid reading the systems architecture at * each start. * * Version: <VERSION> * Released: <DATE> * * Author: Thomas Roehl (tr), thomas.roehl@gmail.com * Project: likwid * * Copyright (C) 2016 RRZE, University Erlangen-Nuremberg * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * ======================================================================================= ]] package.path = '<INSTALLED_PREFIX>/share/lua/?.lua;' .. package.path local likwid = require("likwid") print_stdout = print print_stderr = function(...) for k,v in pairs({...}) do io.stderr:write(v .. "\n") end end local filename = "<INSTALLED_PREFIX>/etc/likwid_topo.cfg" function version() print_stdout(string.format("likwid-genTopoCfg -- Version %d.%d.%d (commit: %s)",likwid.version,likwid.release,likwid.minor,likwid.commit)) end function usage() version() print_stdout("A tool to store the system's architecture to a config file for LIKWID.\n") print_stdout("Options:") print_stdout("-h, --help\t\t Help message") print_stdout("-v, --version\t\t Version information") print_stdout("-o, --output <file>\t Use <file> instead of default "..filename) print_stdout("\t\t\t Likwid searches at startup per default:") print_stdout("\t\t\t /etc/likwid_topo.cfg and <INSTALLED_PREFIX>/etc/likwid_topo.cfg") print_stdout("\t\t\t Another location can be configured in the configuration file /etc/likwid.cfg,") print_stdout("\t\t\t <INSTALLED_PREFIX>/etc/likwid.cfg or the path defined at the build process of Likwid.") end for opt,arg in likwid.getopt(arg, {"h","v","help","version", "o:", "output:"}) do if opt == "h" or opt == "help" then usage() os.exit(0) elseif opt == "v" or opt == "version" then version() os.exit(0) elseif opt == "o" or opt == "output" then filename = arg elseif opt == "?" then print_stderr("Invalid commandline option -"..arg) os.exit(1) elseif opt == "!" then print_stderr("Option requires an argument") os.exit(1) end end local file = io.open(filename, "r") if file ~= nil then print_stderr("File "..filename.." exists, please delete it first.") file:close() os.exit(1) end file = io.open(filename, "w") if file == nil then print_stderr("Cannot open file "..filename.." for writing") os.exit(1) end local cpuinfo = likwid.getCpuInfo() local cputopo = likwid.getCpuTopology() local numainfo = likwid.getNumaInfo() local affinity = likwid.getAffinityInfo() if cpuinfo == nil or cputopo == nil or numainfo == nil or affinity == nil then print_stderr("Cannot initialize topology module of LIKWID") os.exit(1) end print_stdout(string.format("Writing new topology file %s", filename)) cpuinfo["clock"] = likwid.getCpuClock() local threadPool_order = {"threadId", "coreId", "packageId", "apicId"} local cacheLevels_order = {"type", "associativity", "sets", "lineSize", "size", "threads", "inclusive"} for field, value in pairs(cpuinfo) do file:write("cpuid_info " .. field .. " = " .. tostring(value).."\n") end for field, value in pairs(cputopo) do if (field ~= "threadPool" and field ~= "cacheLevels" and field ~= "topologyTree") then if field ~= "activeHWThreads" then file:write("cpuid_topology " .. field .. " = " .. tostring(value).."\n") end elseif (field == "threadPool") then --file:write("cpuid_topology threadPool count = "..tostring(likwid.tablelength(cputopo["threadPool"])).."\n") for id, tab in pairs(cputopo["threadPool"]) do str = "cpuid_topology threadPool "..tostring(id).." " for k,v in pairs(threadPool_order) do file:write(str..tostring(v).." = "..tostring(tab[v]).."\n") end end elseif (field == "cacheLevels") then for id, tab in pairs(cputopo["cacheLevels"]) do str = "cpuid_topology cacheLevels "..tostring(id).." " for k,v in pairs(cacheLevels_order) do file:write(str..tostring(v).." = "..tostring(tab[v]).."\n") end end end end file:write("numa_info numberOfNodes = "..tostring(numainfo["numberOfNodes"]).."\n") for field, value in pairs(numainfo["nodes"]) do for id, tab in pairs(value) do if id ~= "processors" and id ~= "distances" then file:write("numa_info nodes "..tostring(field).." "..tostring(id).." = "..tostring(tab).."\n") elseif id == "processors" then for k,v in pairs(tab) do str = str..","..tostring(v) file:write("numa_info nodes "..tostring(field).." "..tostring(id).." "..tostring(k).." = "..tostring(v).."\n") end elseif id == "distances" then for k,v in pairs(tab) do for k1,v1 in pairs(v) do file:write("numa_info nodes "..tostring(field).." "..tostring(id).." "..tostring(k1).." = "..tostring(v1).."\n") end end end end end file:close() likwid.putAffinityInfo() likwid.putNumaInfo() likwid.putTopology()
gpl-3.0
LaFamiglia/Illarion-Content
base/doors.lua
1
5506
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local M = {} OpenDoors = {}; ClosedDoors = {}; --[[ AddToDoorList This is a helper function to fill the door list. It is removed after the initialisation. @param integer - the ID of the opened door of a opened closed door pair @param integer - the ID of the closed door of a opened closed door pair ]] function AddToDoorList(openedID, closedID) OpenDoors[openedID] = closedID; ClosedDoors[closedID] = openedID; end; AddToDoorList(86, 497); AddToDoorList(87, 922); AddToDoorList(927, 925); AddToDoorList(317, 926); AddToDoorList(476, 480); AddToDoorList(477, 481); AddToDoorList(478, 482); AddToDoorList(479, 483); AddToDoorList(499, 903); AddToDoorList(900, 904); AddToDoorList(901, 905); AddToDoorList(902, 906); AddToDoorList(484, 486); AddToDoorList(485, 487); AddToDoorList(924, 496); AddToDoorList(923, 920); AddToDoorList(668, 656); AddToDoorList(669, 657); AddToDoorList(660, 648); AddToDoorList(661, 649); AddToDoorList(684, 652); AddToDoorList(685, 653); AddToDoorList(664, 644); AddToDoorList(665, 645); AddToDoorList(666, 654); AddToDoorList(670, 658); AddToDoorList(671, 659); AddToDoorList(667, 655); AddToDoorList(662, 650); AddToDoorList(686, 646); AddToDoorList(663, 651); AddToDoorList(687, 647); AddToDoorList(715, 711); AddToDoorList(714, 710); AddToDoorList(712, 708); AddToDoorList(713, 709); AddToDoorList(865, 861); AddToDoorList(866, 862); AddToDoorList(867, 863); AddToDoorList(868, 864); AddToDoorList(944, 943); AddToDoorList(946, 945); AddToDoorList(948, 947); AddToDoorList(950, 949); AddToDoorList(1112, 1108); AddToDoorList(1113, 1109); AddToDoorList(1114, 1110); AddToDoorList(1115, 1111); AddToDoorList(3168, 3164); AddToDoorList(3169, 3165); AddToDoorList(3170, 3166); AddToDoorList(3171, 3167); AddToDoorList(3228, 3224); AddToDoorList(3229, 3225); AddToDoorList(3230, 3226); AddToDoorList(3231, 3227); AddToDoorList(3234, 3232); AddToDoorList(3235, 3233); AddToDoorList(3238, 3236); AddToDoorList(3239, 3237); AddToDoorList(3318, 3314); AddToDoorList(3319, 3315); AddToDoorList(3320, 3316); AddToDoorList(3321, 3317); AddToDoorList(3481, 3477); AddToDoorList(3482, 3478); AddToDoorList(3483, 3479); AddToDoorList(3484, 3480); AddToDoorList(3489, 3485); AddToDoorList(3490, 3486); AddToDoorList(3491, 3487); AddToDoorList(3492, 3488); AddToDoorList(3284, 3200); AddToDoorList(3285, 3201); AddToDoorList(3202, 3282); AddToDoorList(3203, 3283); AddToDoorList = nil; --[[ GetDoorItem Check if there is a item that is a door at a specified location and get the item struct of this item. @param PositionStruct - the position that shall be searched @return ItemStruct - the door item that was found or nil ]] function GetDoorItem(Posi) local items = common.GetItemsOnField(Posi); for _, item in pairs(items) do if (OpenDoors[item.id] or ClosedDoors[item.id]) then return item; end; end; return nil; end; --[[ CheckOpenDoor Check if this a item ID is a opened door. @param integer - the ID of the item that shall be checked @return boolean - true in case the item is a opened door, else false ]] function M.CheckOpenDoor(DoorID) return (OpenDoors[DoorID] ~= nil); end; --[[ CheckClosedDoor Check if this a item ID is a closed door. @param integer - the ID of the item that shall be checked @return boolean - true in case the item is a closed door, else false ]] function M.CheckClosedDoor(DoorID) return (ClosedDoors[DoorID] ~= nil); end; --[[ CloseDoor Close a opened door item by swapping the item. @param ItemStruct - the door item that shall be turned to a closed door @ewruen boolean - true in case the door got closed, false if something went wrong ]] function M.CloseDoor(Door) if OpenDoors[Door.id] then world:swap(Door, OpenDoors[Door.id], 233); world:makeSound(21, Door.pos); return true; end; return false; end; --[[ OpenDoor Open a closed door item by swapping the item. That function performs the check if the door is unlocked or has no lock and only opens the door in this case. @param ItemStruct - the door item that shall be turned to a opened door @return boolean, boolean - the first return value is true in case the door item was found and it wound be possible to open it, the second value is true in case the door really got opened and false if it was locked ]] function M.OpenDoor(Door) if ClosedDoors[Door.id] then if Door:getData("lockId") == "" or Door:getData("doorLock")=="unlocked" then world:swap(Door, ClosedDoors[Door.id], 233); world:makeSound(21, Door.pos); return true, true; end return true, false; end return false, false; end return M
agpl-3.0
LaFamiglia/Illarion-Content
triggerfield/donation_cadomyr.lua
1
1750
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO triggerfields VALUES (115,520,0,'triggerfield.donation_cadomyr'); -- INSERT INTO triggerfields VALUES (115,521,0,'triggerfield.donation_cadomyr'); -- INSERT INTO triggerfields VALUES (116,520,0,'triggerfield.donation_cadomyr'); -- INSERT INTO triggerfields VALUES (116,521,0,'triggerfield.donation_cadomyr'); local common = require("base.common") local donation_base = require("triggerfield.base.donation") local M = {} -- Donation to the Cadomyr treasury -- 115, 552, 0 = Cadomyr function M.PutItemOnField(Item,User) local donated = donation_base.donate(Item, User, "Cadomyr", "Rosaline Edwards", "TreasureCadomyr") -- That's all folks -- Quest 151 (Cadomyr Treasury, NPC Ioannes Faber) if (donated) and (User:getQuestProgress(151) == 1) then User:setQuestProgress(151, 2) --Quest solved! common.InformNLS(User, "[Queststatus] Du hast den Befehl erfolgreich ausgeführt. Kehre zu Ioannes Faber zurück, um deine Belohnung einzufordern.", "[Quest status] You completed your task successfully. Return to Ioannes Faber to claim your reward.") end end return M
agpl-3.0
Jichao/skia
tools/lua/paths.lua
92
3129
-- -- Copyright 2014 Google Inc. -- -- Use of this source code is governed by a BSD-style license that can be -- found in the LICENSE file. -- -- Path scraping script. -- This script is designed to count the number of times we fall back to software -- rendering for a path in a given SKP. However, this script does not count an exact -- number of uploads, since there is some overlap with clipping: e.g. two clipped paths -- may cause three uploads to the GPU (set clip 1, set clip 2, unset clip 2/reset clip 1), -- but these cases are rare. draws = 0 drawPaths = 0 drawPathsAnti = 0 drawPathsConvexAnti = 0 clips = 0 clipPaths = 0 clipPathsAnti = 0 clipPathsConvexAnti = 0 usedPath = false usedSWPath = false skpsTotal = 0 skpsWithPath = 0 skpsWithSWPath = 0 function sk_scrape_startcanvas(c, fileName) usedPath = false usedSWPath = false end function sk_scrape_endcanvas(c, fileName) skpsTotal = skpsTotal + 1 if usedPath then skpsWithPath = skpsWithPath + 1 if usedSWPath then skpsWithSWPath = skpsWithSWPath + 1 end end end function string.starts(String,Start) return string.sub(String,1,string.len(Start))==Start end function isPathValid(path) if not path then return false end if path:isEmpty() then return false end if path:isRect() then return false end return true end function sk_scrape_accumulate(t) if (string.starts(t.verb, "draw")) then draws = draws + 1 end if (string.starts(t.verb, "clip")) then clips = clips + 1 end if t.verb == "clipPath" then local path = t.path if isPathValid(path) then clipPaths = clipPaths + 1 usedPath = true if t.aa then clipPathsAnti = clipPathsAnti + 1 if path:isConvex() then clipPathsConvexAnti = clipPathsConvexAnti + 1 else usedSWPath = true end end end end if t.verb == "drawPath" then local path = t.path local paint = t.paint if paint and isPathValid(path) then drawPaths = drawPaths + 1 usedPath = true if paint:isAntiAlias() then drawPathsAnti = drawPathsAnti + 1 if path:isConvex() then drawPathsConvexAnti = drawPathsConvexAnti + 1 else usedSWPath = true end end end end end function sk_scrape_summarize() local swDrawPaths = drawPathsAnti - drawPathsConvexAnti local swClipPaths = clipPathsAnti - clipPathsConvexAnti io.write("clips = clips + ", clips, "\n"); io.write("draws = draws + ", draws, "\n"); io.write("clipPaths = clipPaths + ", clipPaths, "\n"); io.write("drawPaths = drawPaths + ", drawPaths, "\n"); io.write("swClipPaths = swClipPaths + ", swClipPaths, "\n"); io.write("swDrawPaths = swDrawPaths + ", swDrawPaths, "\n"); io.write("skpsTotal = skpsTotal + ", skpsTotal, "\n"); io.write("skpsWithPath = skpsWithPath + ", skpsWithPath, "\n"); io.write("skpsWithSWPath = skpsWithSWPath + ", skpsWithSWPath, "\n"); end
bsd-3-clause
prophile/xsera
Resources/Scripts/Modules/Math.lua
2
2615
--[[[ - @function hypot - Finds the distance between two given sides, x and y. - @param x The length of one of the sides. - @param y The length of the other side. - @return val The hypotenuse of the triangle given by sides x and y. --]] function hypot(x, y) return math.sqrt(x * x + y * y) end function normalizeAngle(angle) return angle % (2 * math.pi) end --[[[ - @function hypot1 - Taking a @ref vector, finds the hypotenuse as if those sides were lengths of a right triangle. - @param vec The vector to calculate the hypotenuse from. - @return val The hypotenuse of the triangle given by sides vec.x and vec.y. --]] function hypot1(xAndY) return math.sqrt(xAndY.x * xAndY.x + xAndY.y * xAndY.y) end --[[[ - @function hypot2 - Finds the distance between two vectors. - @param point1 The first vector to calculate the distance from. - @param point2 The second vector to calculate the distance from. - @return val The distance from point1 to point2. --]] function hypot2(point1, point2) return (math.sqrt((point1.y - point2.y)^2 + (point1.x - point2.x)^2)) end --[[[ - @function normalize - Takes the two components and returns the first component "normalized" so that when added to the second "normalized" component, makes a vector of length 1.0. - @param comp1 The component to be normalized. - @param comp2 The component against which comp1 is normalized (the other part of the triangle). - @return val The first component, normalized. --]] function normalize(comp1, comp2) return comp1 / hypot(comp1, comp2) end function findAngle(origin, dest) local angle = normalizeAngle(math.atan2(origin.y - dest.y, origin.x - dest.x)) return angle end function RandomReal(min, max) return (math.random() * (max - min)) + min end function RandomVec(ranges) return vec( RandomReal(ranges.x[1],ranges.x[2]), RandomReal(ranges.y[1],ranges.y[2]) ) end function RotatePoint(point, angle) return vec( point.x*math.cos(angle)-point.y*math.sin(angle), point.x*math.sin(angle)+point.y*math.cos(angle) ) end function PolarVec(mag, angle) return vec(mag*math.cos(angle),mag*math.sin(angle)) end function NormalizeVec(v) return v/hypot1(v) end function xor(p,q) return (p and not q) or (not p and q) end math.sign = function(x) return math.abs(x)/x end function ValuePasses(x, plus, y) return math.sign(x - y) ~= math.sign(x + plus - y) end
mit
LaFamiglia/Illarion-Content
monster/race_112_flesh_dragon/id_1123_deathdragon.lua
1
6370
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- ID 1123, Dragon of Death, Level 8, Armourtype: medium, Weapontype: stabbing local base = require("monster.base.base") local monstermagic = require("monster.base.monstermagic") local fleshDragons = require("monster.race_112_flesh_dragon.base") local M = fleshDragons.generateCallbacks() local orgOnSpawn = M.onSpawn function M.onSpawn(monster) if orgOnSpawn ~= nil then orgOnSpawn(monster) end end local magic = monstermagic() magic.addVioletFlame{probability = 0.10, damageRange = {1500, 3000}, range = 8} magic.addWarping{probability = 0.10} return magic.addCallbacks(M) --[[ INSERT INTO "monster" ("mob_monsterid","mob_name_en","mob_race","mob_hitpoints","mob_movementtype","mob_canattack","mob_canhealself","script","mob_minsize","mob_maxsize","mob_name_de") VALUES (1123,'Dragon of Death',112,10000,'walk',true,false,'monster.race_112_flesh_dragon.id_1123_deathdragon',110,120,'Todesdrache'); INSERT INTO "monster_attributes" ("mobattr_monsterid","mobattr_name","mobattr_min","mobattr_max") VALUES (1123,'willpower',32,41); INSERT INTO "monster_attributes" ("mobattr_monsterid","mobattr_name","mobattr_min","mobattr_max") VALUES (1123,'strength',32,41); INSERT INTO "monster_attributes" ("mobattr_monsterid","mobattr_name","mobattr_min","mobattr_max") VALUES (1123,'perception',32,41); INSERT INTO "monster_attributes" ("mobattr_monsterid","mobattr_name","mobattr_min","mobattr_max") VALUES (1123,'intelligence',32,41); INSERT INTO "monster_attributes" ("mobattr_monsterid","mobattr_name","mobattr_min","mobattr_max") VALUES (1123,'essence',32,41); INSERT INTO "monster_attributes" ("mobattr_monsterid","mobattr_name","mobattr_min","mobattr_max") VALUES (1123,'dexterity',32,41); INSERT INTO "monster_attributes" ("mobattr_monsterid","mobattr_name","mobattr_min","mobattr_max") VALUES (1123,'constitution',32,41); INSERT INTO "monster_attributes" ("mobattr_monsterid","mobattr_name","mobattr_min","mobattr_max") VALUES (1123,'agility',32,41); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,21); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,22); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,23); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,24); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,25); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,26); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,27); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,28); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,29); INSERT INTO "monster_skills" ("mobsk_monsterid","mobsk_minvalue","mobsk_maxvalue","mobsk_skill_id") VALUES (1123,80,90,37); INSERT INTO "monster_items" ("mobit_monsterid","mobit_position","mobit_itemid","mobit_mincount","mobit_maxcount") VALUES ('1123','head','2286','1','1'); INSERT INTO "monster_items" ("mobit_monsterid","mobit_position","mobit_itemid","mobit_mincount","mobit_maxcount") VALUES ('1123','breast','2400','1','1'); INSERT INTO "monster_items" ("mobit_monsterid","mobit_position","mobit_itemid","mobit_mincount","mobit_maxcount") VALUES ('1123','right hand','1051','1','1'); INSERT INTO "monster_drop" ("md_monsterid","md_category","md_probability","md_itemid","md_amount_min","md_amount_max","md_quality_min","md_quality_max","md_durability_min","md_durability_max") VALUES ('1123','1','0.2','447','1','1','7','8','77','88'); INSERT INTO "monster_drop" ("md_monsterid","md_category","md_probability","md_itemid","md_amount_min","md_amount_max","md_quality_min","md_quality_max","md_durability_min","md_durability_max") VALUES ('1123','1','0.1','449','1','1','7','8','77','88'); INSERT INTO "monster_drop" ("md_monsterid","md_category","md_probability","md_itemid","md_amount_min","md_amount_max","md_quality_min","md_quality_max","md_durability_min","md_durability_max") VALUES ('1123','1','0.01','738','1','1','7','8','77','88'); INSERT INTO "monster_drop" ("md_monsterid","md_category","md_probability","md_itemid","md_amount_min","md_amount_max","md_quality_min","md_quality_max","md_durability_min","md_durability_max") VALUES ('1123','1','0.01','505','1','1','6','7','99','99'); INSERT INTO "monster_drop" ("md_monsterid","md_category","md_probability","md_itemid","md_amount_min","md_amount_max","md_quality_min","md_quality_max","md_durability_min","md_durability_max") VALUES ('1123','2','0.5','450','1','1','7','8','77','88'); INSERT INTO "monster_drop" ("md_monsterid","md_category","md_probability","md_itemid","md_amount_min","md_amount_max","md_quality_min","md_quality_max","md_durability_min","md_durability_max") VALUES ('1123','2','0.02','2534','1','1','7','8','77','88'); INSERT INTO "monster_drop" ("md_monsterid","md_category","md_probability","md_itemid","md_amount_min","md_amount_max","md_quality_min","md_quality_max","md_durability_min","md_durability_max") VALUES ('1123','2','0.01','2553','1','1','7','8','77','88'); INSERT INTO "monster_drop" ("md_monsterid","md_category","md_probability","md_itemid","md_amount_min","md_amount_max","md_quality_min","md_quality_max","md_durability_min","md_durability_max") VALUES ('1123','3','1','3077','30','90','7','7','73','73'); ]]
agpl-3.0
ashkanpj/seedfire
plugins/owners.lua
2
12458
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^(owners) (%d+) ([^%s]+) (.*)$", "^(owners) (%d+) ([^%s]+)$", "^(changeabout) (%d+) (.*)$", "^(changerules) (%d+) (.*)$", "^(changename) (%d+) (.*)$", "^(loggroup) (%d+)$" }, run = run }
gpl-2.0
Noltari/luci
applications/luci-app-dump1090/luasrc/model/cbi/dump1090.lua
10
7209
-- Copyright 2014-2015 Álvaro Fernández Rojas <noltari@gmail.com> -- Licensed to the public under the Apache License 2.0. m = Map("dump1090", "dump1090", translate("dump1090 is a Mode S decoder specifically designed for RTLSDR devices, here you can configure the settings.")) s = m:section(TypedSection, "dump1090", "") s.addremove = true s.anonymous = false enable=s:option(Flag, "disabled", translate("Enabled")) enable.enabled="0" enable.disabled="1" enable.default = "1" enable.rmempty = false respawn=s:option(Flag, "respawn", translate("Respawn")) respawn.default = false device_index=s:option(Value, "device_index", translate("RTL device index")) device_index.rmempty = true device_index.datatype = "uinteger" gain=s:option(Value, "gain", translate("Gain (-10 for auto-gain)")) gain.rmempty = true gain.datatype = "integer" enable_agc=s:option(Flag, "enable_agc", translate("Enable automatic gain control")) enable_agc.default = false freq=s:option(Value, "freq", translate("Frequency")) freq.rmempty = true freq.datatype = "uinteger" ifile=s:option(Value, "ifile", translate("Data file")) ifile.rmempty = true ifile.datatype = "file" iformat=s:option(ListValue, "iformat", translate("Sample format for data file")) iformat:value("", translate("Default")) iformat:value("UC8") iformat:value("SC16") iformat:value("SC16Q11") throttle=s:option(Flag, "throttle", translate("When reading from a file play back in realtime, not at max speed")) throttle.default = false raw=s:option(Flag, "raw", translate("Show only messages hex values")) raw.default = false net=s:option(Flag, "net", translate("Enable networking")) modeac=s:option(Flag, "modeac", translate("Enable decoding of SSR Modes 3/A & 3/C")) modeac.default = false net_beast=s:option(Flag, "net_beast", translate("TCP raw output in Beast binary format")) net_beast.default = false net_only=s:option(Flag, "net_only", translate("Enable just networking, no RTL device or file used")) net_only.default = false net_bind_address=s:option(Value, "net_bind_address", translate("IP address to bind to")) net_bind_address.rmempty = true net_bind_address.datatype = "ipaddr" net_http_port=s:option(Value, "net_http_port", translate("HTTP server port")) net_http_port.rmempty = true net_http_port.datatype = "port" net_ri_port=s:option(Value, "net_ri_port", translate("TCP raw input listen port")) net_ri_port.rmempty = true net_ri_port.datatype = "port" net_ro_port=s:option(Value, "net_ro_port", translate("TCP raw output listen port")) net_ro_port.rmempty = true net_ro_port.datatype = "port" net_sbs_port=s:option(Value, "net_sbs_port", translate("TCP BaseStation output listen port")) net_sbs_port.rmempty = true net_sbs_port.datatype = "port" net_bi_port=s:option(Value, "net_bi_port", translate("TCP Beast input listen port")) net_bi_port.rmempty = true net_bi_port.datatype = "port" net_bo_port=s:option(Value, "net_bo_port", translate("TCP Beast output listen port")) net_bo_port.rmempty = true net_bo_port.datatype = "port" net_fatsv_port=s:option(Value, "net_fatsv_port", translate("FlightAware TSV output port")) net_fatsv_port.rmempty = true net_fatsv_port.datatype = "port" net_ro_size=s:option(Value, "net_ro_size", translate("TCP raw output minimum size")) net_ro_size.rmempty = true net_ro_size.datatype = "uinteger" net_ro_interval=s:option(Value, "net_ro_interval", translate("TCP raw output memory flush rate in seconds")) net_ro_interval.rmempty = true net_ro_interval.datatype = "uinteger" net_heartbeat=s:option(Value, "net_heartbeat", translate("TCP heartbeat rate in seconds")) net_heartbeat.rmempty = true net_heartbeat.datatype = "uinteger" net_buffer=s:option(Value, "net_buffer", translate("TCP buffer size 64Kb * (2^n)")) net_buffer.rmempty = true net_buffer.datatype = "uinteger" net_verbatim=s:option(Flag, "net_verbatim", translate("Do not apply CRC corrections to messages we forward")) net_verbatim.default = false forward_mlat=s:option(Flag, "forward_mlat", translate("Allow forwarding of received mlat results to output ports")) forward_mlat.default = false lat=s:option(Value, "lat", translate("Reference/receiver latitude for surface posn")) lat.rmempty = true lat.datatype = "float" lon=s:option(Value, "lon", translate("Reference/receiver longitude for surface posn")) lon.rmempty = true lon.datatype = "float" max_range=s:option(Value, "max_range", translate("Absolute maximum range for position decoding")) max_range.rmempty = true max_range.datatype = "uinteger" fix=s:option(Flag, "fix", translate("Enable single-bits error correction using CRC")) fix.default = false no_fix=s:option(Flag, "no_fix", translate("Disable single-bits error correction using CRC")) no_fix.default = false no_crc_check=s:option(Flag, "no_crc_check", translate("Disable messages with broken CRC")) no_crc_check.default = false phase_enhance=s:option(Flag, "phase_enhance", translate("Enable phase enhancement")) phase_enhance.default = false aggressive=s:option(Flag, "aggressive", translate("More CPU for more messages")) aggressive.default = false mlat=s:option(Flag, "mlat", translate("Display raw messages in Beast ascii mode")) mlat.default = false stats=s:option(Flag, "stats", translate("Print stats at exit")) stats.default = false stats_range=s:option(Flag, "stats_range", translate("Collect/show range histogram")) stats_range.default = false stats_every=s:option(Value, "stats_every", translate("Show and reset stats every seconds")) stats_every.rmempty = true stats_every.datatype = "uinteger" onlyaddr=s:option(Flag, "onlyaddr", translate("Show only ICAO addresses")) onlyaddr.default = false metric=s:option(Flag, "metric", translate("Use metric units")) metric.default = false snip=s:option(Value, "snip", translate("Strip IQ file removing samples")) snip.rmempty = true snip.datatype = "uinteger" debug_mode=s:option(Value, "debug", translate("Debug mode flags")) debug_mode.rmempty = true ppm=s:option(Value, "ppm", translate("Set receiver error in parts per million")) ppm.rmempty = true ppm.datatype = "uinteger" html_dir=s:option(Value, "html_dir", translate("Base directory for the internal HTTP server")) html_dir.rmempty = true html_dir.datatype = "directory" write_json=s:option(Value, "write_json", translate("Periodically write json output to a directory")) write_json.rmempty = true write_json.datatype = "directory" write_json_every=s:option(Flag, "write_json_every", translate("Write json output every t seconds")) write_json_every.rmempty = true write_json_every.datatype = "uinteger" json_location_accuracy=s:option(ListValue, "json_location_accuracy", translate("Accuracy of receiver location in json metadata")) json_location_accuracy:value("", translate("Default")) json_location_accuracy:value("0", "No location") json_location_accuracy:value("1", "Approximate") json_location_accuracy:value("2", "Exact") oversample=s:option(Flag, "oversample", translate("Use the 2.4MHz demodulator")) oversample.default = false dcfilter=s:option(Flag, "dcfilter", translate("Apply a 1Hz DC filter to input data")) dcfilter.default = false measure_noise=s:option(Flag, "measure_noise", translate("Measure noise power")) measure_noise.default = false return m
apache-2.0
RandalThompson/Playground
control.lua
1
1243
require "util" require "defines" -- Defines how I want the player to start the game. -- For now the player has it pretty good. It is a playground after all. function build_player(player_index) local player = game.players[player_index] -- Vehicles: player.insert{name="fast-tank", count=1} -- Fuel player.insert{name="solid-fuel", count = 100} -- Weapons player.insert{name="laser-pistol", count = 1} player.insert{name="large-mine", count=10} player.insert{name="steel-sword", count=1} -- Ammo player.insert{name="shotgun-shell", count=100} player.insert{name="laser-cell", count = 100} -- Armor player.insert{name="power-armor-mk2", count=1} end -- end build_player -- Now you're player stinks! function player_pollute(player_index) for player_index in pairs(game.players) do local player = game.players[player_index] local surface = player.surface local position = player.position surface.pollute(position, 10) end end -- end player_pollute script.on_event(defines.events.on_player_created, function(event) build_player(event.player_index) game.disable_tips_and_tricks() end) script.on_event(defines.events.on_tick, function(event) player_pollute(event.player_index) end)
mit
Nexela/autofill
stdlib/utils/wip/joules.lua
1
1490
--- For working with energy strings -- @classmod Joules local Joules = {} setmetatable(Joules, require('stdlib/core')) local Is = require('stdlib/utils/is') local high_to_low = {'Y', 'Z', 'E', 'P', 'T', 'G', 'M', 'k', 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y'} local units = { y = 1E-24, z = 1E-21, a = 1E-18, f = 1E-15, p = 1E-12, n = 1E-9, u = 1E-6, m = 1E-3, k = 1E3, M = 1E6, G = 1E9, T = 1E12, P = 1E15, E = 1E18, Z = 1E21, Y = 1E24 } function Joules._caller(_, j) return Joules.new(j) end local function breakdown(j) local n, m = string.match(j, '([0-9.-]+)%s*([yzafpnumkMGTPEZY]?)%s*[jJ]') if not n or not m or not (m and units[m]) then return end n = tonumber(n) return Is.Assert.Number(n), Is.Assert.String(m) end function Joules.new(j) breakdown(j) return debug.setmetatable(j, Joules._mt) end function Joules.from(j) local n, m = breakdown(j) return n * units[m] end function Joules.to(j, unit) if not unit then return j end if not units[unit] then error('Invalid energy unit', 2) end local n = breakdown(j) return Joules.new(n / units[unit] .. unit .. 'J') end function Joules.nearest(j) for _, v in ipairs(high_to_low) do if j >= units[v] then return Joules.to(j, v) end end return j .. 'J' end Joules._mt = { __call = Joules._caller, __index = Joules } return Joules
mit
LaFamiglia/Illarion-Content
monster/race_3_elf/id_33_priest.lua
1
1177
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 33, Elven Priest, Level: 5, Armourtype: cloth, Weapontype: concussion local monstermagic = require("monster.base.monstermagic") local elves = require("monster.race_3_elf.base") local magic = monstermagic() magic.addSummon{probability = 0.0249, monsters = {252, 582, 622}} -- some animals magic.addSummon{probability = 0.0050, monsters = {253, 583}} -- stronger animals magic.addSummon{probability = 0.0001, monsters = {584}} -- even strong animal local M = elves.generateCallbacks() return magic.addCallbacks(M)
agpl-3.0
punisherbot/sh
plugins/Member_Moderator.lua
20
10430
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.' end local function set_description(msg, data) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = deskripsi save_data(_config.moderation.data, data) return '..deskripsi' end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = '..about return 'About '..about end local function set_rules(msg, data) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = rules save_data(_config.moderation.data, data) return ''..rules end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = '..rules return rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ') save_data(_config.moderation.data, data) return 'Group name has been locked' end end local function unlock_group_name(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end -- show group settings local function show_group_settings(msg, data) if not is_momod(msg) then return "For moderators only!" end local settings = data[tostring(msg.to.id)]['settings'] local text = "Your Gp settings:\nLock gp name : "..settings.lock_name.."\nLock gp photo : "..settings.lock_photo.."\nLock gp member : "..settings.lock_member return text end function run(msg, matches) --vardump(msg) if matches[1] == 'cgp' and matches[2] then group_name = matches[2] return create_group(msg) end if not is_chat_msg(msg) then return "This is not a group chat." end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if msg.media and is_chat_msg(msg) and is_momod(msg) then if msg.media.type == 'photo' and data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then load_photo(msg.id, set_group_photo, msg) end end end if data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'stabout' and matches[2] then deskripsi = matches[2] return set_description(msg, data) end if matches[1] == 'about' then return get_description(msg, data) end if matches[1] == 'strules' then rules = matches[2] return set_rules(msg, data) end if matches[1] == 'rules' then return get_rules(msg, data) end if matches[1] == 'gp' and matches[2] == '+' then --group lock * if matches[3] == 'n' then return lock_group_name(msg, data) end if matches[3] == 'm' then return lock_group_member(msg, data) end if matches[3] == 'p' then return lock_group_photo(msg, data) end end if matches[1] == 'gp' and matches[2] == '-' then --group unlock * if matches[3] == 'n' then return unlock_group_name(msg, data) end if matches[3] == 'm' then return unlock_group_member(msg, data) end if matches[3] == 'p' then return unlock_group_photo(msg, data) end end if matches[1] == 'gp' and matches[2] == 'settings' then return show_group_settings(msg, data) end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'stn' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'stp' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end end end return { description = "Plugin to manage group chat.", }, patterns = { "^(cgp) (.*)$", "^(stabout) (.*)$", "^(about)$", "^(strules) (.*)$", "^(rules)$", "^(stn) (.*)$", "^(stp)$", "^(gp) (+) (.*)$", "^(gp) (-) (.*)$", "^(gp) (settings)$", "^!!tgservice (.+)$", "%[(photo)%]", }, run = run, } end
gpl-2.0
camchenry/shaderview
src/notification.lua
1
3317
local notification = {} local function get_color_opacity(color, opacity) local r, g, b, a = unpack(color) return r, g, b, a * opacity end notification.Notification = Class{ init = function(self, props) self.text = "" self.duration = 2 self.x = 5 self.y = 5 self.dead = false self.foreground = {1, 1, 1, 1} self.background = {0, 0, 0, .63} self.shadow = {0, 0, 0, 1} self.opacity = 0 self.shadow_size = 1 self.width = nil self.height = nil self.padding = 5 self.font = Fonts.default[16] self.align = "left" self.fade_time_in = 0.15 self.fade_time_out = 0.15 props = props or {} for k, v in pairs(props) do self[k] = v end if not self.width then self.width = self.font:getWidth(self.text) end if not self.height then self.height = self.font:getHeight() end self.life = self.duration self.timer = Timer.new() self.timer:script(function(wait) self.timer:tween(self.fade_time_in, self, {opacity = 1}) wait(self.life - self.fade_time_out) self.timer:tween(self.fade_time_in, self, {opacity = 0}) end) end, update = function(self, dt) self.life = self.life - dt self.timer:update(dt) if self.life < 0 then self.dead = true end end, draw = function(self) if not self.dead then love.graphics.setColor(get_color_opacity(self.background, self.opacity)) love.graphics.rectangle('fill', self.x, self.y, self.width+self.padding*2, self.height+self.padding*2) love.graphics.setFont(self.font) local w = self.font:getWidth(self.text) + self.padding*2 local h = self.font:getHeight() + self.padding*2 local x = self.x + self.padding local y = self.y + self.padding love.graphics.setColor(get_color_opacity(self.shadow, self.opacity)) love.graphics.printf(self.text, x + self.shadow_size, y + self.shadow_size, self.width, self.align) love.graphics.setColor(get_color_opacity(self.foreground, self.opacity)) love.graphics.printf(self.text, x, y, self.width, self.align) end end, } notification.Queue = Class{ init = function(self, props) props = props or {} for k, v in pairs(props) do self[k] = v end self.notifications = {} end, add = function(self, notification) table.insert(self.notifications, notification) if not self.current_notification then self.current_notification = notification end end, update = function(self, dt) if self.current_notification and self.current_notification.dead then table.remove(self.notifications, 1) self.current_notification = self.notifications[1] end if self.current_notification then self.current_notification:update(dt) end end, draw = function(self) if self.current_notification then self.current_notification:draw() end end, } return notification
mit
amireh/vertigo-bom
scripts/Shared/UI/UIDialogs.lua
1
5026
-- UI Dialogs -- -- UIDialog provides necessary and convenience functions for attaching -- and detaching CEGUI dialogs UIDialog = {} local __UID = 0 local __Path = "overlays/dialog.layout" local Win2Dialogs = {} -- maps CEGUI::Windows to UIDialog objects, see events below function UIDialog:new(in_text, keep_alive, keep_hidden) if not in_text then return error("can not create an empty dialog!") end local o = { Window = nil, Label = nil, KeepAlive = keep_alive or false, Buttons = { Ok = nil, Cancel = nil }, Callbacks = { Ok = {}, Cancel = {} } } setmetatable(o, {__index = self}) self.__index = self o:__load() o.Label:setText(in_text) Hax.Log("UIDialog: '" .. o.Window:getName() .. "' created") if not keep_hidden then o:show() end return o end -- load the layout and rename it to prevent name clashes, -- UIDialogs are always loaded on construction function UIDialog:__load() local prefix = "UIDialog_Auto_" .. __UID self.Window = CEWindowMgr:loadWindowLayout(__Path, prefix) self.Label = self.Window:getChild(prefix .. "Dialog_Label") self.Buttons.Ok = self.Window:getChild(prefix .. "Dialog_OkButton") self.Buttons.Cancel = self.Window:getChild(prefix .. "Dialog_CancelButton") Win2Dialogs[self.Window:getName()] = self self.Buttons.Ok:subscribeEvent("Clicked", UIDialog.onDialogOk) self.Buttons.Cancel:subscribeEvent("Clicked", UIDialog.onDialogCancel) -- @note -- the name of the window is not used anywhere nor is significant for us, -- but it has to be unique for CEGUI to load it multiple times! --~ self.Window:setName("UIDialog" .. __UID) __UID = __UID + 1 end function UIDialog:show() -- attach layout local parent = Hax.UI.CurrentSheet.Window local layout = self.Window if not parent then return error("attempting to load a dialog when no UISheet is attached!") end parent:addChildWindow(layout) layout:setAlwaysOnTop(true) layout:show() self:__resize() Hax.Log("UIDialog: '" .. self.Window:getName() .. "' is now visible") return self end function UIDialog:isVisible() return self.Window and self.Window:isVisible() and self.Window:getParent() end function UIDialog:hide() local layout = self.Window Hax.Log("UIDialog: '" .. self.Window:getName() .. "' is being hidden") layout:setAlwaysOnTop(false) layout:hide() layout:getParent():removeChildWindow(layout) return self end function UIDialog:__resize() local lbl_height = tonumber(self.Label:getProperty("VertExtent")) local btn_height = tonumber(self.Buttons.Ok:getHeight().offset)-- * AR.Height self.Window:setHeight(CEGUI.UDim(0, lbl_height + btn_height + 20)) self.Window:setWidth(CEGUI.UDim(0, self.Label:getProperty("HorzExtent") )) end -- detaches the sheet, destroys its windows, and removes it from the UIDialog master table function UIDialog:destroy() if self:isVisible() then self:hide() end Hax.Log("UIDialog: '" .. self.Window:getName() .. "' destroyed") Win2Dialogs[self.Window:getName()] = nil CEWindowMgr:destroyWindow(self.Window) self.Window = nil self.Callbacks = {} self = nil return nil end function UIDialog:bind(action, handler) table.insert(self.Callbacks[action], handler) end function UIDialog:unbind(action, handler) assert(self.Callbacks[action]) remove_by_value(self.Callbacks[action], handler) end -- this is called when the Dialog is attached to this sheet -- and its Ok button is pressed, and a callback is registered UIDialog.onDialogOk = function(e) local win = CEGUI.toWindowEventArgs(e).window local dlg = Win2Dialogs[win:getParent():getName()] assert(dlg) for callback in list_iter(dlg.Callbacks.Ok) do callback(dlg) end if not dlg.KeepAlive then dlg:destroy() end return true end UIDialog.onDialogCancel = function(e) local win = CEGUI.toWindowEventArgs(e).window local dlg = Win2Dialogs[win:getParent():getName()] assert(dlg) for callback in list_iter(dlg.Callbacks.Cancel) do callback(dlg) end if not dlg.KeepAlive then dlg:destroy() end return true end -- aliases for the action handlers UIDialog.onDialogYes = UIDialog.onDialogOk UIDialog.onDialogNo = UIDialog.onDialogCancel YesNoDialog = {} function YesNoDialog:new(in_text, keep_hidden) local o = UIDialog:new(in_text, keep_hidden) o.Buttons.Ok:show() o.Buttons.Ok:setText("Yes") o.Buttons.Cancel:show() o.Buttons.Cancel:setText("No") -- position the Yes button next to the No one o.Buttons.Ok:setXPosition(CEGUI.UDim(0.695, 0)) o.Buttons.Ok:setWidth(CEGUI.UDim(0.2, 0)) o.Buttons.Cancel:setXPosition(CEGUI.UDim(0.9, 0)) o.Buttons.Cancel:setWidth(CEGUI.UDim(0.1, 0)) return o end OkDialog = {} function OkDialog:new(in_text, keep_hidden) local o = UIDialog:new(in_text, keep_hidden) o.Buttons.Ok:show() o.Buttons.Ok:setText("Ok") o.Buttons.Cancel:hide() -- position the one button in the middle o.Buttons.Ok:setProperty("HorizontalAlignment", "Centre") return o end
gpl-3.0
SirSepehr/Sepehr
plugins/gnuplot.lua
622
1813
--[[ * Gnuplot plugin by psykomantis * dependencies: * - gnuplot 5.00 * - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html * ]] -- Gnuplot needs absolute path for the plot, so i run some commands to find where we are local outputFile = io.popen("pwd","r") io.input(outputFile) local _pwd = io.read("*line") io.close(outputFile) local _absolutePlotPath = _pwd .. "/data/plot.png" local _scriptPath = "./data/gnuplotScript.gpl" do local function gnuplot(msg, fun) local receiver = get_receiver(msg) -- We generate the plot commands local formattedString = [[ set grid set terminal png set output "]] .. _absolutePlotPath .. [[" plot ]] .. fun local file = io.open(_scriptPath,"w"); file:write(formattedString) file:close() os.execute("gnuplot " .. _scriptPath) os.remove (_scriptPath) return _send_photo(receiver, _absolutePlotPath) end -- Check all dependencies before executing local function checkDependencies() local status = os.execute("gnuplot -h") if(status==true) then status = os.execute("gnuplot -e 'set terminal png'") if(status == true) then return 0 -- OK ready to go! else return 1 -- missing libgd2-xpm-dev end else return 2 -- missing gnuplot end end local function run(msg, matches) local status = checkDependencies() if(status == 0) then return gnuplot(msg,matches[1]) elseif(status == 1) then return "It seems that this bot miss a dependency :/" else return "It seems that this bot doesn't have gnuplot :/" end end return { description = "use gnuplot through telegram, only plot single variable function", usage = "!gnuplot [single variable function]", patterns = {"^!gnuplot (.+)$"}, run = run } end
gpl-2.0
fmassa/object-detection.torch
utils.lua
1
8010
-------------------------------------------------------------------------------- -- utility functions for the evaluation part -------------------------------------------------------------------------------- local function joinTable(input,dim) local size = torch.LongStorage() local is_ok = false for i=1,#input do local currentOutput = input[i] if currentOutput:numel() > 0 then if not is_ok then size:resize(currentOutput:dim()):copy(currentOutput:size()) is_ok = true else size[dim] = size[dim] + currentOutput:size(dim) end end end local output = input[1].new():resize(size) local offset = 1 for i=1,#input do local currentOutput = input[i] if currentOutput:numel() > 0 then output:narrow(dim, offset, currentOutput:size(dim)):copy(currentOutput) offset = offset + currentOutput:size(dim) end end return output end -------------------------------------------------------------------------------- local function keep_top_k(boxes,top_k) local X = joinTable(boxes,1) if X:numel() == 0 then return end local scores = X[{{},-1}]:sort(1,true) local thresh = scores[math.min(scores:numel(),top_k)] for i=1,#boxes do local bbox = boxes[i] if bbox:numel() > 0 then local idx = torch.range(1,bbox:size(1)):long() local keep = bbox[{{},-1}]:ge(thresh) idx = idx[keep] if idx:numel() > 0 then boxes[i] = bbox:index(1,idx) else boxes[i]:resize() end end end return boxes, thresh end -------------------------------------------------------------------------------- -- evaluation -------------------------------------------------------------------------------- local function VOCap(rec,prec) local mrec = rec:totable() local mpre = prec:totable() table.insert(mrec,1,0); table.insert(mrec,1) table.insert(mpre,1,0); table.insert(mpre,0) for i=#mpre-1,1,-1 do mpre[i]=math.max(mpre[i],mpre[i+1]) end local ap = 0 for i=1,#mpre-1 do if mrec[i] ~= mrec[i+1] then ap = ap + (mrec[i+1]-mrec[i])*mpre[i+1] end end return ap end local function VOC2007ap(rec,prec) local ap = 0 for t=0,1,0.1 do local c = prec[rec:ge(t)] local p if c:numel() > 0 then p = torch.max(c) else p = 0 end ap=ap+p/11 end return ap end -------------------------------------------------------------------------------- local function boxoverlap(a,b) --local b = anno.objects[j] local b = b.xmin and {b.xmin,b.ymin,b.xmax,b.ymax} or b local x1 = a:select(2,1):clone() x1[x1:lt(b[1])] = b[1] local y1 = a:select(2,2):clone() y1[y1:lt(b[2])] = b[2] local x2 = a:select(2,3):clone() x2[x2:gt(b[3])] = b[3] local y2 = a:select(2,4):clone() y2[y2:gt(b[4])] = b[4] local w = x2-x1+1; local h = y2-y1+1; local inter = torch.cmul(w,h):float() local aarea = torch.cmul((a:select(2,3)-a:select(2,1)+1) , (a:select(2,4)-a:select(2,2)+1)):float() local barea = (b[3]-b[1]+1) * (b[4]-b[2]+1); -- intersection over union overlap local o = torch.cdiv(inter , (aarea+barea-inter)) -- set invalid entries to 0 overlap o[w:lt(0)] = 0 o[h:lt(0)] = 0 return o end -------------------------------------------------------------------------------- local function VOCevaldet(dataset,scored_boxes,cls) local num_pr = 0 local energy = {} local correct = {} local count = 0 for i=1,dataset:size() do local ann = dataset:getAnnotation(i) local bbox = {} local det = {} for idx,obj in ipairs(ann.object) do if obj.name == cls and obj.difficult == '0' then table.insert(bbox,{obj.bndbox.xmin,obj.bndbox.ymin, obj.bndbox.xmax,obj.bndbox.ymax}) table.insert(det,0) count = count + 1 end end bbox = torch.Tensor(bbox) det = torch.Tensor(det) local num = scored_boxes[i]:numel()>0 and scored_boxes[i]:size(1) or 0 for j=1,num do local bbox_pred = scored_boxes[i][j] num_pr = num_pr + 1 table.insert(energy,bbox_pred[5]) if bbox:numel()>0 then local o = boxoverlap(bbox,bbox_pred[{{1,4}}]) local maxo,index = o:max(1) maxo = maxo[1] index = index[1] if maxo >=0.5 and det[index] == 0 then correct[num_pr] = 1 det[index] = 1 else correct[num_pr] = 0 end else correct[num_pr] = 0 end end end if #energy == 0 then return 0,torch.Tensor(),torch.Tensor() end energy = torch.Tensor(energy) correct = torch.Tensor(correct) local threshold,index = energy:sort(true) correct = correct:index(1,index) local n = threshold:numel() local recall = torch.zeros(n) local precision = torch.zeros(n) local num_correct = 0 for i = 1,n do --compute precision num_positive = i num_correct = num_correct + correct[i] if num_positive ~= 0 then precision[i] = num_correct / num_positive; else precision[i] = 0; end --compute recall recall[i] = num_correct / count end ap = VOCap(recall, precision) io.write(('AP = %.4f\n'):format(ap)); return ap, recall, precision end -------------------------------------------------------------------------------- -- data preparation -------------------------------------------------------------------------------- -- Caffe models are in BGR format, and they suppose the images range from 0-255. -- This function modifies the model read by loadcaffe to use it in torch format -- location is the postion of the first conv layer in the module. If you have -- nested models (like sequential inside sequential), location should be a -- table with as many elements as the depth of the network. local function convertCaffeModelToTorch(model,location) local location = location or {1} local m = model for i=1,#location do m = m:get(location[i]) end local weight = m.weight local weight_clone = weight:clone() local nchannels = weight:size(2) for i=1,nchannels do weight:select(2,i):copy(weight_clone:select(2,nchannels+1-i)) end weight:mul(255) end -------------------------------------------------------------------------------- -- nn -------------------------------------------------------------------------------- local function reshapeLastLinearLayer(model,nOutput) local layers = model:findModules('nn.Linear') local layer = layers[#layers] local nInput = layer.weight:size(2) layer.gradBias:resize(nOutput):zero() layer.gradWeight:resize(nOutput,nInput):zero() layer.bias:resize(nOutput) layer.weight:resize(nOutput,nInput) layer:reset() end -- borrowed from https://github.com/soumith/imagenet-multiGPU.torch/blob/master/train.lua -- clear the intermediate states in the model before saving to disk -- this saves lots of disk space local function sanitize(net) local list = net:listModules() for _,val in ipairs(list) do for name,field in pairs(val) do if torch.type(field) == 'cdata' then val[name] = nil end if name == 'homeGradBuffers' then val[name] = nil end if name == 'input_gpu' then val['input_gpu'] = {} end if name == 'gradOutput_gpu' then val['gradOutput_gpu'] = {} end if name == 'gradInput_gpu' then val['gradInput_gpu'] = {} end if (name == 'output' or name == 'gradInput') then val[name] = field.new() end end end end -------------------------------------------------------------------------------- -- packaging -------------------------------------------------------------------------------- local utils = {} utils.keep_top_k = keep_top_k utils.VOCevaldet = VOCevaldet utils.VOCap = VOCap utils.convertCaffeModelToTorch = convertCaffeModelToTorch utils.reshapeLastLinearLayer = reshapeLastLinearLayer utils.sanitize = sanitize return utils
bsd-2-clause
Godfather021/yag
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
LionKingTeam/Lion.king.bot
libs/redis.lua
32
1129
local Redis = (loadfile "./libs/lua-redis.lua")() local FakeRedis = (loadfile "./libs/fakeredis.lua")() local params = { host = '127.0.0.1', port = 6379, } -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) end return redis -- کد های پایین در ربات نشان داده نمیشوند -- http://permag.ir -- @permag_ir -- @permag_bots -- @permag
gpl-3.0
keyanmca/MonaClients
chat/main.lua
3
2101
-- Test client for push writers = {} -- Function for parsing data coming from a client -- Prevent formatting problems function parseMessage(bytes) if type(bytes) == "string" then return bytes else -- TODO I don't remind me why a table can be a well formed message if type(bytes) == "table" and type(bytes[1]) == "string" then -- prevent date parsing return bytes[1] else WARN("Error in message formatting : ", mona:toJSON(bytes)) return bytes[1] end end end function onConnection(client,...) INFO("Connection of a new client to the chatroom") writers[client] = nil -- Identification function function client:onIdentification(bytes) local name = parseMessage(bytes) if name then INFO("Trying to connect user : ", name) -- Send all current users for user,peerName in pairs(writers) do client.writer:writeInvocation("onEvent", "connection", peerName) end writers[client] = name writeMsgToChat("", "User "..name.." has joined the chatroom!") sendEventToUsers("connection", name) end end -- Reception of a message from a client function client:onMessage(bytes) nameClient = writers[client] local message = parseMessage(bytes) if not nameClient then WARN("Unauthentied user has tried to send a message : ", mona:toJSON(message)) else if message then INFO("New message from user "..nameClient.." : ") INFO(mona:toJSON(message)) writeMsgToChat(nameClient..">", message) end end end end -- send an event to each client function sendEventToUsers(event, userName) for user,name in pairs(writers) do user.writer:writeInvocation("onEvent", event, userName) end end -- send the message to each clients function writeMsgToChat(prompt, message) for user,name in pairs(writers) do user.writer:writeInvocation("onReception", prompt, message) end end function onDisconnection(client) local name = writers[client] if name then writers[client] = nil writeMsgToChat("", "User "..name.." has quit the chatroom!") sendEventToUsers("disconnection", name) end end
lgpl-3.0
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/bsd/ffi.lua
18
10586
-- define general BSD system calls for ffi -- note that some functions may not be available in all, but so long as prototype is standard they can go here local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local cdef = require "ffi".cdef -- standard Posix cdef[[ int open(const char *pathname, int flags, mode_t mode); int close(int fd); int chdir(const char *path); int fchdir(int fd); int mkdir(const char *pathname, mode_t mode); int rmdir(const char *pathname); int unlink(const char *pathname); int rename(const char *oldpath, const char *newpath); int chmod(const char *path, mode_t mode); int fchmod(int fd, mode_t mode); int chown(const char *path, uid_t owner, gid_t group); int fchown(int fd, uid_t owner, gid_t group); int lchown(const char *path, uid_t owner, gid_t group); int link(const char *oldpath, const char *newpath); int linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags); int symlink(const char *oldpath, const char *newpath); int chroot(const char *path); mode_t umask(mode_t mask); void sync(void); int mknod(const char *pathname, mode_t mode, dev_t dev); int mkfifo(const char *path, mode_t mode); ssize_t read(int fd, void *buf, size_t count); ssize_t readv(int fd, const struct iovec *iov, int iovcnt); ssize_t write(int fd, const void *buf, size_t count); ssize_t writev(int fd, const struct iovec *iov, int iovcnt); ssize_t pread(int fd, void *buf, size_t count, off_t offset); ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset); ssize_t preadv(int fd, const struct iovec *iov, int iovcnt, off_t offset); ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset); int access(const char *pathname, int mode); off_t lseek(int fd, off_t offset, int whence); ssize_t readlink(const char *path, char *buf, size_t bufsiz); int fsync(int fd); int fdatasync(int fd); int fcntl(int fd, int cmd, void *arg); /* arg is long or pointer */ int stat(const char *path, struct stat *sb); int lstat(const char *path, struct stat *sb); int fstat(int fd, struct stat *sb); int truncate(const char *path, off_t length); int ftruncate(int fd, off_t length); int shm_open(const char *pathname, int flags, mode_t mode); int shm_unlink(const char *name); int flock(int fd, int operation); int socket(int domain, int type, int protocol); int socketpair(int domain, int type, int protocol, int sv[2]); int pipe2(int pipefd[2], int flags); int dup(int oldfd); int dup2(int oldfd, int newfd); int dup3(int oldfd, int newfd, int flags); ssize_t recv(int sockfd, void *buf, size_t len, int flags); ssize_t send(int sockfd, const void *buf, size_t len, int flags); ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen); ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen); ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags); ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags); int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen); int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen); int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); int listen(int sockfd, int backlog); int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); int accept4(int sockfd, void *addr, socklen_t *addrlen, int flags); int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen); int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen); int shutdown(int sockfd, int how); int pipe(int pipefd[2]); int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); int poll(struct pollfd *fds, nfds_t nfds, int timeout); int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout, const sigset_t *sigmask); int nanosleep(const struct timespec *req, struct timespec *rem); int getrusage(int who, struct rusage *usage); int getpriority(int which, int who); int setpriority(int which, int who, int prio); int sendmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int flags); int recvmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int flags, struct timespec *timeout); uid_t getuid(void); uid_t geteuid(void); pid_t getpid(void); pid_t getppid(void); gid_t getgid(void); gid_t getegid(void); int setuid(uid_t uid); int setgid(gid_t gid); int seteuid(uid_t euid); int setegid(gid_t egid); pid_t getsid(pid_t pid); pid_t setsid(void); int setpgid(pid_t pid, pid_t pgid); pid_t getpgid(pid_t pid); pid_t getpgrp(void); pid_t fork(void); int execve(const char *filename, const char *argv[], const char *envp[]); void exit(int status); void _exit(int status); int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); int sigpending(sigset_t *set); int sigsuspend(const sigset_t *mask); int kill(pid_t pid, int sig); int getgroups(int size, gid_t list[]); int setgroups(size_t size, const gid_t *list); int gettimeofday(struct timeval *tv, void *tz); int settimeofday(const struct timeval *tv, const void *tz); int getitimer(int which, struct itimerval *curr_value); int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value); int acct(const char *filename); void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *addr, size_t length); int msync(void *addr, size_t length, int flags); int madvise(void *addr, size_t length, int advice); int mlock(const void *addr, size_t len); int munlock(const void *addr, size_t len); int mlockall(int flags); int munlockall(void); int openat(int dirfd, const char *pathname, int flags, mode_t mode); int mkdirat(int dirfd, const char *pathname, mode_t mode); int unlinkat(int dirfd, const char *pathname, int flags); int renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath); int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags); int symlinkat(const char *oldpath, int newdirfd, const char *newpath); int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev); int mkfifoat(int dirfd, const char *pathname, mode_t mode); int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags); int readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz); int faccessat(int dirfd, const char *pathname, int mode, int flags); int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags); int futimens(int fd, const struct timespec times[2]); int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags); int lchmod(const char *path, mode_t mode); int fchroot(int fd); int utimes(const char *filename, const struct timeval times[2]); int futimes(int, const struct timeval times[2]); int lutimes(const char *filename, const struct timeval times[2]); pid_t wait4(pid_t wpid, int *status, int options, struct rusage *rusage); int posix_openpt(int oflag); int clock_getres(clockid_t clk_id, struct timespec *res); int clock_gettime(clockid_t clk_id, struct timespec *tp); int clock_settime(clockid_t clk_id, const struct timespec *tp); int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *request, struct timespec *remain); int getpagesize(void); int timer_create(clockid_t clockid, struct sigevent *sevp, timer_t *timerid); int timer_settime(timer_t timerid, int flags, const struct itimerspec *new_value, struct itimerspec * old_value); int timer_gettime(timer_t timerid, struct itimerspec *curr_value); int timer_delete(timer_t timerid); int timer_getoverrun(timer_t timerid); int adjtime(const struct timeval *delta, struct timeval *olddelta); int aio_cancel(int, struct aiocb *); int aio_error(const struct aiocb *); int aio_fsync(int, struct aiocb *); int aio_read(struct aiocb *); int aio_return(struct aiocb *); int aio_write(struct aiocb *); int lio_listio(int, struct aiocb *const *, int, struct sigevent *); int aio_suspend(const struct aiocb *const *, int, const struct timespec *); int aio_waitcomplete(struct aiocb **, struct timespec *); ]] -- BSD specific cdef[[ int getdirentries(int fd, char *buf, int nbytes, long *basep); int unmount(const char *dir, int flags); int revoke(const char *path); int chflags(const char *path, unsigned long flags); int lchflags(const char *path, unsigned long flags); int fchflags(int fd, unsigned long flags); int chflagsat(int fd, const char *path, unsigned long flags, int atflag); long pathconf(const char *path, int name); long lpathconf(const char *path, int name); long fpathconf(int fd, int name); int kqueue(void); int kqueue1(int flags); int kevent(int kq, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); int issetugid(void); int ktrace(const char *tracefile, int ops, int trpoints, pid_t pid); int extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); int extattr_delete_fd(int fd, int attrnamespace, const char *attrname); int extattr_delete_file(const char *path, int attrnamespace, const char *attrname); int extattr_delete_link(const char *path, int attrnamespace, const char *attrname); ssize_t extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); ssize_t extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); ssize_t extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); ssize_t extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); ssize_t extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); ssize_t extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); ssize_t extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); ssize_t extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); ssize_t extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); ]]
apache-2.0
luiseduardohdbackup/WarriorQuest
WarriorQuest/runtime/ios/PrebuiltRuntimeLua.app/headers.lua
133
3698
----------------------------------------------------------------------------- -- Canonic header field capitalization -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- local socket = require("socket") socket.headers = {} local _M = socket.headers _M.canonic = { ["accept"] = "Accept", ["accept-charset"] = "Accept-Charset", ["accept-encoding"] = "Accept-Encoding", ["accept-language"] = "Accept-Language", ["accept-ranges"] = "Accept-Ranges", ["action"] = "Action", ["alternate-recipient"] = "Alternate-Recipient", ["age"] = "Age", ["allow"] = "Allow", ["arrival-date"] = "Arrival-Date", ["authorization"] = "Authorization", ["bcc"] = "Bcc", ["cache-control"] = "Cache-Control", ["cc"] = "Cc", ["comments"] = "Comments", ["connection"] = "Connection", ["content-description"] = "Content-Description", ["content-disposition"] = "Content-Disposition", ["content-encoding"] = "Content-Encoding", ["content-id"] = "Content-ID", ["content-language"] = "Content-Language", ["content-length"] = "Content-Length", ["content-location"] = "Content-Location", ["content-md5"] = "Content-MD5", ["content-range"] = "Content-Range", ["content-transfer-encoding"] = "Content-Transfer-Encoding", ["content-type"] = "Content-Type", ["cookie"] = "Cookie", ["date"] = "Date", ["diagnostic-code"] = "Diagnostic-Code", ["dsn-gateway"] = "DSN-Gateway", ["etag"] = "ETag", ["expect"] = "Expect", ["expires"] = "Expires", ["final-log-id"] = "Final-Log-ID", ["final-recipient"] = "Final-Recipient", ["from"] = "From", ["host"] = "Host", ["if-match"] = "If-Match", ["if-modified-since"] = "If-Modified-Since", ["if-none-match"] = "If-None-Match", ["if-range"] = "If-Range", ["if-unmodified-since"] = "If-Unmodified-Since", ["in-reply-to"] = "In-Reply-To", ["keywords"] = "Keywords", ["last-attempt-date"] = "Last-Attempt-Date", ["last-modified"] = "Last-Modified", ["location"] = "Location", ["max-forwards"] = "Max-Forwards", ["message-id"] = "Message-ID", ["mime-version"] = "MIME-Version", ["original-envelope-id"] = "Original-Envelope-ID", ["original-recipient"] = "Original-Recipient", ["pragma"] = "Pragma", ["proxy-authenticate"] = "Proxy-Authenticate", ["proxy-authorization"] = "Proxy-Authorization", ["range"] = "Range", ["received"] = "Received", ["received-from-mta"] = "Received-From-MTA", ["references"] = "References", ["referer"] = "Referer", ["remote-mta"] = "Remote-MTA", ["reply-to"] = "Reply-To", ["reporting-mta"] = "Reporting-MTA", ["resent-bcc"] = "Resent-Bcc", ["resent-cc"] = "Resent-Cc", ["resent-date"] = "Resent-Date", ["resent-from"] = "Resent-From", ["resent-message-id"] = "Resent-Message-ID", ["resent-reply-to"] = "Resent-Reply-To", ["resent-sender"] = "Resent-Sender", ["resent-to"] = "Resent-To", ["retry-after"] = "Retry-After", ["return-path"] = "Return-Path", ["sender"] = "Sender", ["server"] = "Server", ["smtp-remote-recipient"] = "SMTP-Remote-Recipient", ["status"] = "Status", ["subject"] = "Subject", ["te"] = "TE", ["to"] = "To", ["trailer"] = "Trailer", ["transfer-encoding"] = "Transfer-Encoding", ["upgrade"] = "Upgrade", ["user-agent"] = "User-Agent", ["vary"] = "Vary", ["via"] = "Via", ["warning"] = "Warning", ["will-retry-until"] = "Will-Retry-Until", ["www-authenticate"] = "WWW-Authenticate", ["x-mailer"] = "X-Mailer", } return _M
mit
keyanmca/MonaClients
IndustrialComputing/main.lua
3
1557
_clients = {} -- array of WebSocket clients function onConnection(client,...) -- Register client if (client.protocol=="WebSocket") then _clients[client]=client end function client:initClient() INFO("Init client, actuator: ", data.actuator, " - pool : ", data.pool, " - lamp ON : ", data.lampON) -- First Initialisation if data.pool == nil then data.pool = 0 data.actuator = 0 data.lampON = 0 end client.writer:writeMessage("setActuator", tonumber(data.actuator)) client.writer:writeMessage("setPool", tonumber(data.pool)) client.writer:writeMessage('setLamp', data.lampON) end function client:onCursor(value) data.actuator = value NOTE("actuator: ", data.actuator) sendToClients('setActuator', tonumber(data.actuator)) end function client:onPoolAdd(value) if value > 50 then return end data.pool = value + 1 NOTE("pool : ", data.pool) sendToClients('setPool', tonumber(data.pool)) end function client:onPoolDel(value) if value < -10 then return end data.pool = value - 1 NOTE("pool : ", data.pool) sendToClients('setPool', tonumber(data.pool)) end function client:onLamp(lampON) NOTE("lamp ON : ", lampON) data.lampON = lampON sendToClients('setLamp', data.lampON) end return { index="index.html" } end -- Send a message to all WebSocket clients function sendToClients(event, value) for client, c in pairs(_clients) do client.writer:writeMessage(event, value) end end -- Unregister the client function onDisconnection(client) _clients[client]=nil end
lgpl-3.0
MustaphaTR/OpenRA
mods/d2k/maps/harkonnen-08/harkonnen08.lua
7
11990
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] OrdosBase = { OConYard, OOutpost, OPalace, ORefinery1, ORefinery2, OHeavyFactory, OLightFactory, OHiTechFactory, OResearch, ORepair, OStarport, OGunt1, OGunt2, OGunt3, OGunt4, OGunt5, OGunt6, ORock1, ORock2, ORock3, ORock4, OBarracks1, OBarracks2, OPower1, OPower2, OPower3, OPower4, OPower5, OPower6, OPower7, OPower8, OPower9, OPower10, OPower11, OPower12, OPower13 } AtreidesBase = { AConYard, AOutpost, ARefinery1, ARefinery2, AHeavyFactory, ALightFactory, AHiTechFactory, ARepair, AStarport, AGunt1, AGunt2, ARock1, ARock2, APower1, APower2, APower3, APower4, APower5, APower6, APower7, APower8, APower9 } MercenaryBase = { MHeavyFactory, MStarport, MGunt, MPower1, MPower2 } OrdosReinforcements = { easy = { { "trooper", "trooper", "quad", "quad" }, { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf", "raider", "raider" }, { "combat_tank_o", "quad" } }, normal = { { "trooper", "trooper", "trooper", "quad", "quad" }, { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf", "light_inf", "raider", "raider" }, { "combat_tank_o", "combat_tank_o" }, { "raider", "raider", "quad", "quad", "deviator" } }, hard = { { "trooper", "trooper", "trooper", "trooper", "quad", "quad" }, { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "raider", "raider" }, { "combat_tank_o", "combat_tank_o", "quad" }, { "raider", "raider", "raider", "quad", "quad", "deviator" }, { "siege_tank", "combat_tank_o", "combat_tank_o", "raider" } } } MercenaryStarportReinforcements = { { "trooper", "trooper", "trooper", "trooper", "trooper", "trooper", "quad", "quad" }, { "quad", "combat_tank_o", "trike", "quad", "trooper", "trooper" }, { "trooper", "trooper", "trooper", "trooper", "siege_tank", "siege_tank" }, { "quad", "quad", "combat_tank_o", "combat_tank_o", "combat_tank_o" } } OrdosAttackDelay = { easy = DateTime.Minutes(3), normal = DateTime.Minutes(2) + DateTime.Seconds(20), hard = DateTime.Minutes(1) } MercenaryStarportDelay = DateTime.Minutes(1) + DateTime.Seconds(20) OrdosAttackWaves = { easy = 4, normal = 5, hard = 6 } InitialOrdosReinforcements = { { "trooper", "trooper", "trooper", "trooper", "light_inf", "light_inf", "light_inf" }, { "trooper", "trooper", "trooper", "trooper", "trooper", "combat_tank_o", "combat_tank_o" } } InitialAtreidesReinforcements = { "combat_tank_a", "combat_tank_a", "quad", "quad", "trike" } InitialMercenaryReinforcements = { "trooper", "trooper", "trooper", "trooper", "quad", "quad" } OrdosPaths = { { OrdosEntry1.Location, OrdosRally1.Location }, { OrdosEntry2.Location, OrdosRally2.Location }, { OrdosEntry3.Location, OrdosRally3.Location }, { OrdosEntry4.Location, OrdosRally4.Location } } InitialOrdosPaths = { { OLightFactory.Location, OrdosRally5.Location }, { OHiTechFactory.Location, OrdosRally6.Location } } SaboteurPaths = { { SaboteurWaypoint1.Location, SaboteurWaypoint2.Location, SaboteurWaypoint3.Location }, { SaboteurWaypoint4.Location, SaboteurWaypoint5.Location, SaboteurWaypoint6.Location } } InitialAtreidesPath = { AStarport.Location, AtreidesRally.Location } InitialMercenaryPath = { MStarport.Location, MercenaryRally.Location } SendStarportReinforcements = function(faction) Trigger.AfterDelay(MercenaryStarportDelay, function() if MStarport.IsDead or MStarport.Owner ~= faction then return end reinforcements = Utils.Random(MercenaryStarportReinforcements) local units = Reinforcements.ReinforceWithTransport(faction, "frigate", reinforcements, { MercenaryStarportEntry.Location, MStarport.Location + CVec.New(1, 1) }, { MercenaryStarportExit.Location })[2] Utils.Do(units, function(unit) unit.AttackMove(MercenaryAttackLocation) IdleHunt(unit) end) SendStarportReinforcements(faction) end) end SendAirStrike = function() if AHiTechFactory.IsDead or AHiTechFactory.Owner ~= atreides_enemy then return end local targets = Utils.Where(player.GetActors(), function(actor) return actor.HasProperty("Sell") and actor.Type ~= "wall" and actor.Type ~= "medium_gun_turret" and actor.Type ~= "large_gun_turret" and actor.Type ~= "silo" and actor.Type ~= "wind_trap" end) if #targets > 0 then AHiTechFactory.TargetAirstrike(Utils.Random(targets).CenterPosition) end Trigger.AfterDelay(DateTime.Minutes(5), SendAirStrike) end GetSaboteurTargets = function(player) return Utils.Where(player.GetActors(), function(actor) return actor.HasProperty("Sell") and actor.Type ~= "wall" and actor.Type ~= "medium_gun_turret" and actor.Type ~= "large_gun_turret" and actor.Type ~= "silo" end) end BuildSaboteur = function() if OPalace.IsDead or OPalace.Owner ~= ordos then return end local targets = GetSaboteurTargets(player) if #targets > 0 then local saboteur = Actor.Create("saboteur", true, { Owner = ordos, Location = OPalace.Location + CVec.New(0, 2) }) saboteur.Move(saboteur.Location + CVec.New(0, 1)) saboteur.Wait(DateTime.Seconds(5)) local path = Utils.Random(SaboteurPaths) saboteur.Move(path[1]) saboteur.Move(path[2]) saboteur.Move(path[3]) SendSaboteur(saboteur) end Trigger.AfterDelay(DateTime.Minutes(1) + DateTime.Seconds(30), BuildSaboteur) end SendSaboteur = function(saboteur) local targets = GetSaboteurTargets(player) if #targets < 1 then return end local target = Utils.Random(targets) saboteur.Demolish(target) -- 'target' got removed from the world in the meantime saboteur.CallFunc(function() SendSaboteur(saboteur) end) end CheckAttackToAtreides = function() AtreidesUnits = atreides_neutral.GetActors() Utils.Do(AtreidesUnits, function(unit) Trigger.OnDamaged(unit, function(self, attacker) if attacker.Owner == player and not check then ChangeOwner(atreides_neutral, atreides_enemy) -- Ensure that harvesters that was on a carryall switched sides. Trigger.AfterDelay(DateTime.Seconds(15), function() ChangeOwner(atreides_neutral, atreides_enemy) end) check = true Media.DisplayMessage("The Atreides are now hostile!", "Mentat") end end) end) end ChangeOwner = function(old_owner, new_owner) local units = old_owner.GetActors() Utils.Do(units, function(unit) if not unit.IsDead then unit.Owner = new_owner end end) end Tick = function() if player.HasNoRequiredUnits() then ordos.MarkCompletedObjective(KillHarkonnen1) atreides_enemy.MarkCompletedObjective(KillHarkonnen2) end if ordos.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillOrdos) then Media.DisplayMessage("The Ordos have been annihilated!", "Mentat") player.MarkCompletedObjective(KillOrdos) end if atreides_enemy.HasNoRequiredUnits() and atreides_neutral.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillAtreides) then Media.DisplayMessage("The Atreides have been annihilated!", "Mentat") player.MarkCompletedObjective(KillAtreides) end if mercenary_enemy.HasNoRequiredUnits() and mercenary_ally.HasNoRequiredUnits() and not MercenariesDestroyed then Media.DisplayMessage("The Mercenaries have been annihilated!", "Mentat") MercenariesDestroyed = true end if DateTime.GameTime % DateTime.Seconds(10) == 0 and LastHarvesterEaten[ordos] then local units = ordos.GetActorsByType("harvester") if #units > 0 then LastHarvesterEaten[ordos] = false ProtectHarvester(units[1], ordos, AttackGroupSize[Difficulty]) end end if DateTime.GameTime % DateTime.Seconds(10) == 0 and LastHarvesterEaten[atreides_enemy] then local units = atreides_enemy.GetActorsByType("harvester") if #units > 0 then LastHarvesterEaten[atreides_enemy] = false ProtectHarvester(units[1], atreides_enemy, AttackGroupSize[Difficulty]) end end end WorldLoaded = function() ordos = Player.GetPlayer("Ordos") atreides_enemy = Player.GetPlayer("Ordos Aligned Atreides") atreides_neutral = Player.GetPlayer("Neutral Atreides") mercenary_enemy = Player.GetPlayer("Ordos Aligned Mercenaries") mercenary_ally = Player.GetPlayer("Harkonnen Aligned Mercenaries") player = Player.GetPlayer("Harkonnen") InitObjectives(player) KillOrdos = player.AddPrimaryObjective("Destroy the Ordos.") KillAtreides = player.AddSecondaryObjective("Destroy the Atreides.") AllyWithMercenaries = player.AddSecondaryObjective("Persuade the Mercenaries to fight with\nHouse Harkonnen.") KillHarkonnen1 = ordos.AddPrimaryObjective("Kill all Harkonnen units.") KillHarkonnen2 = atreides_enemy.AddPrimaryObjective("Kill all Harkonnen units.") Camera.Position = HMCV.CenterPosition OrdosAttackLocation = HMCV.Location MercenaryAttackLocation = HMCV.Location Trigger.AfterDelay(DateTime.Minutes(5), SendAirStrike) Trigger.AfterDelay(DateTime.Minutes(1) + DateTime.Seconds(30), BuildSaboteur) Trigger.OnCapture(MHeavyFactory, function() player.MarkCompletedObjective(AllyWithMercenaries) Media.DisplayMessage("Leader Captured. Mercenaries have been persuaded to fight with House Harkonnen.", "Mentat") MercenaryAttackLocation = MercenaryAttackPoint.Location ChangeOwner(mercenary_enemy, mercenary_ally) SendStarportReinforcements(mercenary_ally) DefendAndRepairBase(mercenary_ally, MercenaryBase, 0.75, AttackGroupSize[Difficulty]) IdlingUnits[mercenary_ally] = IdlingUnits[mercenary_enemy] end) Trigger.OnKilled(MHeavyFactory, function() if not player.IsObjectiveCompleted(AllyWithMercenaries) then player.MarkFailedObjective(AllyWithMercenaries) end end) Trigger.OnKilledOrCaptured(OPalace, function() Media.DisplayMessage("We cannot stand against the Harkonnen. We must become neutral.", "Atreides Commander") ChangeOwner(atreides_enemy, atreides_neutral) DefendAndRepairBase(atreides_neutral, AtreidesBase, 0.75, AttackGroupSize[Difficulty]) IdlingUnits[atreides_neutral] = IdlingUnits[atreides_enemy] -- Ensure that harvesters that was on a carryall switched sides. Trigger.AfterDelay(DateTime.Seconds(15), function() ChangeOwner(atreides_enemy, atreides_neutral) CheckAttackToAtreides() end) end) Trigger.OnAllKilledOrCaptured(OrdosBase, function() Utils.Do(ordos.GetGroundAttackers(), IdleHunt) end) Trigger.OnAllKilledOrCaptured(AtreidesBase, function() Utils.Do(atreides_enemy.GetGroundAttackers(), IdleHunt) end) Trigger.OnAllKilledOrCaptured(MercenaryBase, function() Utils.Do(mercenary_enemy.GetGroundAttackers(), IdleHunt) Utils.Do(mercenary_ally.GetGroundAttackers(), IdleHunt) end) local path = function() return Utils.Random(OrdosPaths) end local waveCondition = function() return player.IsObjectiveCompleted(KillOrdos) end local huntFunction = function(unit) unit.AttackMove(OrdosAttackLocation) IdleHunt(unit) end SendCarryallReinforcements(ordos, 0, OrdosAttackWaves[Difficulty], OrdosAttackDelay[Difficulty], path, OrdosReinforcements[Difficulty], waveCondition, huntFunction) SendStarportReinforcements(mercenary_enemy) Actor.Create("upgrade.barracks", true, { Owner = ordos }) Actor.Create("upgrade.light", true, { Owner = ordos }) Actor.Create("upgrade.heavy", true, { Owner = ordos }) Actor.Create("upgrade.barracks", true, { Owner = atreides_enemy }) Actor.Create("upgrade.light", true, { Owner = atreides_enemy }) Actor.Create("upgrade.heavy", true, { Owner = atreides_enemy }) Actor.Create("upgrade.hightech", true, { Owner = atreides_enemy }) Actor.Create("upgrade.heavy", true, { Owner = mercenary_enemy }) Trigger.AfterDelay(0, ActivateAI) end
gpl-3.0
areku/awesomerc
rc.lua
2
20876
-- Standard awesome library local gears = require("gears") local awful = require("awful") awful.rules = require("awful.rules") require("awful.autofocus") -- Widget and layout library local wibox = require("wibox") local vicious = require("vicious") -- Theme handling library local beautiful = require("beautiful") -- Notification library local naughty = require("naughty") local menubar = require("menubar") -- {{{ Error handling -- Check if awesome encountered an error during startup and fell back to -- another config (This code will only ever execute for the fallback config) if awesome.startup_errors then naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors }) end -- Handle runtime errors after startup do local in_error = false awesome.connect_signal("debug::error", function (err) -- Make sure we don't go into an endless error loop if in_error then return end in_error = true naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = err }) in_error = false end) end -- }}} -- {{{ Variable definitions -- Themes define colours, icons, font and wallpapers. beautiful.init("/usr/share/awesome/themes/zenburn/theme.lua") -- beautiful.init("/home/weigl/.config/awesome/themes/matrix/theme.lua") local APW = require("apw/widget") --{{{ APW theme.apw_fg_color = {type = 'linear', from = {0, 0}, to={40,0}, stops={{0, "#CC8888"}, {.4, "#88CC88"}, {.8, "#8888CC"}}} theme.apw_bg_color = "#333333" theme.apw_mute_fg_color = "#CC9393" theme.apw_mute_bg_color = "#663333" --}}} beautiful.wallpaper = "/home/weigla/.wallpaper.jpg" -- This is used later as the default terminal and editor to run. terminal = "urxvtc" editor = os.getenv("EDITOR") or "vim" editor_cmd = terminal .. " -e " .. editor -- Default modkey. -- Usually, Mod4 is the key with a logo between Control and Alt. -- If you do not like this or do not have such a key, -- I suggest you to remap Mod4 to another key using xmodmap or other tools. -- However, you can use another modifier like Mod1, but it may interact with others. modkey = "Mod4" -- Table of layouts to cover with awful.layout.inc, order matters. local layouts = { awful.layout.suit.floating, awful.layout.suit.tile, awful.layout.suit.tile.left, awful.layout.suit.tile.bottom, awful.layout.suit.tile.top, awful.layout.suit.fair, awful.layout.suit.fair.horizontal, awful.layout.suit.spiral, awful.layout.suit.spiral.dwindle, awful.layout.suit.max, awful.layout.suit.max.fullscreen, awful.layout.suit.magnifier } -- }}} -- {{{ Wallpaper if beautiful.wallpaper then for s = 1, screen.count() do gears.wallpaper.maximized(beautiful.wallpaper, s, true) end end -- }}} -- {{{ Tags -- Define a tag table which hold all screen tags. tags = {} for s = 1, screen.count() do -- Each screen has its own tag table. tags[s] = awful.tag({ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, s, layouts[1]) end -- }}} -- {{{ Menu -- Create a laucher widget and a main menu myawesomemenu = { { "manual", terminal .. " -e man awesome" }, { "edit config", editor_cmd .. " " .. awesome.conffile }, { "restart", awesome.restart }, { "firefox", "firefox"} -- { "quit", awesome.quit } } mymainmenu = awful.menu({ items = { { "awesome", myawesomemenu, beautiful.awesome_icon }, { "open terminal", terminal } } }) mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon, menu = mymainmenu }) -- Menubar configuration menubar.utils.terminal = terminal -- Set the terminal for applications that require it -- }}} -- {{{ Wibox -- Create a textclock widget mytextclock = awful.widget.textclock() -- Create a wibox for each screen and add it mywibox = {} mypromptbox = {} mylayoutbox = {} mytaglist = {} mytaglist.buttons = awful.util.table.join( awful.button({ }, 1, awful.tag.viewonly), awful.button({ modkey }, 1, awful.client.movetotag), awful.button({ }, 3, awful.tag.viewtoggle), awful.button({ modkey }, 3, awful.client.toggletag), awful.button({ }, 4, function(t) awful.tag.viewnext(awful.tag.getscreen(t)) end), awful.button({ }, 5, function(t) awful.tag.viewprev(awful.tag.getscreen(t)) end) ) mytasklist = {} mytasklist.buttons = awful.util.table.join( awful.button({ }, 1, function (c) if c == client.focus then c.minimized = true else -- Without this, the following -- :isvisible() makes no sense c.minimized = false if not c:isvisible() then awful.tag.viewonly(c:tags()[1]) end -- This will also un-minimize -- the client, if needed client.focus = c c:raise() end end), awful.button({ }, 3, function () if instance then instance:hide() instance = nil else instance = awful.menu.clients({ theme = { width = 250 } }) end end), awful.button({ }, 4, function () awful.client.focus.byidx(1) if client.focus then client.focus:raise() end end), awful.button({ }, 5, function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end)) memwidget = wibox.widget.textbox() cpuwidget = wibox.widget.textbox() volwidget = wibox.widget.textbox() mysystrace = wibox.widget.systray() vicious.register(volwidget, vicious.widgets.volume, "$1%", 10, "Master") vicious.register(memwidget, vicious.widgets.mem, "mem $1% ", 13) --($2MB/$3MB) vicious.register(cpuwidget, vicious.widgets.cpu, "cpu $1%", 10) -- batwidget = awful.widget.progressbar() -- batwidget:set_width(8) -- batwidget:set_height(10) -- batwidget:set_vertical(true) -- batwidget:set_background_color("#494B4F") -- batwidget:set_border_color(nil) -- batwidget:set_color({ type = "linear", from = { 0, 0 }, to = { 0, 10 }, -- stops = { { 0, "#AECF96" }, { 0.5, "#88A175" }, -- { 1, "#FF5656" }}}) -- vicious.register(batwidget, vicious.widgets.bat, "$2", 61, "BAT0") -- Initialize widget -- mpdwidget = wibox.widget.textbox() --vicious.register(mpdwidget, vicious.widgets.mpd, -- function (mpdwidget, args) -- if args["{state}"] == "Stop" then -- return " - " -- else -- return args["{Artist}"]..' - '.. args["{Title}"] -- end -- end, 10) for s = 1, screen.count() do -- Create a promptbox for each screen mypromptbox[s] = awful.widget.prompt() -- Create an imagebox widget which will contains an icon indicating which layout we're using. -- We need one layoutbox per screen. mylayoutbox[s] = awful.widget.layoutbox(s) mylayoutbox[s]:buttons(awful.util.table.join( awful.button({ }, 1, function () awful.layout.inc(layouts, 1) end), awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end), awful.button({ }, 4, function () awful.layout.inc(layouts, 1) end), awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end))) -- Create a taglist widget mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.filter.all, mytaglist.buttons) -- Create a tasklist widget mytasklist[s] = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, mytasklist.buttons) -- Create the wibox mywibox[s] = awful.wibox({ position = "top", screen = s }) -- Widgets that are aligned to the left local left_layout = wibox.layout.fixed.horizontal() left_layout:add(mylauncher) left_layout:add(mytaglist[s]) left_layout:add(mypromptbox[s]) -- Widgets that are aligned to the right local right_layout = wibox.layout.fixed.horizontal() if s == 1 then right_layout:add(wibox.widget.systray()) end -- right_layout:add(volwidget) right_layout:add(APW) -- right_layout:add(batwidget) right_layout:add(memwidget) --right_layout:add(mpdwidget) right_layout:add(cpuwidget) right_layout:add(mysystrace) right_layout:add(mytextclock) right_layout:add(mylayoutbox[s]) -- Now bring it all together (with the tasklist in the middle) local layout = wibox.layout.align.horizontal() layout:set_left(left_layout) layout:set_middle(mytasklist[s]) layout:set_right(right_layout) mywibox[s]:set_widget(layout) end -- }}} -- {{{ Mouse bindings root.buttons(awful.util.table.join( awful.button({ }, 3, function () mymainmenu:toggle() end), awful.button({ }, 4, awful.tag.viewnext), awful.button({ }, 5, awful.tag.viewprev) )) -- }}} -- {{{ Key bindings globalkeys = awful.util.table.join( awful.key({ modkey, }, "Left", awful.tag.viewprev ), awful.key({ modkey, }, "Right", awful.tag.viewnext ), awful.key({ modkey, }, "Escape", awful.tag.history.restore), awful.key({ modkey, }, "j", function () awful.client.focus.byidx( 1) if client.focus then client.focus:raise() end end), awful.key({ modkey, }, "k", function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end), awful.key({ modkey, }, "w", function () mymainmenu:show() end), -- Layout manipulation awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end), awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end), awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end), awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end), awful.key({ modkey, }, "u", awful.client.urgent.jumpto), awful.key({ modkey, }, "Tab", function () awful.client.focus.history.previous() if client.focus then client.focus:raise() end end), -- Standard program awful.key({ modkey, }, "Return", function () awful.util.spawn(terminal) end), awful.key({ modkey, "Control" }, "r", awesome.restart), awful.key({ modkey, "Shift" }, "q", awesome.quit), awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end), awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end), awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1) end), awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1) end), awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1) end), awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1) end), awful.key({ modkey, }, "space", function () awful.layout.inc(layouts, 1) end), awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(layouts, -1) end), awful.key({ modkey, "Control" }, "n", awful.client.restore), -- Prompt awful.key({ modkey }, "r", function () mypromptbox[mouse.screen]:run() end), awful.key({ modkey }, "x", function () awful.prompt.run({ prompt = "Run Lua code: " }, mypromptbox[mouse.screen].widget, awful.util.eval, nil, awful.util.getdir("cache") .. "/history_eval") end), -- Menubar awful.key({ modkey }, "p", function() menubar.show() end), -- Volume Control awful.key({ }, "XF86AudioRaiseVolume",APW.Up), awful.key({ }, "XF86AudioLowerVolume", APW.Down), awful.key({ }, "XF86AudioMute", APW.ToggleMute) ) clientkeys = awful.util.table.join( awful.key({ modkey, }, "f", function (c) c.fullscreen = not c.fullscreen end), awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end), awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ), awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end), awful.key({ modkey, }, "o", awful.client.movetoscreen ), awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end), awful.key({ modkey, }, "n", function (c) -- The client currently has the input focus, so it cannot be -- minimized, since minimized clients can't have the focus. c.minimized = true end), awful.key({ modkey, }, "m", function (c) c.maximized_horizontal = not c.maximized_horizontal c.maximized_vertical = not c.maximized_vertical end) ) -- Bind all key numbers to tags. -- Be careful: we use keycodes to make it works on any keyboard layout. -- This should map on the top row of your keyboard, usually 1 to 9. for i = 1, 9 do globalkeys = awful.util.table.join(globalkeys, -- View tag only. awful.key({ modkey }, "#" .. i + 9, function () local screen = mouse.screen local tag = awful.tag.gettags(screen)[i] if tag then awful.tag.viewonly(tag) end end), -- Toggle tag. awful.key({ modkey, "Control" }, "#" .. i + 9, function () local screen = mouse.screen local tag = awful.tag.gettags(screen)[i] if tag then awful.tag.viewtoggle(tag) end end), -- Move client to tag. awful.key({ modkey, "Shift" }, "#" .. i + 9, function () if client.focus then local tag = awful.tag.gettags(client.focus.screen)[i] if tag then awful.client.movetotag(tag) end end end), -- Toggle tag. awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9, function () if client.focus then local tag = awful.tag.gettags(client.focus.screen)[i] if tag then awful.client.toggletag(tag) end end end)) end clientbuttons = awful.util.table.join( awful.button({ }, 1, function (c) client.focus = c; c:raise() end), awful.button({ modkey }, 1, awful.mouse.client.move), awful.button({ modkey }, 3, awful.mouse.client.resize)) -- Set keys root.keys(globalkeys) -- }}} -- {{{ Rules -- Rules to apply to new clients (through the "manage" signal). awful.rules.rules = { -- All clients will match this rule. { rule = { }, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = awful.client.focus.filter, raise = true, keys = clientkeys, buttons = clientbuttons } }, { rule = { class = "MPlayer" }, properties = { floating = true } }, { rule = { class = "pinentry" }, properties = { floating = true } }, { rule = { class = "gimp" }, properties = { floating = true } }, -- Set Firefox to always map on tags number 2 of screen 1. -- { rule = { class = "Firefox" }, -- properties = { tag = tags[1][2] } }, } -- }}} -- {{{ Signals -- Signal function to execute when a new client appears. client.connect_signal("manage", function (c, startup) -- Enable sloppy focus c:connect_signal("mouse::enter", function(c) if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier and awful.client.focus.filter(c) then client.focus = c end end) if not startup then -- Set the windows at the slave, -- i.e. put it at the end of others instead of setting it master. -- awful.client.setslave(c) -- Put windows in a smart way, only if they does not set an initial position. if not c.size_hints.user_position and not c.size_hints.program_position then awful.placement.no_overlap(c) awful.placement.no_offscreen(c) end end local titlebars_enabled = false if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then -- buttons for the titlebar local buttons = awful.util.table.join( awful.button({ }, 1, function() client.focus = c c:raise() awful.mouse.client.move(c) end), awful.button({ }, 3, function() client.focus = c c:raise() awful.mouse.client.resize(c) end) ) -- Widgets that are aligned to the left local left_layout = wibox.layout.fixed.horizontal() left_layout:add(awful.titlebar.widget.iconwidget(c)) left_layout:buttons(buttons) -- Widgets that are aligned to the right local right_layout = wibox.layout.fixed.horizontal() right_layout:add(awful.titlebar.widget.floatingbutton(c)) right_layout:add(awful.titlebar.widget.maximizedbutton(c)) right_layout:add(awful.titlebar.widget.stickybutton(c)) right_layout:add(awful.titlebar.widget.ontopbutton(c)) right_layout:add(awful.titlebar.widget.closebutton(c)) -- The title goes in the middle local middle_layout = wibox.layout.flex.horizontal() local title = awful.titlebar.widget.titlewidget(c) title:set_align("center") middle_layout:add(title) middle_layout:buttons(buttons) -- Now bring it all together local layout = wibox.layout.align.horizontal() layout:set_left(left_layout) layout:set_right(right_layout) layout:set_middle(middle_layout) awful.titlebar(c):set_widget(layout) end end) client.connect_signal("focus", function(c) c.border_color = "#729fcf" end) client.connect_signal("unfocus", function(c) c.border_color = "#dae3e0" end) -- }}} -- Autostart {{{ function run_once(prg, arg_string, pname, screen) if not prg then do return nil end end if not pname then pname = prg end if not arg_string then awful.util.spawn_with_shell( "pgrep -f -u $USER -x '" .. pname .. "' || (" .. prg .. ")", screen) else awful.util.spawn_with_shell( "pgrep -f -u $USER -x '" .. pname .. " " .. arg_string .."' || (" .. prg .. " " .. arg_string .. ")", screen) end end run_once("xscreensaver","-no-splash") -- run_once("pidgin",nil,nil,2) run_once("urxvtd -f") -- }}}
gpl-3.0
BrasileiroGamer/TrineEE_TranslationTools
translations/portuguese/lua/data/locale/gui/pt/menu/mainmenu/visualsettingsmenu.lua
1
1245
-- /data/locale/gui/$$/menu/mainmenu/visualsettingsmenu.lua headerVisualSettings = "Configurações Visuais" subheaderStereo3D = "Configurações do 3D Estereoscópico" infoNoBrightness = "O brilho só pode ser aplicado no modo de tela cheia" buttonUiVisibility = "Visibilidade da UI" buttonEnableStereo3D = "3D Estereoscópico" valueAlways = "Sempre" valueFlash = "Flash" valueOn = "Ligado" valueOff = "Desligado" tooltipUiVisibility = "" tooltipAlways = "Exibe retratos dos personagens em todos os momentos" tooltipFlash = "Os retratos de personagem são exibidos ao alterar o personagem ou recebendo dano" sliderBrightness = "Brilho" sliderSeparation = "Separação" sliderConvergence = "Convergência" sliderUIDepth = "Profundidade da UI" buttonReset = "Restaurar Padrões" popupResetDefaults = "Restaurar para as configurações padrão?" buttonTooltipsEnabled = "Dicas" valueSmall = "Pequeno" valueMedium = "Médio" valueLarge = "Grande" buttonFPSCapEnabled = "Habilitar Limitação de FPS" inputFPSCap = "Limitação de FPS" buttonWiiUReset = "Resetar" sliderWiiUBrightness2 = "Brilho do Wii U GamePad" valueUIOff = "Desligado" valueUIPartial = "Parcial" valueUIAll = "Todos"
gpl-3.0
Noltari/luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/sensors.lua
5
2954
-- Copyright 2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local m, s, o local sensor_types = { ["12v"] = "voltage", ["2.0v"] = "voltage", ["2.5v"] = "voltage", ["3.3v"] = "voltage", ["5.0v"] = "voltage", ["5v"] = "voltage", ["ain1"] = "voltage", ["ain2"] = "voltage", ["cpu_temp"] = "temperature", ["fan1"] = "fanspeed", ["fan2"] = "fanspeed", ["fan3"] = "fanspeed", ["fan4"] = "fanspeed", ["fan5"] = "fanspeed", ["fan6"] = "fanspeed", ["fan7"] = "fanspeed", ["in0"] = "voltage", ["in10"] = "voltage", ["in2"] = "voltage", ["in3"] = "voltage", ["in4"] = "voltage", ["in5"] = "voltage", ["in6"] = "voltage", ["in7"] = "voltage", ["in8"] = "voltage", ["in9"] = "voltage", ["power1"] = "power", ["remote_temp"] = "temperature", ["temp1"] = "temperature", ["temp2"] = "temperature", ["temp3"] = "temperature", ["temp4"] = "temperature", ["temp5"] = "temperature", ["temp6"] = "temperature", ["temp7"] = "temperature", ["temp"] = "temperature", ["vccp1"] = "voltage", ["vccp2"] = "voltage", ["vdd"] = "voltage", ["vid1"] = "voltage", ["vid2"] = "voltage", ["vid3"] = "voltage", ["vid4"] = "voltage", ["vid5"] = "voltage", ["vid"] = "voltage", ["vin1"] = "voltage", ["vin2"] = "voltage", ["vin3"] = "voltage", ["vin4"] = "voltage", ["volt12"] = "voltage", ["volt5"] = "voltage", ["voltbatt"] = "voltage", ["vrm"] = "voltage" } m = Map("luci_statistics", translate("Sensors Plugin Configuration"), translate("The sensors plugin uses the Linux Sensors framework to gather environmental statistics.")) s = m:section( NamedSection, "collectd_sensors", "luci_statistics" ) o = s:option( Flag, "enable", translate("Enable this plugin") ) o.default = 0 o = s:option(Flag, "__all", translate("Monitor all sensors")) o:depends("enable", 1) o.default = 1 o.write = function() end o.cfgvalue = function(self, sid) local v = self.map:get(sid, "Sensor") if v == nil or (type(v) == "table" and #v == 0) or (type(v) == "string" and #v == 0) then return "1" end end o = s:option(MultiValue, "Sensor", translate("Sensor list"), translate("Hold Ctrl to select multiple items or to deselect entries.")) o:depends({enable = 1, __all = "" }) o.widget = "select" o.rmempty = true o.size = 0 local sensorcli = io.popen("/usr/sbin/sensors -u -A") if sensorcli then local bus, sensor while true do local ln = sensorcli:read("*ln") if not ln then break elseif ln:match("^[%w-]+$") then bus = ln elseif ln:match("^[%w-]+:$") then sensor = ln:sub(0, -2):lower() if bus and sensor_types[sensor] then o:value("%s/%s-%s" %{ bus, sensor_types[sensor], sensor }) o.size = o.size + 1 end elseif ln == "" then bus = nil sensor = nil end end sensorcli:close() end o = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") ) o.default = 0 o.rmempty = true o:depends({ enable = 1, __all = "" }) return m
apache-2.0
BrasileiroGamer/TrineEE_TranslationTools
translations/portuguese/lua/data/locale/gui/pt/hud/collection_messages_window.lua
1
1293
-- /data/locale/gui/$$/hud/collection_messages_window.lua picked_up_mana_potion = "Você pegou uma poção de mana" picked_up_large_mana_potion = "Você pegou uma grande poção de mana" picked_up_health_potion = "Você pegou uma poção de saúde" picked_up_full_health_potion = "Você pegou uma poção de saúde completa" picked_up_large_health_potion = "Você pegou uma grande poção de saúde" picked_up_winter_present = "Você encontrou um segredo festivo" picked_up_mystery_bottle = "Você encontrou uma garrafa misteriosa" picked_up_mystery_bottle_last_one = "Você encontrou a última garrafa misteriosa, algo foi desbloqueado..." picked_up_experience_shard = "Você adquiriu experiência" picked_up_large_experience_shard = "Você adquiriu grande experiência" grappling_hook_attaches_only_to_wooden_surfaces = "O gancho agarra-se somente em superfícies de madeira" item_vial_h_proc = "Você usou o Frasco de Saúde para recuperar saúde" item_vial_h_info = "(Recarrega no próximo checkpoint)" item_vial_e_proc = "Você usou o Frasco de Mana para recuperar mana" item_vial_e_info = "(Recarrega no próximo checkpoint)" item_resur_gem_proc = "Você foi ressuscitado pela Gema da Ressurreição" item_resur_gem_info = "(Esgotado até o próximo nível)"
gpl-3.0
bsmr-games/lipsofsuna
data/system/widgets/label.lua
1
2191
--- TODO:doc -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module system.widgets.label -- @alias Label local Class = require("system/class") local Widget = require("system/widget") --- TODO:doc -- @type Label local Label = Class("Label", Widget) Label.new = function(clss) local self = Widget.new(clss) self.text = "" self.halign = 0 self.valign = 0.5 return self end Label.reshaped = function(self) local wrap,_ = self:get_request() self:calculate_request{ font = self.font, internal = true, paddings = {2,2,2,2}, text = self.text, width = wrap and (wrap - 4)} local f = self.focused local p = self.pressed self:canvas_clear() self:canvas_text{ dest_position = {0,0}, dest_size = {self:get_width(),self:get_height()}, text = self.text, text_alignment = {self.halign,self.valign}, text_color = self.color or (f and p and {0.6,0.6,0,1} or p and {0.6,0.6,0.6,0.6} or {1,1,1,1}), text_font = self.font} self:canvas_compile() end Label.get_color = function(self) return self.color end Label.get_focused = function(self) return self.focused end Label.get_font = function(self) return self.font end Label.get_text = function(self) return self.text end Label.set_color = function(self, v) if not v then return end self.color = v self:reshaped() end Label.set_focused = function(self, v) if self.focused == v then return end self.focused = v self:reshaped() end Label.set_halign = function(self, v) if not v then return end if self.halign == v then return end self.halign = v self:reshaped() end Label.set_font = function(self, v) if not v then return end if self.font == v then return end self.font = v self:reshaped() end Label.set_text = function(self, v) if not v then return end if self.text == v then return end self.text = v self:reshaped() end Label.set_valign = function(self, v) if not v then return end if self.valign == v then return end self.halign = v self:reshaped() end return Label
gpl-3.0
dismantl/luci-0.12
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
86
2540
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") m = Map("network", translate("Routes"), translate("Routes specify over which interface and gateway a certain host or network " .. "can be reached.")) local routes6 = luci.sys.net.routes6() local bit = require "bit" s = m:section(TypedSection, "route", translate("Static IPv4 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) t = s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network")) t.datatype = "ip4addr" t.rmempty = false n = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")) n.placeholder = "255.255.255.255" n.datatype = "ip4addr" n.rmempty = true g = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) g.datatype = "ip4addr" g.rmempty = true metric = s:option(Value, "metric", translate("Metric")) metric.placeholder = 0 metric.datatype = "range(0,255)" metric.rmempty = true mtu = s:option(Value, "mtu", translate("MTU")) mtu.placeholder = 1500 mtu.datatype = "range(64,9000)" mtu.rmempty = true if routes6 then s = m:section(TypedSection, "route6", translate("Static IPv6 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) t = s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)")) t.datatype = "ip6addr" t.rmempty = false g = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")) g.datatype = "ip6addr" g.rmempty = true metric = s:option(Value, "metric", translate("Metric")) metric.placeholder = 0 metric.datatype = "range(0,65535)" -- XXX: not sure metric.rmempty = true mtu = s:option(Value, "mtu", translate("MTU")) mtu.placeholder = 1500 mtu.datatype = "range(64,9000)" mtu.rmempty = true end return m
apache-2.0
119/aircam-openwrt
build_dir/target-arm_v5te_uClibc-0.9.32_eabi/lua-5.1.4/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
gpl-2.0
dismantl/luci-0.12
applications/luci-statistics/luasrc/model/cbi/luci_statistics/rrdtool.lua
80
3431
--[[ Luci configuration model for statistics - collectd rrdtool plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("RRDTool Plugin Configuration"), translate( "The rrdtool plugin stores the collected data in rrd database " .. "files, the foundation of the diagrams.<br /><br />" .. "<strong>Warning: Setting the wrong values will result in a very " .. "high memory consumption in the temporary directory. " .. "This can render the device unusable!</strong>" )) -- collectd_rrdtool config section s = m:section( NamedSection, "collectd_rrdtool", "luci_statistics" ) -- collectd_rrdtool.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 1 -- collectd_rrdtool.datadir (DataDir) datadir = s:option( Value, "DataDir", translate("Storage directory") ) datadir.default = "/tmp" datadir.rmempty = true datadir.optional = true datadir:depends( "enable", 1 ) -- collectd_rrdtool.stepsize (StepSize) stepsize = s:option( Value, "StepSize", translate("RRD step interval"), translate("Seconds") ) stepsize.default = 30 stepsize.isinteger = true stepsize.rmempty = true stepsize.optional = true stepsize:depends( "enable", 1 ) -- collectd_rrdtool.heartbeat (HeartBeat) heartbeat = s:option( Value, "HeartBeat", translate("RRD heart beat interval"), translate("Seconds") ) heartbeat.default = 60 heartbeat.isinteger = true heartbeat.rmempty = true heartbeat.optional = true heartbeat:depends( "enable", 1 ) -- collectd_rrdtool.rrasingle (RRASingle) rrasingle = s:option( Flag, "RRASingle", translate("Only create average RRAs"), translate("reduces rrd size") ) rrasingle.default = true rrasingle.rmempty = true rrasingle.optional = true rrasingle:depends( "enable", 1 ) -- collectd_rrdtool.rratimespans (RRATimespan) rratimespans = s:option( Value, "RRATimespans", translate("Stored timespans"), translate("seconds; multiple separated by space") ) rratimespans.default = "600 86400 604800 2678400 31622400" rratimespans.rmempty = true rratimespans.optional = true rratimespans:depends( "enable", 1 ) -- collectd_rrdtool.rrarows (RRARows) rrarows = s:option( Value, "RRARows", translate("Rows per RRA") ) rrarows.isinteger = true rrarows.default = 100 rrarows.rmempty = true rrarows.optional = true rrarows:depends( "enable", 1 ) -- collectd_rrdtool.xff (XFF) xff = s:option( Value, "XFF", translate("RRD XFiles Factor") ) xff.default = 0.1 xff.isnumber = true xff.rmempty = true xff.optional = true xff:depends( "enable", 1 ) -- collectd_rrdtool.cachetimeout (CacheTimeout) cachetimeout = s:option( Value, "CacheTimeout", translate("Cache collected data for"), translate("Seconds") ) cachetimeout.isinteger = true cachetimeout.default = 100 cachetimeout.rmempty = true cachetimeout.optional = true cachetimeout:depends( "enable", 1 ) -- collectd_rrdtool.cacheflush (CacheFlush) cacheflush = s:option( Value, "CacheFlush", translate("Flush cache after"), translate("Seconds") ) cacheflush.isinteger = true cacheflush.default = 100 cacheflush.rmempty = true cacheflush.optional = true cacheflush:depends( "enable", 1 ) return m
apache-2.0
LaFamiglia/Illarion-Content
npc/base/consequence/inform.lua
4
1040
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local class = require("base.class") local consequence = require("npc.base.consequence.consequence") local _inform_helper local inform = class(consequence, function(self, text) consequence:init(self) self["text"] = tostring(text) self["perform"] = _inform_helper end) function _inform_helper(self, npcChar, player) player:inform(self.text) end return inform
agpl-3.0
staeld/lua-ruuvi
servobj.lua
1
1415
#!/usr/bin/env lua -- servobj.lua - Server object creation for lua-ruuvi -- Copyright Stæld Lakorv, 2013 <staeld@illumine.ch> -- This file is part of lua-ruuvi. -- lua-ruuvi is released under the GPLv3 - see COPYING local M = {} function M.new(url) if type(url) ~= "string" then aux.throwError("not a string") end local obj = {} if not url:find(vars.apiPath:gsub("([%.%-%+])", "%%%1")) then url = url:gsub("/$", "") .. vars.apiPath end obj.url = url obj._c = aux.connObj(url) obj._c:setopt_useragent(libName .."/".. libVersion) function obj:ping() return aux.ping(self) end -- Events function obj:events(idString, paramArray) return events.getList(self, idString, paramArray) end -- Trackers function obj:trackerId(name) return trackers.getId(self, name) end function obj:trackerCode(id) return trackers.getCode(self, id) end function obj:trackerName(id) return trackers.getName(self, id) end function obj:trackers(idString, paramArray) return trackers.getList(self, idString, paramArray) end function obj:eventsFor(idString, paramArray) return events.getFor(self, idString, paramArray) end function obj:latestFor(idString, paramArray) return events.getLatestFor(self, idString, paramArray) end return obj end return M -- EOF
gpl-3.0
soundsrc/premake-core
binmodules/luasocket/test/testclnt.lua
20
22799
local socket = require"socket" host = host or "localhost" port = port or "8383" function printf(...) io.stderr:write(string.format(...)) end function pass(...) printf(...) io.stderr:write("\n") end function fail(...) io.stderr:write("ERROR: ") printf(...) io.stderr:write("!\n") os.exit() end function warn(...) local s = string.format(...) io.stderr:write("WARNING: ", s, "\n") end function remote(...) local s = string.format(...) s = string.gsub(s, "\n", ";") s = string.gsub(s, "%s+", " ") s = string.gsub(s, "^%s*", "") control:send(s .. "\n") control:receive() end function test(test) io.stderr:write("----------------------------------------------\n", "testing: ", test, "\n", "----------------------------------------------\n") end function check_timeout(tm, sl, elapsed, err, opp, mode, alldone) if tm < sl then if opp == "send" then if not err then warn("must be buffered") elseif err == "timeout" then pass("proper timeout") else fail("unexpected error '%s'", err) end else if err ~= "timeout" then fail("should have timed out") else pass("proper timeout") end end else if mode == "total" then if elapsed > tm then if err ~= "timeout" then fail("should have timed out") else pass("proper timeout") end elseif elapsed < tm then if err then fail(err) else pass("ok") end else if alldone then if err then fail("unexpected error '%s'", err) else pass("ok") end else if err ~= "timeout" then fail(err) else pass("proper timeoutk") end end end else if err then fail(err) else pass("ok") end end end end if not socket._DEBUG then fail("Please define LUASOCKET_DEBUG and recompile LuaSocket") end io.stderr:write("----------------------------------------------\n", "LuaSocket Test Procedures\n", "----------------------------------------------\n") start = socket.gettime() function reconnect() if data then data:close() end remote [[ if data then data:close() data = nil end data = server:accept() data:setoption("tcp-nodelay", true) ]] data, err = socket.connect(host, port) if not data then fail(err) end data:setoption("tcp-nodelay", true) end printf("attempting control connection...") control, err = socket.connect(host, port) if err then fail(err) else pass("connected!") end control:setoption("tcp-nodelay", true) ------------------------------------------------------------------------ function test_methods(sock, methods) for _, v in pairs(methods) do if type(sock[v]) ~= "function" then fail(sock.class .. " method '" .. v .. "' not registered") end end pass(sock.class .. " methods are ok") end ------------------------------------------------------------------------ function test_mixed(len) reconnect() io.stderr:write("length " .. len .. ": ") local inter = math.ceil(len/4) local p1 = "unix " .. string.rep("x", inter) .. "line\n" local p2 = "dos " .. string.rep("y", inter) .. "line\r\n" local p3 = "raw " .. string.rep("z", inter) .. "bytes" local p4 = "end" .. string.rep("w", inter) .. "bytes" local bp1, bp2, bp3, bp4 remote (string.format("str = data:receive(%d)", string.len(p1)+string.len(p2)+string.len(p3)+string.len(p4))) sent, err = data:send(p1..p2..p3..p4) if err then fail(err) end remote "data:send(str); data:close()" bp1, err = data:receive() if err then fail(err) end bp2, err = data:receive() if err then fail(err) end bp3, err = data:receive(string.len(p3)) if err then fail(err) end bp4, err = data:receive("*a") if err then fail(err) end if bp1.."\n" == p1 and bp2.."\r\n" == p2 and bp3 == p3 and bp4 == p4 then pass("patterns match") else fail("patterns don't match") end end ------------------------------------------------------------------------ if not math.mod then math.mod = math.fmod end function test_asciiline(len) reconnect() io.stderr:write("length " .. len .. ": ") local str, str10, back, err str = string.rep("x", math.mod(len, 10)) str10 = string.rep("aZb.c#dAe?", math.floor(len/10)) str = str .. str10 remote "str = data:receive()" sent, err = data:send(str.."\n") if err then fail(err) end remote "data:send(str ..'\\n')" back, err = data:receive() if err then fail(err) end if back == str then pass("lines match") else fail("lines don't match") end end ------------------------------------------------------------------------ function test_rawline(len) reconnect() io.stderr:write("length " .. len .. ": ") local str, str10, back, err str = string.rep(string.char(47), math.mod(len, 10)) str10 = string.rep(string.char(120,21,77,4,5,0,7,36,44,100), math.floor(len/10)) str = str .. str10 remote "str = data:receive()" sent, err = data:send(str.."\n") if err then fail(err) end remote "data:send(str..'\\n')" back, err = data:receive() if err then fail(err) end if back == str then pass("lines match") else fail("lines don't match") end end ------------------------------------------------------------------------ function test_raw(len) reconnect() io.stderr:write("length " .. len .. ": ") local half = math.floor(len/2) local s1, s2, back, err s1 = string.rep("x", half) s2 = string.rep("y", len-half) remote (string.format("str = data:receive(%d)", len)) sent, err = data:send(s1) if err then fail(err) end sent, err = data:send(s2) if err then fail(err) end remote "data:send(str)" back, err = data:receive(len) if err then fail(err) end if back == s1..s2 then pass("blocks match") else fail("blocks don't match") end end ------------------------------------------------------------------------ function test_totaltimeoutreceive(len, tm, sl) reconnect() local str, err, partial printf("%d bytes, %ds total timeout, %ds pause: ", len, tm, sl) remote (string.format ([[ data:settimeout(%d) str = string.rep('a', %d) data:send(str) print('server: sleeping for %ds') socket.sleep(%d) print('server: woke up') data:send(str) ]], 2*tm, len, sl, sl)) data:settimeout(tm, "total") local t = socket.gettime() str, err, partial, elapsed = data:receive(2*len) check_timeout(tm, sl, elapsed, err, "receive", "total", string.len(str or partial) == 2*len) end ------------------------------------------------------------------------ function test_totaltimeoutsend(len, tm, sl) reconnect() local str, err, total printf("%d bytes, %ds total timeout, %ds pause: ", len, tm, sl) remote (string.format ([[ data:settimeout(%d) str = data:receive(%d) print('server: sleeping for %ds') socket.sleep(%d) print('server: woke up') str = data:receive(%d) ]], 2*tm, len, sl, sl, len)) data:settimeout(tm, "total") str = string.rep("a", 2*len) total, err, partial, elapsed = data:send(str) check_timeout(tm, sl, elapsed, err, "send", "total", total == 2*len) end ------------------------------------------------------------------------ function test_blockingtimeoutreceive(len, tm, sl) reconnect() local str, err, partial printf("%d bytes, %ds blocking timeout, %ds pause: ", len, tm, sl) remote (string.format ([[ data:settimeout(%d) str = string.rep('a', %d) data:send(str) print('server: sleeping for %ds') socket.sleep(%d) print('server: woke up') data:send(str) ]], 2*tm, len, sl, sl)) data:settimeout(tm) str, err, partial, elapsed = data:receive(2*len) check_timeout(tm, sl, elapsed, err, "receive", "blocking", string.len(str or partial) == 2*len) end ------------------------------------------------------------------------ function test_blockingtimeoutsend(len, tm, sl) reconnect() local str, err, total printf("%d bytes, %ds blocking timeout, %ds pause: ", len, tm, sl) remote (string.format ([[ data:settimeout(%d) str = data:receive(%d) print('server: sleeping for %ds') socket.sleep(%d) print('server: woke up') str = data:receive(%d) ]], 2*tm, len, sl, sl, len)) data:settimeout(tm) str = string.rep("a", 2*len) total, err, partial, elapsed = data:send(str) check_timeout(tm, sl, elapsed, err, "send", "blocking", total == 2*len) end ------------------------------------------------------------------------ function empty_connect() printf("empty connect: ") reconnect() if data then data:close() data = nil end remote [[ if data then data:close() data = nil end data = server:accept() ]] data, err = socket.connect("", port) if not data then pass("ok") data = socket.connect(host, port) else pass("gethostbyname returns localhost on empty string...") end end ------------------------------------------------------------------------ function isclosed(c) return c:getfd() == -1 or c:getfd() == (2^32-1) end function active_close() local tcp = socket.tcp4() if isclosed(tcp) then fail("should not be closed") end tcp:close() if not isclosed(tcp) then fail("should be closed") end tcp = socket.tcp() if not isclosed(tcp) then fail("should be closed") end tcp = nil local udp = socket.udp4() if isclosed(udp) then fail("should not be closed") end udp:close() if not isclosed(udp) then fail("should be closed") end udp = socket.udp() if not isclosed(udp) then fail("should be closed") end udp = nil pass("ok") end ------------------------------------------------------------------------ function test_closed() local back, partial, err local str = 'little string' reconnect() printf("trying read detection: ") remote (string.format ([[ data:send('%s') data:close() data = nil ]], str)) -- try to get a line back, err, partial = data:receive() if not err then fail("should have gotten 'closed'.") elseif err ~= "closed" then fail("got '"..err.."' instead of 'closed'.") elseif str ~= partial then fail("didn't receive partial result.") else pass("graceful 'closed' received") end reconnect() printf("trying write detection: ") remote [[ data:close() data = nil ]] total, err, partial = data:send(string.rep("ugauga", 100000)) if not err then pass("failed: output buffer is at least %d bytes long!", total) elseif err ~= "closed" then fail("got '"..err.."' instead of 'closed'.") else pass("graceful 'closed' received after %d bytes were sent", partial) end end ------------------------------------------------------------------------ function test_selectbugs() local r, s, e = socket.select(nil, nil, 0.1) assert(type(r) == "table" and type(s) == "table" and (e == "timeout" or e == "error")) pass("both nil: ok") local udp = socket.udp() udp:close() r, s, e = socket.select({ udp }, { udp }, 0.1) assert(type(r) == "table" and type(s) == "table" and (e == "timeout" or e == "error")) pass("closed sockets: ok") e = pcall(socket.select, "wrong", 1, 0.1) assert(e == false, tostring(e)) e = pcall(socket.select, {}, 1, 0.1) assert(e == false, tostring(e)) pass("invalid input: ok") local toomany = {} for i = 1, socket._SETSIZE+1 do toomany[#toomany+1] = socket.udp4() end if #toomany > socket._SETSIZE then local e = pcall(socket.select, toomany, nil, 0.1) assert(e == false, tostring(e)) pass("too many sockets (" .. #toomany .. "): ok") else pass("unable to create enough sockets (max was "..#toomany..")") pass("try using ulimit") end for _, c in ipairs(toomany) do c:close() end end ------------------------------------------------------------------------ function accept_timeout() printf("accept with timeout (if it hangs, it failed): ") local s, e = socket.bind("*", 0, 0) assert(s, e) local t = socket.gettime() s:settimeout(1) local c, e = s:accept() assert(not c, "should not accept") assert(e == "timeout", string.format("wrong error message (%s)", e)) t = socket.gettime() - t assert(t < 2, string.format("took to long to give up (%gs)", t)) s:close() pass("good") end ------------------------------------------------------------------------ function connect_timeout() printf("connect with timeout (if it hangs, it failed!): ") local t = socket.gettime() local c, e = socket.tcp() assert(c, e) c:settimeout(0.1) local t = socket.gettime() local r, e = c:connect("10.0.0.1", 81) assert(not r, "should not connect") assert(socket.gettime() - t < 2, "took too long to give up.") c:close() pass("ok") end ------------------------------------------------------------------------ function accept_errors() printf("not listening: ") local d, e = socket.bind("*", 0) assert(d, e); local c, e = socket.tcp(); assert(c, e); d:setfd(c:getfd()) d:settimeout(2) local r, e = d:accept() assert(not r and e) pass("ok") printf("not supported: ") local c, e = socket.udp() assert(c, e); d:setfd(c:getfd()) local r, e = d:accept() assert(not r and e) pass("ok") end ------------------------------------------------------------------------ function connect_errors() printf("connection refused: ") local c, e = socket.connect("localhost", 1); assert(not c and e) pass("ok") printf("host not found: ") local c, e = socket.connect("host.is.invalid", 1); assert(not c and e, e) pass("ok") end ------------------------------------------------------------------------ function rebind_test() local c ,c1 = socket.bind("127.0.0.1", 0) if not c then pass ("failed to bind! " .. tostring(c) .. ' ' .. tostring(c1)) return end assert(c,c1) local i, p = c:getsockname() local s, e = socket.tcp() assert(s, e) s:setoption("reuseaddr", false) r, e = s:bind(i, p) assert(not r, "managed to rebind!") assert(e) pass("ok") end ------------------------------------------------------------------------ function getstats_test() reconnect() local t = 0 for i = 1, 25 do local c = math.random(1, 100) remote (string.format ([[ str = data:receive(%d) data:send(str) ]], c)) data:send(string.rep("a", c)) data:receive(c) t = t + c local r, s, a = data:getstats() assert(r == t, "received count failed" .. tostring(r) .. "/" .. tostring(t)) assert(s == t, "sent count failed" .. tostring(s) .. "/" .. tostring(t)) end pass("ok") end ------------------------------------------------------------------------ function test_nonblocking(size) reconnect() printf("testing " .. 2*size .. " bytes: ") remote(string.format([[ data:send(string.rep("a", %d)) socket.sleep(0.5) data:send(string.rep("b", %d) .. "\n") ]], size, size)) local err = "timeout" local part = "" local str data:settimeout(0) while 1 do str, err, part = data:receive("*l", part) if err ~= "timeout" then break end end assert(str == (string.rep("a", size) .. string.rep("b", size))) reconnect() remote(string.format([[ str = data:receive(%d) socket.sleep(0.5) str = data:receive(2*%d, str) data:send(str) ]], size, size)) data:settimeout(0) local start = 0 while 1 do ret, err, start = data:send(str, start+1) if err ~= "timeout" then break end end data:send("\n") data:settimeout(-1) local back = data:receive(2*size) assert(back == str, "'" .. back .. "' vs '" .. str .. "'") pass("ok") end ------------------------------------------------------------------------ function test_readafterclose() local back, partial, err local str = 'little string' reconnect() printf("trying repeated '*a' pattern") remote (string.format ([[ data:send('%s') data:close() data = nil ]], str)) back, err, partial = data:receive("*a") assert(back == str, "unexpected data read") back, err, partial = data:receive("*a") assert(back == nil and err == "closed", "should have returned 'closed'") pass("ok") reconnect() printf("trying active close before '*a'") remote (string.format ([[ data:close() data = nil ]])) data:close() back, err, partial = data:receive("*a") assert(back == nil and err == "closed", "should have returned 'closed'") pass("ok") reconnect() printf("trying active close before '*l'") remote (string.format ([[ data:close() data = nil ]])) data:close() back, err, partial = data:receive() assert(back == nil and err == "closed", "should have returned 'closed'") pass("ok") reconnect() printf("trying active close before raw 1") remote (string.format ([[ data:close() data = nil ]])) data:close() back, err, partial = data:receive(1) assert(back == nil and err == "closed", "should have returned 'closed'") pass("ok") reconnect() printf("trying active close before raw 0") remote (string.format ([[ data:close() data = nil ]])) data:close() back, err, partial = data:receive(0) assert(back == nil and err == "closed", "should have returned 'closed'") pass("ok") end ------------------------------------------------------------------------ function test_writeafterclose() local str = 'little string' reconnect() remote (string.format ([[ data:close() data = nil ]])) local sent, err, errsent while not err do sent, err, errsent, time = data:send(str) end assert(err == "closed", "got " .. err .. " instead of 'closed'") pass("ok") end ------------------------------------------------------------------------ function test_partialrecv() local str = 'little string' reconnect() remote([[ data:send("7890") ]]) data:settimeout(1) back, err = data:receive(10, "123456") assert(back == "1234567890", "failed on exact mixed length") back, err = data:receive(8, "87654321") assert(back == "87654321", "failed on exact length") back, err = data:receive(4, "87654321") assert(back == "87654321", "failed on smaller length") pass("ok") end ------------------------------------------------------------------------ test("method registration") local tcp_methods = { "accept", "bind", "close", "connect", "dirty", "getfamily", "getfd", "getoption", "getpeername", "getsockname", "getstats", "setstats", "listen", "receive", "send", "setfd", "setoption", "setpeername", "setsockname", "settimeout", "shutdown", } test_methods(socket.tcp(), tcp_methods) do local sock = socket.tcp6() if sock then test_methods(socket.tcp6(), tcp_methods) else io.stderr:write("Warning! IPv6 does not support!\n") end end local udp_methods = { "close", "dirty", "getfamily", "getfd", "getoption", "getpeername", "getsockname", "receive", "receivefrom", "send", "sendto", "setfd", "setoption", "setpeername", "setsockname", "settimeout" } ------------------------------------------------------------------------ test_methods(socket.udp(), udp_methods) do local sock = socket.tcp6() if sock then test_methods(socket.udp6(), udp_methods) else io.stderr:write("Warning! IPv6 does not support!\n") end end test("closed connection detection: ") test_closed() test("partial receive") test_partialrecv() test("select function") test_selectbugs() test("read after close") test_readafterclose() test("write after close") test_writeafterclose() test("connect function") connect_timeout() empty_connect() connect_errors() test("rebinding: ") rebind_test() test("active close: ") active_close() test("accept function: ") accept_timeout() accept_errors() test("getstats test") getstats_test() test("character line") test_asciiline(1) test_asciiline(17) test_asciiline(200) test_asciiline(4091) test_asciiline(80199) test_asciiline(8000000) test_asciiline(80199) test_asciiline(4091) test_asciiline(200) test_asciiline(17) test_asciiline(1) test("mixed patterns") test_mixed(1) test_mixed(17) test_mixed(200) test_mixed(4091) test_mixed(801990) test_mixed(4091) test_mixed(200) test_mixed(17) test_mixed(1) test("binary line") test_rawline(1) test_rawline(17) test_rawline(200) test_rawline(4091) test_rawline(80199) test_rawline(8000000) test_rawline(80199) test_rawline(4091) test_rawline(200) test_rawline(17) test_rawline(1) test("raw transfer") test_raw(1) test_raw(17) test_raw(200) test_raw(4091) test_raw(80199) test_raw(8000000) test_raw(80199) test_raw(4091) test_raw(200) test_raw(17) test_raw(1) test("non-blocking transfer") test_nonblocking(1) test_nonblocking(17) test_nonblocking(200) test_nonblocking(4091) test_nonblocking(80199) test_nonblocking(800000) test_nonblocking(80199) test_nonblocking(4091) test_nonblocking(200) test_nonblocking(17) test_nonblocking(1) test("total timeout on send") test_totaltimeoutsend(800091, 1, 3) test_totaltimeoutsend(800091, 2, 3) test_totaltimeoutsend(800091, 5, 2) test_totaltimeoutsend(800091, 3, 1) test("total timeout on receive") test_totaltimeoutreceive(800091, 1, 3) test_totaltimeoutreceive(800091, 2, 3) test_totaltimeoutreceive(800091, 3, 2) test_totaltimeoutreceive(800091, 3, 1) test("blocking timeout on send") test_blockingtimeoutsend(800091, 1, 3) test_blockingtimeoutsend(800091, 2, 3) test_blockingtimeoutsend(800091, 3, 2) test_blockingtimeoutsend(800091, 3, 1) test("blocking timeout on receive") test_blockingtimeoutreceive(800091, 1, 3) test_blockingtimeoutreceive(800091, 2, 3) test_blockingtimeoutreceive(800091, 3, 2) test_blockingtimeoutreceive(800091, 3, 1) test("shutting server down") reconnect() remote("os.exit()") test(string.format("done in %.2fs", socket.gettime() - start))
bsd-3-clause
ramindel0761/setdelete
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-3.0
tsharly/TSHARLY
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-2.0
hnyman/luci
applications/luci-app-coovachilli/luasrc/model/cbi/coovachilli_radius.lua
79
1554
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. m = Map("coovachilli") -- radius server s1 = m:section(TypedSection, "radius") s1.anonymous = true s1:option( Value, "radiusserver1" ) s1:option( Value, "radiusserver2" ) s1:option( Value, "radiussecret" ).password = true s1:option( Value, "radiuslisten" ).optional = true s1:option( Value, "radiusauthport" ).optional = true s1:option( Value, "radiusacctport" ).optional = true s1:option( Value, "radiusnasid" ).optional = true s1:option( Value, "radiusnasip" ).optional = true s1:option( Value, "radiuscalled" ).optional = true s1:option( Value, "radiuslocationid" ).optional = true s1:option( Value, "radiuslocationname" ).optional = true s1:option( Value, "radiusnasporttype" ).optional = true s1:option( Flag, "radiusoriginalurl" ) s1:option( Value, "adminuser" ).optional = true rs = s1:option( Value, "adminpassword" ) rs.optional = true rs.password = true s1:option( Flag, "swapoctets" ) s1:option( Flag, "openidauth" ) s1:option( Flag, "wpaguests" ) s1:option( Flag, "acctupdate" ) s1:option( Value, "coaport" ).optional = true s1:option( Flag, "coanoipcheck" ) -- radius proxy s2 = m:section(TypedSection, "proxy") s2.anonymous = true s2:option( Value, "proxylisten" ).optional = true s2:option( Value, "proxyport" ).optional = true s2:option( Value, "proxyclient" ).optional = true ps = s2:option( Value, "proxysecret" ) ps.optional = true ps.password = true return m
apache-2.0
adam000/xsera
Resources/Scripts/Tests/BasicPilotAITests.lua
1
16592
-- These tests work on one-on-one interactions between ships - engaging, following, retreating, defending, etc. -- Tests with higher numbers may build on tests with lower numbers, so lower numbered tests should be run first import('GlobalVars') import('Actions') import('Conditions') import('Animation') import('ObjectLoad') --import('Math') import('Scenarios') import('PrintRecursive') import('KeyboardControl') import('PilotAI') import('Interfaces') import('PopDownConsole') import('Camera') import('Physics') import('Effects') import('Proximity') function init() Physics.NewSystem() start_time = mode_manager.time() realTime = mode_manager.time() last_time = mode_manager.time() end function key(k) if k == "escape" then mode_manager.switch("Xsera/MainMenu") elseif k == "1" then -- start test 1 elseif k == "2" then -- start test 2 elseif k == "3" then -- start test 3 elseif k == "4" then -- start test 4 elseif k == "5" then -- start test 5 elseif k == "6" then -- start test 6 elseif k == "7" then -- start test 7 elseif k == "8" then -- start test 8 elseif k == "9" then -- start test 9 end end normal_key = key function update() local newTime = mode_manager.time() dt = newTime - last_time last_time = newTime realTime = realTime + dt if cameraSnap == false then CameraInterpolate(dt) else CameraSnap() cameraSnap = false end KeyDoActivated() --Reset the proximity information for i, o in pairs(scen.objects) do o.proximity = { closest = nil; closestDistance = 0; closestHostile = nil; closestHostileDistance = 0; closestBase = nil; closestBaseDistance = 0; closestHostileBase = nil; closestHostileBaseDistance = nil; }; end for i, o in pairs(scen.objects) do if o.type == "beam" then --[[ BITS HEX FLAG 001 0x1 RELATIVE 010 0x2 STATIC 100 0x4 BOLT --]] if o.base.beam.mode == "relative" then local src = o.gfx.source.position local off = o.gfx.offset local rel = o.gfx.relative local a = src; a = a + off a = a + rel o.physics.position = src + off + rel elseif o.base.beam.mode == "direct" then local from = o.gfx.offset + o.gfx.source.position local dir = NormalizeVec(o.gfx.target.position - o.gfx.source.position) local len = math.min(o.base.beam.range, hypot2(from,o.gfx.target.position)) o.physics.position = dir * len end end if o.status.health <= 0 and o.status.healthMax >= 1 then DestroyTrigger(o) o.status.dead = true end if o.status.energy ~= nil then if o.status.energy < o.status.energyMax and o.status.battery > dt * ENERGY_RECHARGE_RATIO / BASE_RECHARGE_RATE then o.status.energy = o.status.energy + dt * ENERGY_RECHARGE_RATIO / BASE_RECHARGE_RATE o.status.battery = o.status.battery - dt * ENERGY_RECHARGE_RATIO / BASE_RECHARGE_RATE end if o.status.health ~= nil and o.status.health <= o.status.healthMax * SHIELD_RECHARGE_MAX and o.status.energy > SHIELD_RECHARGE_RATIO * dt / BASE_RECHARGE_RATE then o.status.health = o.status.health + dt / BASE_RECHARGE_RATE o.status.energy = o.status.energy - SHIELD_RECHARGE_RATIO * dt / BASE_RECHARGE_RATE end if o.weapons ~= nil then for wid, weap in pairs(o.weapons) do if weap.ammo ~= -1 and weap.base.device.restockCost > 0 and weap.ammo < weap.base.device.ammo / 2 and weap.lastRestock + weap.base.device.restockCost * BASE_RECHARGE_RATE * WEAPON_RESTOCK_RATE / TIME_FACTOR <= realTime and o.status.energy >= weap.base.device.restockCost * WEAPON_RESTOCK_RATIO then o.status.energy = o.status.energy - weap.base.device.restockCost * WEAPON_RESTOCK_RATIO weap.ammo = weap.ammo + 1 weap.lastRestock = realTime end end end end --Lifetimer if o.age ~= nil then if o.age.lifeSpan + o.age.created <= realTime then ExpireTrigger(o) o.status.dead = true end end if o ~= scen.playerShip then Think(o) end if o.triggers.periodic ~= nil and o.triggers.periodic.interval ~= 0 and o.triggers.periodic.next <= realTime then ActivateTrigger(o) o.triggers.periodic.next = realTime + o.triggers.periodic.interval + math.random(0,o.triggers.periodic.range) end --Fire weapons if o.weapons ~= nil then if o.control.pulse == true and o.weapons.pulse ~= nil then ActivateTrigger(o.weapons.pulse, o) end if o.control.beam == true and o.weapons.beam ~= nil then ActivateTrigger(o.weapons.beam, o) end if o.control.special == true and o.weapons.special ~= nil then ActivateTrigger(o.weapons.special, o) end end --[[------------------ Movement ------------------]]-- local rvel if o.base.attributes.canTurn then rvel = o.base.rotation.turnRate else rvel = DEFAULT_ROTATION_RATE end if o.control.left then o.physics.angularVelocity = rvel * 2.0 elseif o.control.right then o.physics.angularVelocity = -rvel * 2.0 else o.physics.angularVelocity = 0 end if o.warp.stage < WARP_RUNNING then if o.control.accel then -- apply a forward force in the direction the ship is facing local angle = o.physics.angle local thrust = o.base.thrust * SPEED_FACTOR local force = vec(thrust * math.cos(angle), thrust * math.sin(angle)) Physics.ApplyImpulse(o.physics, force) end if o.control.decel == true or hypot1(o.physics.velocity) >= o.base.maxVelocity * SPEED_FACTOR then -- apply a reverse force in the direction opposite the direction the ship is MOVING local thrust = o.base.thrust * SPEED_FACTOR local force = o.physics.velocity if force.x ~= 0 or force.y ~= 0 then if hypot1(o.physics.velocity) <= 10 then o.physics.velocity = vec(0, 0) else local velocityMag = hypot1(force) force = -force * thrust / velocityMag if dt * velocityMag / o.physics.mass > velocityMag then o.physics.velocity = vec(0, 0) else Physics.ApplyImpulse(o.physics, force) end end end end elseif o.base.warpSpeed ~= nil then local velocityMag = math.max(o.warp.factor * o.base.warpSpeed, o.base.maxVelocity) * SPEED_FACTOR o.physics.velocity = PolarVec(velocityMag, o.physics.angle) end if o.base.attributes.canAcceptBuild then UpdatePlanet(o, dt) end end RemoveDead() UpdateEffects(dt) Physics.UpdateSystem(dt, scen.objects) end function render() graphics.begin_frame() CameraToObject(scen.playerShip) graphics.begin_warp(scen.playerShip.warp.factor,scen.playerShip.physics.angle, cameraRatio.current) graphics.draw_starfield(3.4) graphics.draw_starfield(1.8) graphics.draw_starfield(0.6) graphics.draw_starfield(-0.3) graphics.draw_starfield(-0.9) graphics.end_warp() if proxDebug then for i, o in pairs(scen.objects) do local p = o.proximity local op = o.physics.position if p.closest ~= nil then graphics.draw_line(op, p.closest.physics.position, 1, {r=0,g=1,b=0,a=1}) end if p.closestHostile ~= nil then graphics.draw_line(op, p.closestHostile.physics.position, 1, {r=1,g=0,b=0,a=1}) end if p.closestBase ~= nil then graphics.draw_line(op, p.closestBase.physics.position, 2, {r=0,g=0,b=1,a=1}) end if p.closestHostileBase ~= nil then graphics.draw_line(op, p.closestHostileBase.physics.position, 2, {r=1,g=1,b=0,a=1}) end end end if targDebug then for i, o in pairs(scen.objects) do if o.ai.objectives.target ~= nil then graphics.draw_line(o.physics.position, o.ai.objectives.target.physics.position, 1, {r=1,g=0,b=0,a=1}) end if o.ai.objectives.dest ~= nil then graphics.draw_line(o.physics.position, o.ai.objectives.dest.physics.position, 1, {r=0,g=0,b=1,a=1}) end end end for layerId, layer in ipairs({1, 2, 3, 0}) do for objectId, object in pairs(scen.objects) do if objectId ~= scen.playerShipId and object.layer == layer then DrawObject(object) end end end graphics.draw_particles() DrawObject(scen.playerShip) DrawEffects() DrawArrow() DrawMouse1() DrawPanels() local cam = CameraToWindow() graphics.set_camera(cam[1], cam[2], cam[3], cam[4]) DrawMouse2() InterfaceDisplay(dt) PopDownConsole() ZoomLevelIndicator() graphics.end_frame() sound.listener(scen.playerShip.physics.position, scen.playerShip.physics.velocity) end function mouse(button, x, y) if button == "wheel_up" then DoScaleIn(0.2) elseif button == "wheel_down" then DoScaleOut(0.2) else mdown = true end end function mouse_up() if mdown then print(cameraRatio.current) local mousePos = GetMouseCoords() if keyboard[2][5].active then -- TARGET scen.playerShip.ai.objectives.targetId, scen.playerShip.ai.objectives.target = NextTargetUnderCursor(scen.playerShip.ai.objectives.targetId, true) else -- CONTROL scen.playerShip.ai.objectives.controlId, scen.playerShip.ai.objectives.control = NextTargetUnderCursor(scen.playerShip.ai.objectives.controlId, false) if scen.playerShip.ai.objectives.control.base.attributes.canAcceptBuild then selection.lastPlanet = scen.playerShip.ai.objectives.control CalculateBuildables(selection.lastPlanet, scen) end end end mdown = false end function shutdown() window.mouse_toggle() end function RemoveDead() --Remove destroyed or expired objects for i, o in pairs(scen.objects) do if o.status.dead then if scen.playerShipId == i then AddPlayerBody() end scen.objects[i] = nil end end end function AddPlayerBody() local body = NewObject(22)--[SCOTT][HARDCODE] body.ai.owner = scen.playerShip.ai.owner body.physics.velocity = scen.playerShip.physics.velocity body.physics.position = scen.playerShip.physics.position body.physics.angle = scen.playerShip.physics.angle local bodyId = body.physics.object_id scen.objects[bodyId] = body SetPlayerShip(bodyId) end function NextPlayerShip() --canAcceptDestination=false means that the object is controllable local idStart = scen.playerShipId local cursorId = idStart local cursor repeat cursorId, cursor = next(scen.objects, cursorId) if cursor.base.attributes.canAcceptDestination then SetPlayerShip(cursorId) break end until cursorId == idStart end function SetPlayerShip(id) scen.playerShipId = id scen.playerShip = scen.objects[id] scen.playerShip.ai.objectives.target = nil scen.playerShip.ai.objectives.dest = nil scen.playerShip.control = { accel = false; decel = false; left = false; right = false; beam = false; pulse = false; special = false; warp = false; } end function Collide(a,b) local o = a local other = b --[[ Equation for 1D elastic collision: v1 = (m1v1 + m2v2 + m1C(v2-v1))/(m1+m2) OR Nathan's Method: dist = dist(v1,v2) angle = angleto(pos1,pos2) momentMag = dist * m1/(m1+m2) v1 = Polar2Rect(1,angle) * dist * m1 / (m1 + m2) v2 = Polar2Rect(1,angle+180) * dist * m2 / (m1 + m2) --]] if o.base.attributes.occupiesSpace and other.base.attributes.occupiesSpace then local p = o.physics local p2 = other.physics v1 = p.velocity m1 = p.mass v2 = p2.velocity m2 = p2.mass --[[ p.velocity = { x = (m1 * v1.x + m2 *v2.x + m1 * RESTITUTION_COEFFICIENT * ( v2.x - v1.x))/(m1+m2); y = (m1 * v1.y + m2 *v2.y + m1 * RESTITUTION_COEFFICIENT * ( v2.y - v1.y))/(m1+m2); } p2.velocity = { x = (m1 * v1.x + m2 *v2.x + m2 * RESTITUTION_COEFFICIENT * ( v1.x - v2.x))/(m1+m2); y = (m1 * v1.y + m2 *v2.y + m2 * RESTITUTION_COEFFICIENT * ( v1.y - v2.y))/(m1+m2); } --]] local dist = hypot2(v1, v2) local angle = findAngle(p.position,p2.position) p.velocity = PolarVec(dist * m1 / (m1+m2), angle) p2.velocity = PolarVec(dist * m2 / (m1+m2), angle+math.pi) end CollideTrigger(o,other) CollideTrigger(other,o) if other.base.damage ~= nil then o.status.health = o.status.health - other.base.damage end if o.base.damage ~= nil then other.status.health = other.status.health - o.base.damage end end function DrawObject(o) o.gfx.cycle = o.gfx.cycle + dt if o.type == "beam" then --[[ BITS HEX FLAG 001 0x1 RELATIVE 010 0x2 STATIC 100 0x4 BOLT --]] if o.base.beam.hex > 0 then local from = o.gfx.source.position + o.gfx.offset if o.base.beam.hex == "bolt" then graphics.draw_lightning(from, o.physics.position, 1.0, 10.0, false,ClutColour(o.base.beam.color)) elseif o.base.beam.type == "static" then graphics.draw_line(from, o.physics.position, 3.0, ClutColour(o.base.beam.color)) end else --kinetic local p1 = o.physics.position local p2 = PolarVec(BEAM_LENGTH,o.physics.angle) graphics.draw_line(p1, p1 + p2, 1, ClutColour(o.base.beam.color)) end else if cameraRatio.current >= 1 / 4 then if o.type == "animation" then graphics.draw_sprite_frame(o.gfx.sprite, o.physics.position, o.gfx.dimensions, Animate(o)) else -- Rotational graphics.draw_sprite(o.gfx.sprite, o.physics.position, o.gfx.dimensions, o.physics.angle) end else local cscale = 1 if o.status.health <= o.status.healthMax / 2 then cscale = math.ceil((math.sin(o.gfx.cycle*4) + 1)*7) end local color if o.ai.owner == -1 then color = ClutColour(4,cscale) elseif o.ai.owner == scen.playerShip.ai.owner then color = ClutColour(5,cscale) else color = ClutColour(16,cscale) end local iconScale = 1.0/cameraRatio.current if o.base.iconShape == "square" then graphics.draw_rbox(o.physics.position, o.base.iconSize * iconScale, color) elseif o.base.iconShape == "plus" then graphics.draw_rplus(o.physics.position, o.base.iconSize * iconScale, color) elseif o.base.iconShape == "triangle" then graphics.draw_rtri(o.physics.position, o.base.iconSize * iconScale, color) elseif o.base.iconShape == "diamond" then graphics.draw_rdia(o.physics.position, o.base.iconSize * iconScale, color) elseif o.base.iconShape == "framed square" then --NOT IMPLEMENTED [TODO] graphics.draw_rbox(o.physics.position, o.base.iconSize * iconScale, color) end end end end
mit
spseol/NEATPybotSolver
src/neat/genetic/containers/species.lua
1
1945
require "neat.genetic.cells.chromosome" require "neat.genetic.factors.mutator" require "core.core" Species = {} SpeciesMeta = {} SpeciesMeta.__index = Species function SpeciesMeta.__tostring(self) return string.format("Species %f", self:averageFitness()) end function Species.new() local o = {} property(Species, "__chromosomes", "chromosomes", nil, o, {}) setmetatable(o, SpeciesMeta) return o end function Species:sortChromosomes() table.sort(self.__chromosomes, function(a, b) return a:fitness() > b:fitness() end) end function Species:averageFitness() local totalFitnessInSpecies = 0 for _, chromosome in pairs(self.__chromosomes) do totalFitnessInSpecies = totalFitnessInSpecies + chromosome:fitness() end return totalFitnessInSpecies / table.keysCount(self.__chromosomes) end function Species:_addChromosome(chromosome) table.insert(self.__chromosomes, chromosome) end function Species:breedChild() local parent1 = self.__chromosomes[math.seededRandom(1, #self.__chromosomes)] local parent2 = self.__chromosomes[math.seededRandom(1, #self.__chromosomes)] return Mutator.breedChild(parent1, parent2) end function Species:mutate() for _, chromosome in pairs(self.__chromosomes) do Mutator.mutateChromosome(chromosome) end end function Species:removeWorstHalf() self:sortChromosomes() for i = 1, math.floor(#self.__chromosomes / 2) do table.remove(self.__chromosomes) end end function Species:removeAllExceptBest() self:sortChromosomes() while #self.__chromosomes > 1 do table.remove(self.__chromosomes) end end function Species:replaceWorstByChildren(children) self:sortChromosomes() for i = 1, #children do table.remove(self.__chromosomes) end for i = 1, #children do self:_addChromosome(children[i]) end end
gpl-2.0
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/openbsd/constants.lua
24
20467
-- tables of constants for NetBSD local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select local abi = require "syscall.abi" local h = require "syscall.helpers" local bit = require "syscall.bit" local version = require "syscall.openbsd.version".version local octal, multiflags, charflags, swapflags, strflag, atflag, modeflags = h.octal, h.multiflags, h.charflags, h.swapflags, h.strflag, h.atflag, h.modeflags local ffi = require "ffi" local function charp(n) return ffi.cast("char *", n) end local c = {} c.errornames = require "syscall.openbsd.errors" c.STD = strflag { IN_FILENO = 0, OUT_FILENO = 1, ERR_FILENO = 2, IN = 0, OUT = 1, ERR = 2, } c.E = strflag { PERM = 1, NOENT = 2, SRCH = 3, INTR = 4, IO = 5, NXIO = 6, ["2BIG"] = 7, NOEXEC = 8, BADF = 9, CHILD = 10, DEADLK = 11, NOMEM = 12, ACCES = 13, FAULT = 14, NOTBLK = 15, BUSY = 16, EXIST = 17, XDEV = 18, NODEV = 19, NOTDIR = 20, ISDIR = 21, INVAL = 22, NFILE = 23, MFILE = 24, NOTTY = 25, TXTBSY = 26, FBIG = 27, NOSPC = 28, SPIPE = 29, ROFS = 30, MLINK = 31, PIPE = 32, DOM = 33, RANGE = 34, AGAIN = 35, INPROGRESS = 36, ALREADY = 37, NOTSOCK = 38, DESTADDRREQ = 39, MSGSIZE = 40, PROTOTYPE = 41, NOPROTOOPT = 42, PROTONOSUPPORT= 43, SOCKTNOSUPPORT= 44, OPNOTSUPP = 45, PFNOSUPPORT = 46, AFNOSUPPORT = 47, ADDRINUSE = 48, ADDRNOTAVAIL = 49, NETDOWN = 50, NETUNREACH = 51, NETRESET = 52, CONNABORTED = 53, CONNRESET = 54, NOBUFS = 55, ISCONN = 56, NOTCONN = 57, SHUTDOWN = 58, TOOMANYREFS = 59, TIMEDOUT = 60, CONNREFUSED = 61, LOOP = 62, NAMETOOLONG = 63, HOSTDOWN = 64, HOSTUNREACH = 65, NOTEMPTY = 66, PROCLIM = 67, USERS = 68, DQUOT = 69, STALE = 70, REMOTE = 71, BADRPC = 72, BADRPC = 72, RPCMISMATCH = 73, PROGUNAVAIL = 74, PROGMISMATCH = 75, PROCUNAVAIL = 76, NOLCK = 77, NOSYS = 78, FTYPE = 79, AUTH = 80, NEEDAUTH = 81, IPSEC = 82, NOATTR = 83, ILSEQ = 84, NOMEDIUM = 85, MEDIUMTYPE = 86, OVERFLOW = 87, CANCELED = 88, IDRM = 89, NOMSG = 90, NOTSUP = 91, } -- alternate names c.EALIAS = { WOULDBLOCK = c.E.AGAIN, } c.AF = strflag { UNSPEC = 0, LOCAL = 1, INET = 2, IMPLINK = 3, PUP = 4, CHAOS = 5, ISO = 7, ECMA = 8, DATAKIT = 9, CCITT = 10, SNA = 11, DECNET = 12, DLI = 13, LAT = 14, HYLINK = 15, APPLETALK = 16, ROUTE = 17, LINK = 18, -- pseudo_AF_XTP 19 COIP = 20, CNT = 21, -- pseudo_AF_RTIP 22 IPX = 23, INET6 = 24, -- pseudo_AF_PIP 25 ISDN = 26, NATM = 27, ENCAP = 28, SIP = 29, KEY = 30, -- pseudo_AF_HDRCMPLT 31 BLUETOOTH = 32, MPLS = 33, -- pseudo_AF_PFLOW 34 -- pseudo_AF_PIPEX 35 } c.AF.UNIX = c.AF.LOCAL c.AF.OSI = c.AF.ISO c.AF.E164 = c.AF.ISDN c.O = multiflags { RDONLY = 0x0000, WRONLY = 0x0001, RDWR = 0x0002, ACCMODE = 0x0003, NONBLOCK = 0x0004, APPEND = 0x0008, SHLOCK = 0x0010, EXLOCK = 0x0020, ASYNC = 0x0040, FSYNC = 0x0080, SYNC = 0x0080, NOFOLLOW = 0x0100, CREAT = 0x0200, TRUNC = 0x0400, EXCL = 0x0800, NOCTTY = 0x8000, CLOEXEC = 0x10000, DIRECTORY = 0x20000, } -- for pipe2, selected flags from c.O c.OPIPE = multiflags { NONBLOCK = 0x0004, CLOEXEC = 0x10000, } -- sigaction, note renamed SIGACT from SIG_ c.SIGACT = strflag { ERR = -1, DFL = 0, IGN = 1, HOLD = 3, } c.SIG = strflag { HUP = 1, INT = 2, QUIT = 3, ILL = 4, TRAP = 5, ABRT = 6, EMT = 7, FPE = 8, KILL = 9, BUS = 10, SEGV = 11, SYS = 12, PIPE = 13, ALRM = 14, TERM = 15, URG = 16, STOP = 17, TSTP = 18, CONT = 19, CHLD = 20, TTIN = 21, TTOU = 22, IO = 23, XCPU = 24, XFSZ = 25, VTALRM = 26, PROF = 27, WINCH = 28, INFO = 29, USR1 = 30, USR2 = 31, THR = 32, } c.EXIT = strflag { SUCCESS = 0, FAILURE = 1, } c.OK = charflags { F = 0, X = 0x01, W = 0x02, R = 0x04, } c.MODE = modeflags { SUID = octal('04000'), SGID = octal('02000'), STXT = octal('01000'), RWXU = octal('00700'), RUSR = octal('00400'), WUSR = octal('00200'), XUSR = octal('00100'), RWXG = octal('00070'), RGRP = octal('00040'), WGRP = octal('00020'), XGRP = octal('00010'), RWXO = octal('00007'), ROTH = octal('00004'), WOTH = octal('00002'), XOTH = octal('00001'), } c.SEEK = strflag { SET = 0, CUR = 1, END = 2, } c.SOCK = multiflags { STREAM = 1, DGRAM = 2, RAW = 3, RDM = 4, SEQPACKET = 5, } if version >= 201505 then c.SOCK.NONBLOCK = 0x4000 c.SOCK.CLOEXEC = 0x8000 end c.SOL = strflag { SOCKET = 0xffff, } c.POLL = multiflags { IN = 0x0001, PRI = 0x0002, OUT = 0x0004, RDNORM = 0x0040, RDBAND = 0x0080, WRBAND = 0x0100, ERR = 0x0008, HUP = 0x0010, NVAL = 0x0020, } c.POLL.WRNORM = c.POLL.OUT c.AT_FDCWD = atflag { FDCWD = -100, } c.AT = multiflags { EACCESS = 0x01, SYMLINK_NOFOLLOW = 0x02, SYMLINK_FOLLOW = 0x04, REMOVEDIR = 0x08, } c.S_I = modeflags { FMT = octal('0170000'), FSOCK = octal('0140000'), FLNK = octal('0120000'), FREG = octal('0100000'), FBLK = octal('0060000'), FDIR = octal('0040000'), FCHR = octal('0020000'), FIFO = octal('0010000'), SUID = octal('0004000'), SGID = octal('0002000'), SVTX = octal('0001000'), STXT = octal('0001000'), RWXU = octal('00700'), RUSR = octal('00400'), WUSR = octal('00200'), XUSR = octal('00100'), RWXG = octal('00070'), RGRP = octal('00040'), WGRP = octal('00020'), XGRP = octal('00010'), RWXO = octal('00007'), ROTH = octal('00004'), WOTH = octal('00002'), XOTH = octal('00001'), } c.S_I.READ = c.S_I.RUSR c.S_I.WRITE = c.S_I.WUSR c.S_I.EXEC = c.S_I.XUSR c.PROT = multiflags { NONE = 0x0, READ = 0x1, WRITE = 0x2, EXEC = 0x4, } c.MAP = multiflags { SHARED = 0x0001, PRIVATE = 0x0002, FILE = 0x0000, FIXED = 0x0010, ANON = 0x1000, } if version < 201411 then -- defined in 5.6 but as zero so no effect c.MAP.RENAME = 0x0020 c.MAP.NORESERVE = 0x0040 c.MAP.HASSEMAPHORE = 0x0200 end c.MCL = strflag { CURRENT = 0x01, FUTURE = 0x02, } -- flags to `msync'. - note was MS_ renamed to MSYNC_ c.MSYNC = multiflags { ASYNC = 0x01, SYNC = 0x02, INVALIDATE = 0x04, } c.MADV = strflag { NORMAL = 0, RANDOM = 1, SEQUENTIAL = 2, WILLNEED = 3, DONTNEED = 4, SPACEAVAIL = 5, FREE = 6, } c.IPPROTO = strflag { IP = 0, HOPOPTS = 0, ICMP = 1, IGMP = 2, GGP = 3, IPV4 = 4, IPIP = 4, TCP = 6, EGP = 8, PUP = 12, UDP = 17, IDP = 22, TP = 29, IPV6 = 41, ROUTING = 43, FRAGMENT = 44, RSVP = 46, GRE = 47, ESP = 50, AH = 51, MOBILE = 55, ICMPV6 = 58, NONE = 59, DSTOPTS = 60, EON = 80, ETHERIP = 97, ENCAP = 98, PIM = 103, IPCOMP = 108, CARP = 112, MPLS = 137, PFSYNC = 240, RAW = 255, } c.SCM = multiflags { RIGHTS = 0x01, TIMESTAMP = 0x04, } c.F = strflag { DUPFD = 0, GETFD = 1, SETFD = 2, GETFL = 3, SETFL = 4, GETOWN = 5, SETOWN = 6, GETLK = 7, SETLK = 8, SETLKW = 9, DUPFD_CLOEXEC= 10, } c.FD = multiflags { CLOEXEC = 1, } -- note changed from F_ to FCNTL_LOCK c.FCNTL_LOCK = strflag { RDLCK = 1, UNLCK = 2, WRLCK = 3, } -- lockf, changed from F_ to LOCKF_ c.LOCKF = strflag { ULOCK = 0, LOCK = 1, TLOCK = 2, TEST = 3, } -- for flock (2) c.LOCK = multiflags { SH = 0x01, EX = 0x02, NB = 0x04, UN = 0x08, } c.W = multiflags { NOHANG = 1, UNTRACED = 2, CONTINUED = 8, STOPPED = octal "0177", } if version < 201405 then c.W.ALTSIG = 4 end -- waitpid and wait4 pid c.WAIT = strflag { ANY = -1, MYPGRP = 0, } c.MSG = multiflags { OOB = 0x1, PEEK = 0x2, DONTROUTE = 0x4, EOR = 0x8, TRUNC = 0x10, CTRUNC = 0x20, WAITALL = 0x40, DONTWAIT = 0x80, BCAST = 0x100, MCAST = 0x200, NOSIGNAL = 0x400, } c.PC = strflag { LINK_MAX = 1, MAX_CANON = 2, MAX_INPUT = 3, NAME_MAX = 4, PATH_MAX = 5, PIPE_BUF = 6, CHOWN_RESTRICTED = 7, NO_TRUNC = 8, VDISABLE = 9, ["2_SYMLINKS"] = 10, ALLOC_SIZE_MIN = 11, ASYNC_IO = 12, FILESIZEBITS = 13, PRIO_IO = 14, REC_INCR_XFER_SIZE= 15, REC_MAX_XFER_SIZE = 16, REC_MIN_XFER_SIZE = 17, REC_XFER_ALIGN = 18, SYMLINK_MAX = 19, SYNC_IO = 20, TIMESTAMP_RESOLUTION = 21, } -- getpriority, setpriority flags c.PRIO = strflag { PROCESS = 0, PGRP = 1, USER = 2, MIN = -20, -- TODO useful to have for other OSs MAX = 20, } c.RUSAGE = strflag { SELF = 0, CHILDREN = -1, THREAD = 1, } c.SOMAXCONN = 128 c.SO = strflag { DEBUG = 0x0001, ACCEPTCONN = 0x0002, REUSEADDR = 0x0004, KEEPALIVE = 0x0008, DONTROUTE = 0x0010, BROADCAST = 0x0020, USELOOPBACK = 0x0040, LINGER = 0x0080, OOBINLINE = 0x0100, REUSEPORT = 0x0200, TIMESTAMP = 0x0800, BINDANY = 0x1000, SNDBUF = 0x1001, RCVBUF = 0x1002, SNDLOWAT = 0x1003, RCVLOWAT = 0x1004, SNDTIMEO = 0x1005, RCVTIMEO = 0x1006, ERROR = 0x1007, TYPE = 0x1008, NETPROC = 0x1020, RTABLE = 0x1021, PEERCRED = 0x1022, SPLICE = 0x1023, } c.DT = strflag { UNKNOWN = 0, FIFO = 1, CHR = 2, DIR = 4, BLK = 6, REG = 8, LNK = 10, SOCK = 12, } c.IP = strflag { OPTIONS = 1, HDRINCL = 2, TOS = 3, TTL = 4, RECVOPTS = 5, RECVRETOPTS = 6, RECVDSTADDR = 7, RETOPTS = 8, MULTICAST_IF = 9, MULTICAST_TTL = 10, MULTICAST_LOOP = 11, ADD_MEMBERSHIP = 12, DROP_MEMBERSHIP = 13, PORTRANGE = 19, AUTH_LEVEL = 20, ESP_TRANS_LEVEL = 21, ESP_NETWORK_LEVEL = 22, IPSEC_LOCAL_ID = 23, IPSEC_REMOTE_ID = 24, IPSEC_LOCAL_CRED = 25, IPSEC_REMOTE_CRED = 26, IPSEC_LOCAL_AUTH = 27, IPSEC_REMOTE_AUTH = 28, IPCOMP_LEVEL = 29, RECVIF = 30, RECVTTL = 31, MINTTL = 32, RECVDSTPORT = 33, PIPEX = 34, RECVRTABLE = 35, IPSECFLOWINFO = 36, RTABLE = 0x1021, DIVERTFL = 0x1022, } -- Baud rates just the identity function other than EXTA, EXTB TODO check c.B = strflag { } c.CC = strflag { VEOF = 0, VEOL = 1, VEOL2 = 2, VERASE = 3, VWERASE = 4, VKILL = 5, VREPRINT = 6, VINTR = 8, VQUIT = 9, VSUSP = 10, VDSUSP = 11, VSTART = 12, VSTOP = 13, VLNEXT = 14, VDISCARD = 15, VMIN = 16, VTIME = 17, VSTATUS = 18, } c.IFLAG = multiflags { IGNBRK = 0x00000001, BRKINT = 0x00000002, IGNPAR = 0x00000004, PARMRK = 0x00000008, INPCK = 0x00000010, ISTRIP = 0x00000020, INLCR = 0x00000040, IGNCR = 0x00000080, ICRNL = 0x00000100, IXON = 0x00000200, IXOFF = 0x00000400, IXANY = 0x00000800, IMAXBEL = 0x00002000, } c.OFLAG = multiflags { OPOST = 0x00000001, ONLCR = 0x00000002, OXTABS = 0x00000004, ONOEOT = 0x00000008, OCRNL = 0x00000010, OLCUC = 0x00000020, ONOCR = 0x00000040, ONLRET = 0x00000080, } c.CFLAG = multiflags { CIGNORE = 0x00000001, CSIZE = 0x00000300, CS5 = 0x00000000, CS6 = 0x00000100, CS7 = 0x00000200, CS8 = 0x00000300, CSTOPB = 0x00000400, CREAD = 0x00000800, PARENB = 0x00001000, PARODD = 0x00002000, HUPCL = 0x00004000, CLOCAL = 0x00008000, CRTSCTS = 0x00010000, MDMBUF = 0x00100000, } c.CFLAG.CRTS_IFLOW = c.CFLAG.CRTSCTS c.CFLAG.CCTS_OFLOW = c.CFLAG.CRTSCTS c.CFLAG.CHWFLOW = c.CFLAG.MDMBUF + c.CFLAG.CRTSCTS c.LFLAG = multiflags { ECHOKE = 0x00000001, ECHOE = 0x00000002, ECHOK = 0x00000004, ECHO = 0x00000008, ECHONL = 0x00000010, ECHOPRT = 0x00000020, ECHOCTL = 0x00000040, ISIG = 0x00000080, ICANON = 0x00000100, ALTWERASE = 0x00000200, IEXTEN = 0x00000400, EXTPROC = 0x00000800, TOSTOP = 0x00400000, FLUSHO = 0x00800000, NOKERNINFO = 0x02000000, PENDIN = 0x20000000, NOFLSH = 0x80000000, } c.TCSA = multiflags { -- this is another odd one, where you can have one flag plus SOFT NOW = 0, DRAIN = 1, FLUSH = 2, SOFT = 0x10, } -- tcflush(), renamed from TC to TCFLUSH c.TCFLUSH = strflag { IFLUSH = 1, OFLUSH = 2, IOFLUSH = 3, } -- termios - tcflow() and TCXONC use these. renamed from TC to TCFLOW c.TCFLOW = strflag { OOFF = 1, OON = 2, IOFF = 3, ION = 4, } -- for chflags and stat. note these have no prefix c.CHFLAGS = multiflags { UF_NODUMP = 0x00000001, UF_IMMUTABLE = 0x00000002, UF_APPEND = 0x00000004, UF_OPAQUE = 0x00000008, SF_ARCHIVED = 0x00010000, SF_IMMUTABLE = 0x00020000, SF_APPEND = 0x00040000, } c.CHFLAGS.IMMUTABLE = c.CHFLAGS.UF_IMMUTABLE + c.CHFLAGS.SF_IMMUTABLE c.CHFLAGS.APPEND = c.CHFLAGS.UF_APPEND + c.CHFLAGS.SF_APPEND c.CHFLAGS.OPAQUE = c.CHFLAGS.UF_OPAQUE c.TCP = strflag { NODELAY = 0x01, MAXSEG = 0x02, MD5SIG = 0x04, SACK_ENABLE = 0x08, } c.RB = multiflags { AUTOBOOT = 0, ASKNAME = 0x0001, SINGLE = 0x0002, NOSYNC = 0x0004, HALT = 0x0008, INITNAME = 0x0010, DFLTROOT = 0x0020, KDB = 0x0040, RDONLY = 0x0080, DUMP = 0x0100, MINIROOT = 0x0200, CONFIG = 0x0400, TIMEBAD = 0x0800, POWERDOWN = 0x1000, SERCONS = 0x2000, USERREQ = 0x4000, } -- kqueue c.EV = multiflags { ADD = 0x0001, DELETE = 0x0002, ENABLE = 0x0004, DISABLE = 0x0008, ONESHOT = 0x0010, CLEAR = 0x0020, SYSFLAGS = 0xF000, FLAG1 = 0x2000, EOF = 0x8000, ERROR = 0x4000, } c.EVFILT = strflag { READ = -1, WRITE = -2, AIO = -3, VNODE = -4, PROC = -5, SIGNAL = -6, TIMER = -7, SYSCOUNT = 7, } c.NOTE = multiflags { -- read and write LOWAT = 0x0001, -- vnode DELETE = 0x0001, WRITE = 0x0002, EXTEND = 0x0004, ATTRIB = 0x0008, LINK = 0x0010, RENAME = 0x0020, REVOKE = 0x0040, -- proc EXIT = 0x80000000, FORK = 0x40000000, EXEC = 0x20000000, PCTRLMASK = 0xf0000000, PDATAMASK = 0x000fffff, TRACK = 0x00000001, TRACKERR = 0x00000002, CHILD = 0x00000004, } c.ITIMER = strflag { REAL = 0, VIRTUAL = 1, PROF = 2, } c.SA = multiflags { ONSTACK = 0x0001, RESTART = 0x0002, RESETHAND = 0x0004, NOCLDSTOP = 0x0008, NODEFER = 0x0010, NOCLDWAIT = 0x0020, SIGINFO = 0x0040, } -- ipv6 sockopts c.IPV6 = strflag { UNICAST_HOPS = 4, MULTICAST_IF = 9, MULTICAST_HOPS = 10, MULTICAST_LOOP = 11, JOIN_GROUP = 12, LEAVE_GROUP = 13, PORTRANGE = 14, --ICMP6_FILTER = 18, -- not namespaced as IPV6 CHECKSUM = 26, V6ONLY = 27, RTHDRDSTOPTS = 35, RECVPKTINFO = 36, RECVHOPLIMIT = 37, RECVRTHDR = 38, RECVHOPOPTS = 39, RECVDSTOPTS = 40, USE_MIN_MTU = 42, RECVPATHMTU = 43, PATHMTU = 44, PKTINFO = 46, HOPLIMIT = 47, NEXTHOP = 48, HOPOPTS = 49, DSTOPTS = 50, RTHDR = 51, RECVTCLASS = 57, TCLASS = 61, DONTFRAG = 62, } if version < 201405 then c.IPV6.SOCKOPT_RESERVED1 = 3 c.IPV6.FAITH = 29 end c.CLOCK = strflag { REALTIME = 0, PROCESS_CPUTIME_ID = 2, MONOTONIC = 3, THREAD_CPUTIME_ID = 4, } if version < 201505 then c.CLOCK.VIRTUAL = 1 end if version >= 201505 then c.CLOCK.UPTIME = 5 end c.UTIME = strflag { NOW = -2, OMIT = -1, } c.PATH_MAX = 1024 c.CTL = strflag { UNSPEC = 0, KERN = 1, VM = 2, FS = 3, NET = 4, DEBUG = 5, HW = 6, MACHDEP = 7, DDB = 9, VFS = 10, MAXID = 11, } c.KERN = strflag { OSTYPE = 1, OSRELEASE = 2, OSREV = 3, VERSION = 4, MAXVNODES = 5, MAXPROC = 6, MAXFILES = 7, ARGMAX = 8, SECURELVL = 9, HOSTNAME = 10, HOSTID = 11, CLOCKRATE = 12, PROF = 16, POSIX1 = 17, NGROUPS = 18, JOB_CONTROL = 19, SAVED_IDS = 20, BOOTTIME = 21, DOMAINNAME = 22, MAXPARTITIONS = 23, RAWPARTITION = 24, MAXTHREAD = 25, NTHREADS = 26, OSVERSION = 27, SOMAXCONN = 28, SOMINCONN = 29, USERMOUNT = 30, RND = 31, NOSUIDCOREDUMP = 32, FSYNC = 33, SYSVMSG = 34, SYSVSEM = 35, SYSVSHM = 36, ARND = 37, MSGBUFSIZE = 38, MALLOCSTATS = 39, CPTIME = 40, NCHSTATS = 41, FORKSTAT = 42, NSELCOLL = 43, TTY = 44, CCPU = 45, FSCALE = 46, NPROCS = 47, MSGBUF = 48, POOL = 49, STACKGAPRANDOM = 50, SYSVIPC_INFO = 51, SPLASSERT = 54, PROC_ARGS = 55, NFILES = 56, TTYCOUNT = 57, NUMVNODES = 58, MBSTAT = 59, SEMINFO = 61, SHMINFO = 62, INTRCNT = 63, WATCHDOG = 64, EMUL = 65, PROC = 66, MAXCLUSTERS = 67, EVCOUNT = 68, TIMECOUNTER = 69, MAXLOCKSPERUID = 70, CPTIME2 = 71, CACHEPCT = 72, FILE = 73, CONSDEV = 75, NETLIVELOCKS = 76, POOL_DEBUG = 77, PROC_CWD = 78, } if version < 201405 then c.KERN.FILE = 15 c.KERN.FILE2 = 73 end if version >= 201411 then c.KERN.PROC_NOBROADCASTKILL = 79 end if version < 201505 then c.KERN.VNODE = 13 c.KERN.USERCRYPTO = 52 c.KERN.CRYPTODEVALLOWSOFT = 53 c.KERN.USERASYMCRYPTO = 60 end return c
apache-2.0
thartman83/awesome-pass
tests/mocks/awful.lua
1
3944
------------------------------------------------------------------------------- -- awful.lua for awesome-pass -- -- Copyright (c) 2017 Tom Hartman (thomas.lees.hartman@gmail.com) -- -- -- -- This program is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU General Public License -- -- as published by the Free Software Foundation; either version 2 -- -- of the License, or the License, or (at your option) any later -- -- version. -- -- -- -- This program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- -- GNU General Public License for more details. -- ------------------------------------------------------------------------------- --- Commentary -- {{{ -- Awful mocks for awesome-pass testing -- }}} local setmetatable = setmetatable --- awful -- {{{ --- menu mocks and stubs-- {{{ local menu = {} menu.mt = {} --- menu_call -- {{{ ---------------------------------------------------------------------- -- ---------------------------------------------------------------------- function menu_call (_, args, parent) return args end -- }}} -- }}} --- spawn mocks and stubs -- {{{ local spawn = {} spawn.callback_values = { stdout = "", stderr = "", exitreason = "", exitcode = "", } spawn.mt = {} --- spawn_call -- {{{ ---------------------------------------------------------------------- -- stub for awful.spawn(...), basically a noop ---------------------------------------------------------------------- function spawn_call (...) return -1 end -- }}} --- spawn.easy_async -- {{{ ---------------------------------------------------------------------- -- Mock function for spawn.easy_async -- Instead of actually making the call to command, this mock applies -- the values of awful.spawn.callback_values to callback -- @param cmd (string or table) The command -- @param callback Function with the following arguments ---------------------------------------------------------------------- function spawn.easy_async (cmd, callback) callback(spawn.callback_values.stdout, spawn.callback_values.stderr, spawn.callback_values.exitreason, spawn.callback_values.exitcode) end -- }}} --- spawn.set_callback_values -- {{{ ---------------------------------------------------------------------- -- Sets the global callback to be used if easy_async is invoked ---------------------------------------------------------------------- function spawn.set_callback_values (stdout, stderr, exitreason, exitcode) spawn.callback_values = { stdout = stdout, stderr = stderr, exitreason = exitreason, exitcode = exitcode, } end -- }}} spawn.mt.__call = spawn_call -- }}} --- button mocks and stubs -- {{{ local button = {} button.mt = {} --- button_call -- {{{ ---------------------------------------------------------------------- -- Stub for awful.button, functionally a nop ---------------------------------------------------------------------- function button_call (...) end -- }}} button.mt.__call = button_call -- }}} return { menu = setmetatable(menu, {__call = menu_call}), spawn = setmetatable(spawn, spawn.mt), button = setmetatable(button, button.mt), } -- }}}
gpl-2.0
dismantl/luci-0.12
applications/luci-radvd/luasrc/model/cbi/radvd/dnssl.lua
82
2276
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: rdnss.lua 6715 2011-01-13 20:03:40Z jow $ ]]-- local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - DNSSL"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "dnssl" then luci.http.redirect(m.redirect) return end s = m:section(NamedSection, sid, "interface", translate("DNSSL Configuration")) s.addremove = false -- -- General -- o = s:option(Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:option(Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:option(DynamicList, "suffix", translate("Suffix"), translate("Advertised Domain Suffixes")) o.optional = false o.rmempty = false o.datatype = "hostname" function o.cfgvalue(self, section) local l = { } local v = m.uci:get_list("radvd", section, "suffix") for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:option(Value, "AdvDNSSLLifetime", translate("Lifetime"), translate("Specifies the maximum duration how long the DNSSL entries are used for name resolution.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 1200 return m
apache-2.0
qq779089973/ramod
luci/applications/luci-radvd/luasrc/model/cbi/radvd/dnssl.lua
82
2276
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: rdnss.lua 6715 2011-01-13 20:03:40Z jow $ ]]-- local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - DNSSL"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "dnssl" then luci.http.redirect(m.redirect) return end s = m:section(NamedSection, sid, "interface", translate("DNSSL Configuration")) s.addremove = false -- -- General -- o = s:option(Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:option(Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:option(DynamicList, "suffix", translate("Suffix"), translate("Advertised Domain Suffixes")) o.optional = false o.rmempty = false o.datatype = "hostname" function o.cfgvalue(self, section) local l = { } local v = m.uci:get_list("radvd", section, "suffix") for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:option(Value, "AdvDNSSLLifetime", translate("Lifetime"), translate("Specifies the maximum duration how long the DNSSL entries are used for name resolution.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 1200 return m
mit
astrofra/amiga-experiments
amos-demo-python-remake/src/pkg.core/lua/wall.lua
2
5833
-- {"name":"Wall", "category":"Physic Structure", "editor":["@data/script_integration/register_as_component.py", "@data/script_integration/add_to_scene_create_menu.py"]} execution_context = gs.ScriptContextAll wall_x = 10 --> float wall_y = 10 --> float wall_z = 1 --> float smoothing_angle = 40.0 --> float nb_brick_x = 5 --> int nb_brick_y = 5 --> int material = nil --> RenderMaterial cube_x = 0 cube_y = 0 cube_z = 0 function GetMaterialPath() if material == nil then material = engine:GetRenderSystemAsync():LoadMaterial("@core/materials/default.mat") end return material:GetName() end function CreateRenderGeometry(uname, cube_x, cube_y, cube_z) local geo = gs.CoreGeometry() geo:SetName(uname) local d = gs.Vector3(cube_x, cube_y, cube_z) d = d * 0.5 geo:AllocateMaterialTable(1) geo:SetMaterial(0, GetMaterialPath(), true) -- generate vertices if geo:AllocateVertex(8) == 0 then return end geo:SetVertex(0, -d.x, d.y, d.z); geo:SetVertex(1, d.x, d.y, d.z); geo:SetVertex(2, d.x, d.y, -d.z); geo:SetVertex(3, -d.x, d.y, -d.z); geo:SetVertex(4, -d.x, -d.y, d.z); geo:SetVertex(5, d.x, -d.y, d.z); geo:SetVertex(6, d.x, -d.y, -d.z); geo:SetVertex(7, -d.x, -d.y, -d.z); -- build polygons if geo:AllocatePolygon(6) == 0 then return end for n = 0, 5 do geo:SetPolygon(n, 4, 0) end geo:AllocateRgb(6 * 4) geo:AllocateUVChannels(3, 6 * 4) if geo:AllocatePolygonBinding() == 0 then return end geo:SetPolygonBinding(0, {0, 1, 2, 3}) geo:SetPolygonBinding(1, {3, 2, 6, 7}) geo:SetPolygonBinding(2, {7, 6, 5, 4}) geo:SetPolygonBinding(3, {4, 5, 1, 0}) geo:SetPolygonBinding(4, {2, 1, 5, 6}) geo:SetPolygonBinding(5, {0, 3, 7, 4}) for c = 0, 5 do geo:SetRgb(c, {gs.Color.One, gs.Color.One, gs.Color.One, gs.Color.One}) end geo:SetUV(0, 0, {gs.Vector2(0.5, 0), gs.Vector2(0.5, 0.33), gs.Vector2(0.25, 0.33), gs.Vector2(0.25, 0)}) geo:SetUV(0, 1, {gs.Vector2(0, 0.33), gs.Vector2(0.25, 0.33), gs.Vector2(0.25, 0.66), gs.Vector2(0, 0.66)}) geo:SetUV(0, 2, {gs.Vector2(0.25, 1), gs.Vector2(0.25, 0.66), gs.Vector2(0.5, 0.66), gs.Vector2(0.5, 1)}) geo:SetUV(0, 3, {gs.Vector2(0.75, 0.66), gs.Vector2(0.5, 0.66), gs.Vector2(0.5, 0.33), gs.Vector2(0.75, 0.33)}) geo:SetUV(0, 4, {gs.Vector2(0.25, 0.33), gs.Vector2(0.5, 0.33), gs.Vector2(0.5, 0.66), gs.Vector2(0.25, 0.66)}) geo:SetUV(0, 5, {gs.Vector2(0.75, 0.33), gs.Vector2(1, 0.33), gs.Vector2(1, 0.66), gs.Vector2(0.75, 0.66)}) geo:SetUV(1, 0, {gs.Vector2(0.5, 0), gs.Vector2(0.5, 0.33), gs.Vector2(0.25, 0.33), gs.Vector2(0.25, 0)}) geo:SetUV(1, 1, {gs.Vector2(0, 0.33), gs.Vector2(0.25, 0.33), gs.Vector2(0.25, 0.66), gs.Vector2(0, 0.66)}) geo:SetUV(1, 2, {gs.Vector2(0.25, 1), gs.Vector2(0.25, 0.66), gs.Vector2(0.5, 0.66), gs.Vector2(0.5, 1)}) geo:SetUV(1, 3, {gs.Vector2(0.75, 0.66), gs.Vector2(0.5, 0.66), gs.Vector2(0.5, 0.33), gs.Vector2(0.75, 0.33)}) geo:SetUV(1, 4, {gs.Vector2(0.25, 0.33), gs.Vector2(0.5, 0.33), gs.Vector2(0.5, 0.66), gs.Vector2(0.25, 0.66)}) geo:SetUV(1, 5, {gs.Vector2(0.75, 0.33), gs.Vector2(1, 0.33), gs.Vector2(1, 0.66), gs.Vector2(0.75, 0.66)}) geo:SetUV(2, 0, {gs.Vector2(0.5, 0), gs.Vector2(0.5, 0.33), gs.Vector2(0.25, 0.33), gs.Vector2(0.25, 0)}) geo:SetUV(2, 1, {gs.Vector2(0, 0.33), gs.Vector2(0.25, 0.33), gs.Vector2(0.25, 0.66), gs.Vector2(0, 0.66)}) geo:SetUV(2, 2, {gs.Vector2(0.25, 1), gs.Vector2(0.25, 0.66), gs.Vector2(0.5, 0.66), gs.Vector2(0.5, 1)}) geo:SetUV(2, 3, {gs.Vector2(0.75, 0.66), gs.Vector2(0.5, 0.66), gs.Vector2(0.5, 0.33), gs.Vector2(0.75, 0.33)}) geo:SetUV(2, 4, {gs.Vector2(0.25, 0.33), gs.Vector2(0.5, 0.33), gs.Vector2(0.5, 0.66), gs.Vector2(0.25, 0.66)}) geo:SetUV(2, 5, {gs.Vector2(0.75, 0.33), gs.Vector2(1, 0.33), gs.Vector2(1, 0.66), gs.Vector2(0.75, 0.66)}) geo:ComputeVertexNormal(math.rad(smoothing_angle)) geo:ComputeVertexTangent() return engine:GetRenderSystemAsync():CreateGeometry(geo) end function GetUniqueName(cube_x, cube_y, cube_z) return string.format("@gen/brick_%.2f_%.2f_%.2f_%.2f_%s", cube_x, cube_y, cube_z, smoothing_angle, GetMaterialPath()) end node_list_wall = {} function Setup() Delete() local scene = this:GetScene() local cube_x = wall_x / nb_brick_x local cube_y = wall_y / nb_brick_y local cube_z = wall_z local render_system = engine:GetRenderSystemAsync() local uname = GetUniqueName(cube_x, cube_y, cube_z) local render_geo = render_system:HasGeometry(uname) if render_geo == nil then render_geo = CreateRenderGeometry(uname, cube_x, cube_y, cube_z) end -- create the wall using the render geo local count = 1 for h = 0, (nb_brick_y - 1) do for w = 0, (nb_brick_x - 1) do local node = gs.Node() node:SetInstantiatedBy(this) node:SetName("brick") local transform = gs.Transform() transform:SetPosition(gs.Vector3(w * cube_x, h* cube_y, 0)) transform:SetParent(this) node:AddComponent(transform) local object = gs.Object() object:SetGeometry(render_geo) node:AddComponent(object) node:AddComponent(gs.MakeRigidBody()) local box_collision = gs.MakeBoxCollision() box_collision:SetDimensions(gs.Vector3(cube_x, cube_y, cube_z)) node:AddComponent(box_collision) node:SetInstantiatedBy(this) scene:AddNode(node) node_list_wall[count] = node count = count+1 end end end function OnEditorSetParameter(name) if smoothing_angle < 0.0 then smoothing_angle = 0.0 end if smoothing_angle > 180.0 then smoothing_angle = 180.0 end Setup() -- simply regenerate the geometry on parameter change end function Delete() local scene = this:GetScene() for i = 1, #node_list_wall do scene:RemoveNode(node_list_wall[i]) end node_list_wall = {} end
mit
299299/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/declaration.lua
24
15117
-- tolua: declaration class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Modified by Yao Wei Tjong for Urho3D -- Declaration class -- Represents variable, function, or argument declaration. -- Stores the following fields: -- mod = type modifiers -- type = type -- ptr = "*" or "&", if representing a pointer or a reference -- name = name -- dim = dimension, if a vector -- def = default value, if any (only for arguments) -- ret = "*" or "&", if value is to be returned (only for arguments) classDeclaration = { mod = '', type = '', ptr = '', name = '', dim = '', ret = '', def = '' } classDeclaration.__index = classDeclaration setmetatable(classDeclaration,classFeature) -- Create an unique variable name function create_varname () if not _varnumber then _varnumber = 0 end _varnumber = _varnumber + 1 return "tolua_var_".._varnumber end -- Check declaration name -- It also identifies default values function classDeclaration:checkname () if strsub(self.name,1,1) == '[' and not findtype(self.type) then self.name = self.type..self.name local m = split(self.mod,'%s%s*') self.type = m[m.n] self.mod = concat(m,1,m.n-1) end local t = split(self.name,'=') if t.n==2 then self.name = t[1] self.def = find_enum_var(t[t.n]) end local b,e,d = strfind(self.name,"%[(.-)%]") if b then self.name = strsub(self.name,1,b-1) self.dim = find_enum_var(d) end if self.type ~= '' and self.type ~= 'void' and self.name == '' then self.name = create_varname() elseif self.kind=='var' then if self.type=='' and self.name~='' then self.type = self.type..self.name self.name = create_varname() elseif findtype(self.name) then if self.type=='' then self.type = self.name else self.type = self.type..' '..self.name end self.name = create_varname() end end -- adjust type of string if self.type == 'char' and self.dim ~= '' then self.type = 'char*' end if self.kind and self.kind == 'var' then self.name = string.gsub(self.name, ":.*$", "") -- ??? end end -- Check declaration type -- Substitutes typedef's. function classDeclaration:checktype () -- check if there is a pointer to basic type local basic = isbasic(self.type) if self.kind == 'func' and basic=='number' and string.find(self.ptr, "%*") then self.type = '_userdata' self.ptr = "" end if basic and self.ptr~='' then self.ret = self.ptr self.ptr = nil if isbasic(self.type) == 'number' then self.return_userdata = true end end -- check if there is array to be returned if self.dim~='' and self.ret~='' then error('#invalid parameter: cannot return an array of values') end -- restore 'void*' and 'string*' if self.type == '_userdata' then self.type = 'void*' elseif self.type == '_cstring' then self.type = 'char*' elseif self.type == '_lstate' then self.type = 'lua_State*' end -- resolve types inside the templates if self.type then self.type = resolve_template_types(self.type) end -- -- -- if returning value, automatically set default value -- if self.ret ~= '' and self.def == '' then -- self.def = '0' -- end -- end function resolve_template_types(type) if isbasic(type) then return type end local b,_,m = string.find(type, "(%b<>)") if b then m = split_c_tokens(string.sub(m, 2, -2), ",") for i=1, table.getn(m) do m[i] = string.gsub(m[i],"%s*([%*&])", "%1") if not isbasic(m[i]) then if not isenum(m[i]) then _, m[i] = applytypedef("", m[i]) end m[i] = findtype(m[i]) or m[i] m[i] = resolve_template_types(m[i]) end end local b,i type,b,i = break_template(type) --print("concat is ",concat(m, 1, m.n)) local template_part = "<"..concat(m, 1, m.n, ",")..">" type = rebuild_template(type, b, template_part) type = string.gsub(type, ">>", "> >") end return type end function break_template(s) local b,e,timpl = string.find(s, "(%b<>)") if timpl then s = string.gsub(s, "%b<>", "") return s, b, timpl else return s, 0, nil end end function rebuild_template(s, b, timpl) if b == 0 then return s end return string.sub(s, 1, b-1)..timpl..string.sub(s, b, -1) end -- Print method function classDeclaration:print (ident,close) print(ident.."Declaration{") print(ident.." mod = '"..self.mod.."',") print(ident.." type = '"..self.type.."',") print(ident.." ptr = '"..self.ptr.."',") print(ident.." name = '"..self.name.."',") print(ident.." dim = '"..self.dim.."',") print(ident.." def = '"..self.def.."',") print(ident.." ret = '"..self.ret.."',") print(ident.."}"..close) end -- check if array of values are returned to Lua function classDeclaration:requirecollection (t) if self.mod ~= 'const' and self.dim and self.dim ~= '' and not isbasic(self.type) and self.ptr == '' and self:check_public_access() then local type = gsub(self.type,"%s*const%s+","") t[type] = "tolua_collect_" .. clean_template(type) return true end return false end -- declare tag function classDeclaration:decltype () self.type = typevar(self.type) if strfind(self.mod,'const') then self.type = 'const '..self.type self.mod = gsub(self.mod,'const%s*','') end end -- output type checking function classDeclaration:outchecktype (narg) local def local t = isbasic(self.type) if self.def~='' then def = 1 else def = 0 end if self.dim ~= '' then --if t=='string' then -- return 'tolua_isstringarray(tolua_S,'..narg..','..def..',&tolua_err)' --else return '!tolua_istable(tolua_S,'..narg..',0,&tolua_err)' --end elseif t then return '!tolua_is'..t..'(tolua_S,'..narg..','..def..',&tolua_err)' else local is_func = get_is_function(self.type) if self.ptr == '&' or self.ptr == '' then return '(tolua_isvaluenil(tolua_S,'..narg..',&tolua_err) || !'..is_func..'(tolua_S,'..narg..',"'..self.type..'",'..def..',&tolua_err))' else return '!'..is_func..'(tolua_S,'..narg..',"'..self.type..'",'..def..',&tolua_err)' end end end function classDeclaration:builddeclaration (narg, cplusplus) local array = self.dim ~= '' and tonumber(self.dim)==nil local line = "" local ptr = '' local mod local type = self.type local nctype = gsub(self.type,'const%s+','') if self.dim ~= '' then type = gsub(self.type,'const%s+','') -- eliminates const modifier for arrays end if self.ptr~='' and not isbasic(type) then ptr = '*' end line = concatparam(line," ",self.mod,type,ptr) if array then line = concatparam(line,'*') end line = concatparam(line,self.name) if self.dim ~= '' then if tonumber(self.dim)~=nil then line = concatparam(line,'[',self.dim,'];') else if cplusplus then line = concatparam(line,' = Mtolua_new_dim(',type,ptr,', '..self.dim..');') else line = concatparam(line,' = (',type,ptr,'*)', 'malloc((',self.dim,')*sizeof(',type,ptr,'));') end end else local t = isbasic(type) line = concatparam(line,' = ') if t == 'state' then line = concatparam(line, 'tolua_S;') else --print("t is "..tostring(t)..", ptr is "..tostring(self.ptr)) if t == 'number' and string.find(self.ptr, "%*") then t = 'userdata' end if not t and ptr=='' then line = concatparam(line,'*') end line = concatparam(line,'((',self.mod,type) if not t then line = concatparam(line,'*') end line = concatparam(line,') ') if isenum(nctype) then line = concatparam(line,'(int) ') end local def = 0 if self.def ~= '' then def = self.def if (ptr == '' or self.ptr == '&') and not t then def = "(void*)&(const "..type..")"..def end end if t then line = concatparam(line,'tolua_to'..t,'(tolua_S,',narg,',',def,'));') else local to_func = get_to_function(type) line = concatparam(line,to_func..'(tolua_S,',narg,',',def,'));') end end end return line end -- Declare variable function classDeclaration:declare (narg) if self.dim ~= '' and tonumber(self.dim)==nil then output('#ifdef __cplusplus\n') output(self:builddeclaration(narg,true)) output('#else\n') output(self:builddeclaration(narg,false)) output('#endif\n') else output(self:builddeclaration(narg,false)) end end -- Get parameter value function classDeclaration:getarray (narg) if self.dim ~= '' then local type = gsub(self.type,'const ','') output(' {') output('#ifndef TOLUA_RELEASE\n') local def; if self.def~='' then def=1 else def=0 end local t = isbasic(type) if (t) then output(' if (!tolua_is'..t..'array(tolua_S,',narg,',',self.dim,',',def,',&tolua_err))') else output(' if (!tolua_isusertypearray(tolua_S,',narg,',"',type,'",',self.dim,',',def,',&tolua_err))') end output(' goto tolua_lerror;') output(' else\n') output('#endif\n') output(' {') output(' int i;') output(' for(i=0; i<'..self.dim..';i++)') local t = isbasic(type) local ptr = '' if self.ptr~='' then ptr = '*' end output(' ',self.name..'[i] = ') if not t and ptr=='' then output('*') end output('((',type) if not t then output('*') end output(') ') local def = 0 if self.def ~= '' then def = self.def end if t then output('tolua_tofield'..t..'(tolua_S,',narg,',i+1,',def,'));') else output('tolua_tofieldusertype(tolua_S,',narg,',i+1,',def,'));') end output(' }') output(' }') end end -- Get parameter value function classDeclaration:setarray (narg) if not strfind(self.type,'const%s+') and self.dim ~= '' then local type = gsub(self.type,'const ','') output(' {') output(' int i;') output(' for(i=0; i<'..self.dim..';i++)') local t,ct = isbasic(type) if t then output(' tolua_pushfield'..t..'(tolua_S,',narg,',i+1,(',ct,')',self.name,'[i]);') else if self.ptr == '' then output(' {') output('#ifdef __cplusplus\n') output(' void* tolua_obj = Mtolua_new((',type,')(',self.name,'[i]));') output(' tolua_pushfieldusertype_and_takeownership(tolua_S,',narg,',i+1,tolua_obj,"',type,'");') output('#else\n') output(' void* tolua_obj = tolua_copy(tolua_S,(void*)&',self.name,'[i],sizeof(',type,'));') output(' tolua_pushfieldusertype(tolua_S,',narg,',i+1,tolua_obj,"',type,'");') output('#endif\n') output(' }') else output(' tolua_pushfieldusertype(tolua_S,',narg,',i+1,(void*)',self.name,'[i],"',type,'");') end end output(' }') end end -- Free dynamically allocated array function classDeclaration:freearray () if self.dim ~= '' and tonumber(self.dim)==nil then output('#ifdef __cplusplus\n') output(' Mtolua_delete_dim(',self.name,');') output('#else\n') output(' free(',self.name,');') output('#endif\n') end end -- Pass parameter function classDeclaration:passpar () if self.ptr=='&' and not isbasic(self.type) then output('*'..self.name) elseif self.ret=='*' then output('&'..self.name) else output(self.name) end end -- Return parameter value function classDeclaration:retvalue () if self.ret ~= '' then local t,ct = isbasic(self.type) if t and t~='' then output(' tolua_push'..t..'(tolua_S,(',ct,')'..self.name..');') else local push_func = get_push_function(self.type) output(' ',push_func,'(tolua_S,(void*)'..self.name..',"',self.type,'");') end return 1 end return 0 end -- Internal constructor function _Declaration (t) setmetatable(t,classDeclaration) t:buildnames() t:checkname() t:checktype() local ft = findtype(t.type) or t.type if not isenum(ft) then t.mod, t.type = applytypedef(t.mod, ft) end if t.kind=="var" and (string.find(t.mod, "tolua_property%s") or string.find(t.mod, "tolua_property$")) then t.mod = string.gsub(t.mod, "tolua_property", "tolua_property__"..get_property_type()) end return t end -- Constructor -- Expects the string declaration. -- The kind of declaration can be "var" or "func". function Declaration (s,kind,is_parameter) -- eliminate spaces if default value is provided s = gsub(s,"%s*=%s*","=") s = gsub(s, "%s*<", "<") local defb,tmpdef defb,_,tmpdef = string.find(s, "(=.*)$") if defb then s = string.gsub(s, "=.*$", "") else tmpdef = '' end if kind == "var" then -- check the form: void if s == '' or s == 'void' then return _Declaration{type = 'void', kind = kind, is_parameter = is_parameter} end end -- check the form: mod type*& name local t = split_c_tokens(s,'%*%s*&') if t.n == 2 then if kind == 'func' then error("#invalid function return type: "..s) end --local m = split(t[1],'%s%s*') local m = split_c_tokens(t[1],'%s+') return _Declaration{ name = t[2]..tmpdef, ptr = '*', ret = '&', --type = rebuild_template(m[m.n], tb, timpl), type = m[m.n], mod = concat(m,1,m.n-1), is_parameter = is_parameter, kind = kind } end -- check the form: mod type** name t = split_c_tokens(s,'%*%s*%*') if t.n == 2 then if kind == 'func' then error("#invalid function return type: "..s) end --local m = split(t[1],'%s%s*') local m = split_c_tokens(t[1],'%s+') return _Declaration{ name = t[2]..tmpdef, ptr = '*', ret = '*', --type = rebuild_template(m[m.n], tb, timpl), type = m[m.n], mod = concat(m,1,m.n-1), is_parameter = is_parameter, kind = kind } end -- check the form: mod type& name t = split_c_tokens(s,'&') if t.n == 2 then --local m = split(t[1],'%s%s*') local m = split_c_tokens(t[1],'%s+') return _Declaration{ name = t[2]..tmpdef, ptr = '&', --type = rebuild_template(m[m.n], tb, timpl), type = m[m.n], mod = concat(m,1,m.n-1), is_parameter = is_parameter, kind = kind } end -- Urho3D: comply with stricter escape sequence -- check the form: mod type* name local s1 = gsub(s,"(%b\\[\\])",function (n) return gsub(n,'%*','\1') end) t = split_c_tokens(s1,'%*') if t.n == 2 then t[2] = gsub(t[2],'\1','%*') -- restore * in dimension expression --local m = split(t[1],'%s%s*') local m = split_c_tokens(t[1],'%s+') return _Declaration{ name = t[2]..tmpdef, ptr = '*', type = m[m.n], --type = rebuild_template(m[m.n], tb, timpl), mod = concat(m,1,m.n-1) , is_parameter = is_parameter, kind = kind } end if kind == 'var' then -- check the form: mod type name --t = split(s,'%s%s*') t = split_c_tokens(s,'%s+') local v if findtype(t[t.n]) then v = create_varname() else v = t[t.n]; t.n = t.n-1 end return _Declaration{ name = v..tmpdef, --type = rebuild_template(t[t.n], tb, timpl), type = t[t.n], mod = concat(t,1,t.n-1), is_parameter = is_parameter, kind = kind } else -- kind == "func" -- check the form: mod type name --t = split(s,'%s%s*') t = split_c_tokens(s,'%s+') local v = t[t.n] -- last word is the function name local tp,md if t.n>1 then tp = t[t.n-1] md = concat(t,1,t.n-2) end --if tp then tp = rebuild_template(tp, tb, timpl) end return _Declaration{ name = v, type = tp, mod = md, is_parameter = is_parameter, kind = kind } end end
mit
Godfather021/yag
plugins/rss.lua
700
5434
local function get_base_redis(id, option, extra) local ex = '' if option ~= nil then ex = ex .. ':' .. option if extra ~= nil then ex = ex .. ':' .. extra end end return 'rss:' .. id .. ex end local function prot_url(url) local url, h = string.gsub(url, "http://", "") local url, hs = string.gsub(url, "https://", "") local protocol = "http" if hs == 1 then protocol = "https" end return url, protocol end local function get_rss(url, prot) local res, code = nil, 0 if prot == "http" then res, code = http.request(url) elseif prot == "https" then res, code = https.request(url) end if code ~= 200 then return nil, "Error while doing the petition to " .. url end local parsed = feedparser.parse(res) if parsed == nil then return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?" end return parsed, nil end local function get_new_entries(last, nentries) local entries = {} for k,v in pairs(nentries) do if v.id == last then return entries else table.insert(entries, v) end end return entries end local function print_subs(id) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) local text = id .. ' are subscribed to:\n---------\n' for k,v in pairs(subs) do text = text .. k .. ") " .. v .. '\n' end return text end local function subscribe(id, url) local baseurl, protocol = prot_url(url) local prothash = get_base_redis(baseurl, "protocol") local lasthash = get_base_redis(baseurl, "last_entry") local lhash = get_base_redis(baseurl, "subs") local uhash = get_base_redis(id) if redis:sismember(uhash, baseurl) then return "You are already subscribed to " .. url end local parsed, err = get_rss(url, protocol) if err ~= nil then return err end local last_entry = "" if #parsed.entries > 0 then last_entry = parsed.entries[1].id end local name = parsed.feed.title redis:set(prothash, protocol) redis:set(lasthash, last_entry) redis:sadd(lhash, id) redis:sadd(uhash, baseurl) return "You had been subscribed to " .. name end local function unsubscribe(id, n) if #n > 3 then return "I don't think that you have that many subscriptions." end n = tonumber(n) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) if n < 1 or n > #subs then return "Subscription id out of range!" end local sub = subs[n] local lhash = get_base_redis(sub, "subs") redis:srem(uhash, sub) redis:srem(lhash, id) local left = redis:smembers(lhash) if #left < 1 then -- no one subscribed, remove it local prothash = get_base_redis(sub, "protocol") local lasthash = get_base_redis(sub, "last_entry") redis:del(prothash) redis:del(lasthash) end return "You had been unsubscribed from " .. sub end local function cron() -- sync every 15 mins? local keys = redis:keys(get_base_redis("*", "subs")) for k,v in pairs(keys) do local base = string.match(v, "rss:(.+):subs") -- Get the URL base local prot = redis:get(get_base_redis(base, "protocol")) local last = redis:get(get_base_redis(base, "last_entry")) local url = prot .. "://" .. base local parsed, err = get_rss(url, prot) if err ~= nil then return end local newentr = get_new_entries(last, parsed.entries) local subscribers = {} local text = '' -- Send only one message with all updates for k2, v2 in pairs(newentr) do local title = v2.title or 'No title' local link = v2.link or v2.id or 'No Link' text = text .. "[rss](" .. link .. ") - " .. title .. '\n' end if text ~= '' then local newlast = newentr[1].id redis:set(get_base_redis(base, "last_entry"), newlast) for k2, receiver in pairs(redis:smembers(v)) do send_msg(receiver, text, ok_cb, false) end end end end local function run(msg, matches) local id = "user#id" .. msg.from.id if is_chat_msg(msg) then id = "chat#id" .. msg.to.id end if matches[1] == "!rss"then return print_subs(id) end if matches[1] == "sync" then if not is_sudo(msg) then return "Only sudo users can sync the RSS." end cron() end if matches[1] == "subscribe" or matches[1] == "sub" then return subscribe(id, matches[2]) end if matches[1] == "unsubscribe" or matches[1] == "uns" then return unsubscribe(id, matches[2]) end end return { description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.", usage = { "!rss: Get your rss (or chat rss) subscriptions", "!rss subscribe (url): Subscribe to that url", "!rss unsubscribe (id): Unsubscribe of that id", "!rss sync: Download now the updates and send it. Only sudo users can use this option." }, patterns = { "^!rss$", "^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (unsubscribe) (%d+)$", "^!rss (uns) (%d+)$", "^!rss (sync)$" }, run = run, cron = cron }
gpl-2.0
RytoEX/obs-studio
UI/frontend-plugins/frontend-tools/data/scripts/instant-replay.lua
23
5385
obs = obslua source_name = "" hotkey_id = obs.OBS_INVALID_HOTKEY_ID attempts = 0 last_replay = "" ---------------------------------------------------------- function try_play() local replay_buffer = obs.obs_frontend_get_replay_buffer_output() if replay_buffer == nil then obs.remove_current_callback() return end -- Call the procedure of the replay buffer named "get_last_replay" to -- get the last replay created by the replay buffer local cd = obs.calldata_create() local ph = obs.obs_output_get_proc_handler(replay_buffer) obs.proc_handler_call(ph, "get_last_replay", cd) local path = obs.calldata_string(cd, "path") obs.calldata_destroy(cd) obs.obs_output_release(replay_buffer) if path == last_replay then path = nil end -- If the path is valid and the source exists, update it with the -- replay file to play back the replay. Otherwise, stop attempting to -- replay after 10 retries if path == nil then attempts = attempts + 1 if attempts >= 10 then obs.remove_current_callback() end else last_replay = path local source = obs.obs_get_source_by_name(source_name) if source ~= nil then local settings = obs.obs_data_create() source_id = obs.obs_source_get_id(source) if source_id == "ffmpeg_source" then obs.obs_data_set_string(settings, "local_file", path) obs.obs_data_set_bool(settings, "is_local_file", true) -- updating will automatically cause the source to -- refresh if the source is currently active obs.obs_source_update(source, settings) elseif source_id == "vlc_source" then -- "playlist" array = obs.obs_data_array_create() item = obs.obs_data_create() obs.obs_data_set_string(item, "value", path) obs.obs_data_array_push_back(array, item) obs.obs_data_set_array(settings, "playlist", array) -- updating will automatically cause the source to -- refresh if the source is currently active obs.obs_source_update(source, settings) obs.obs_data_release(item) obs.obs_data_array_release(array) end obs.obs_data_release(settings) obs.obs_source_release(source) end obs.remove_current_callback() end end -- The "Instant Replay" hotkey callback function instant_replay(pressed) if not pressed then return end local replay_buffer = obs.obs_frontend_get_replay_buffer_output() if replay_buffer ~= nil then -- Call the procedure of the replay buffer named "get_last_replay" to -- get the last replay created by the replay buffer local ph = obs.obs_output_get_proc_handler(replay_buffer) obs.proc_handler_call(ph, "save", nil) -- Set a 2-second timer to attempt playback every 1 second -- until the replay is available if obs.obs_output_active(replay_buffer) then attempts = 0 obs.timer_add(try_play, 2000) else obs.script_log(obs.LOG_WARNING, "Tried to save an instant replay, but the replay buffer is not active!") end obs.obs_output_release(replay_buffer) else obs.script_log(obs.LOG_WARNING, "Tried to save an instant replay, but found no active replay buffer!") end end ---------------------------------------------------------- -- A function named script_update will be called when settings are changed function script_update(settings) source_name = obs.obs_data_get_string(settings, "source") end -- A function named script_description returns the description shown to -- the user function script_description() return "When the \"Instant Replay\" hotkey is triggered, saves a replay with the replay buffer, and then plays it in a media source as soon as the replay is ready. Requires an active replay buffer.\n\nMade by Jim and Exeldro" end -- A function named script_properties defines the properties that the user -- can change for the entire script module itself function script_properties() props = obs.obs_properties_create() local p = obs.obs_properties_add_list(props, "source", "Media Source", obs.OBS_COMBO_TYPE_EDITABLE, obs.OBS_COMBO_FORMAT_STRING) local sources = obs.obs_enum_sources() if sources ~= nil then for _, source in ipairs(sources) do source_id = obs.obs_source_get_id(source) if source_id == "ffmpeg_source" then local name = obs.obs_source_get_name(source) obs.obs_property_list_add_string(p, name, name) elseif source_id == "vlc_source" then local name = obs.obs_source_get_name(source) obs.obs_property_list_add_string(p, name, name) else -- obs.script_log(obs.LOG_INFO, source_id) end end end obs.source_list_release(sources) return props end -- A function named script_load will be called on startup function script_load(settings) hotkey_id = obs.obs_hotkey_register_frontend("instant_replay.trigger", "Instant Replay", instant_replay) local hotkey_save_array = obs.obs_data_get_array(settings, "instant_replay.trigger") obs.obs_hotkey_load(hotkey_id, hotkey_save_array) obs.obs_data_array_release(hotkey_save_array) end -- A function named script_save will be called when the script is saved -- -- NOTE: This function is usually used for saving extra data (such as in this -- case, a hotkey's save data). Settings set via the properties are saved -- automatically. function script_save(settings) local hotkey_save_array = obs.obs_hotkey_save(hotkey_id) obs.obs_data_set_array(settings, "instant_replay.trigger", hotkey_save_array) obs.obs_data_array_release(hotkey_save_array) end
gpl-2.0
luiseduardohdbackup/WarriorQuest
WarriorQuest/runtime/mac/PrebuiltRuntimeLua.app/Contents/Resources/CCBReaderLoad.lua
79
5530
ccb = ccb or {} function CCBReaderLoad(strFilePath,proxy,owner) if nil == proxy then return nil end local ccbReader = proxy:createCCBReader() local node = ccbReader:load(strFilePath) local rootName = "" --owner set in readCCBFromFile is proxy if nil ~= owner then --Callbacks local ownerCallbackNames = ccbReader:getOwnerCallbackNames() local ownerCallbackNodes = ccbReader:getOwnerCallbackNodes() local ownerCallbackControlEvents = ccbReader:getOwnerCallbackControlEvents() local i = 1 for i = 1,table.getn(ownerCallbackNames) do local callbackName = ownerCallbackNames[i] local callbackNode = tolua.cast(ownerCallbackNodes[i],"cc.Node") if "function" == type(owner[callbackName]) then proxy:setCallback(callbackNode, owner[callbackName], ownerCallbackControlEvents[i]) else print("Warning: Cannot find owner's lua function:" .. ":" .. callbackName .. " for ownerVar selector") end end --Variables local ownerOutletNames = ccbReader:getOwnerOutletNames() local ownerOutletNodes = ccbReader:getOwnerOutletNodes() for i = 1, table.getn(ownerOutletNames) do local outletName = ownerOutletNames[i] local outletNode = tolua.cast(ownerOutletNodes[i],"cc.Node") owner[outletName] = outletNode end end local nodesWithAnimationManagers = ccbReader:getNodesWithAnimationManagers() local animationManagersForNodes = ccbReader:getAnimationManagersForNodes() for i = 1 , table.getn(nodesWithAnimationManagers) do local innerNode = tolua.cast(nodesWithAnimationManagers[i], "cc.Node") local animationManager = tolua.cast(animationManagersForNodes[i], "cc.CCBAnimationManager") local documentControllerName = animationManager:getDocumentControllerName() if "" == documentControllerName then end if nil ~= ccb[documentControllerName] then ccb[documentControllerName]["mAnimationManager"] = animationManager end --Callbacks local documentCallbackNames = animationManager:getDocumentCallbackNames() local documentCallbackNodes = animationManager:getDocumentCallbackNodes() local documentCallbackControlEvents = animationManager:getDocumentCallbackControlEvents() for i = 1,table.getn(documentCallbackNames) do local callbackName = documentCallbackNames[i] local callbackNode = tolua.cast(documentCallbackNodes[i],"cc.Node") if "" ~= documentControllerName and nil ~= ccb[documentControllerName] then if "function" == type(ccb[documentControllerName][callbackName]) then proxy:setCallback(callbackNode, ccb[documentControllerName][callbackName], documentCallbackControlEvents[i]) else print("Warning: Cannot found lua function [" .. documentControllerName .. ":" .. callbackName .. "] for docRoot selector") end end end --Variables local documentOutletNames = animationManager:getDocumentOutletNames() local documentOutletNodes = animationManager:getDocumentOutletNodes() for i = 1, table.getn(documentOutletNames) do local outletName = documentOutletNames[i] local outletNode = tolua.cast(documentOutletNodes[i],"cc.Node") if nil ~= ccb[documentControllerName] then ccb[documentControllerName][outletName] = tolua.cast(outletNode, proxy:getNodeTypeName(outletNode)) end end --[[ if (typeof(controller.onDidLoadFromCCB) == "function") controller.onDidLoadFromCCB(); ]]-- --Setup timeline callbacks local keyframeCallbacks = animationManager:getKeyframeCallbacks() for i = 1 , table.getn(keyframeCallbacks) do local callbackCombine = keyframeCallbacks[i] local beignIndex,endIndex = string.find(callbackCombine,":") local callbackType = tonumber(string.sub(callbackCombine,1,beignIndex - 1)) local callbackName = string.sub(callbackCombine,endIndex + 1, -1) --Document callback if 1 == callbackType and nil ~= ccb[documentControllerName] then local callfunc = cc.CallFunc:create(ccb[documentControllerName][callbackName]) animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine); elseif 2 == callbackType and nil ~= owner then --Owner callback local callfunc = cc.CallFunc:create(owner[callbackName])--need check animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine) end end --start animation local autoPlaySeqId = animationManager:getAutoPlaySequenceId() if -1 ~= autoPlaySeqId then animationManager:runAnimationsForSequenceIdTweenDuration(autoPlaySeqId, 0) end end return node end local function CCBuilderReaderLoad(strFilePath,proxy,owner) print("\n********** \n".."CCBuilderReaderLoad(strFilePath,proxy,owner)".." was deprecated please use ".. "CCBReaderLoad(strFilePath,proxy,owner)" .. " instead.\n**********") return CCBReaderLoad(strFilePath,proxy,owner) end rawset(_G,"CCBuilderReaderLoad",CCBuilderReaderLoad)
mit
nsf/nextgame
scripts/ng/wm.lua
1
5466
local M = {} require "ng.struct" local ngm = require "ng.math" local binding = require "ng.binding" local bit = require "bit" local ffi = require "ffi" local band, bor, lshift, rshift = bit.band, bit.bor, bit.lshift, bit.rshift ------------------------------------------------------------------------------ -- Color ------------------------------------------------------------------------------ local mt = {} mt.__index = mt function mt:__new(r, g, b) local r2 = math.floor(r * 31) local g2 = math.floor(g * 63) local b2 = math.floor(b * 31) return ffi.new(self, bor(bor(lshift(r2, 11), lshift(g2, 5)), b2)) end function mt:R() return rshift(self.color, 11) / 31.0 end function mt:G() return band(rshift(self.color, 5), 63) / 63.0 end function mt:B() return band(self.color, 31) / 31.0 end M.Color = ffi.metatype("RGB565", mt) mt.BLACK = M.Color(0.000, 0.000, 0.000) mt.GREY = M.Color(0.498, 0.498, 0.498) mt.WHITE = M.Color(1.000, 1.000, 1.000) mt.BOLD_WHITE = M.Color(1.000, 1.000, 1.000) mt.RED = M.Color(0.804, 0.000, 0.000) mt.BOLD_RED = M.Color(1.000, 0.000, 0.000) mt.GREEN = M.Color(0.000, 0.804, 0.000) mt.BOLD_GREEN = M.Color(0.000, 1.000, 0.000) mt.BLUE = M.Color(0.067, 0.235, 0.447) mt.BOLD_BLUE = M.Color(0.192, 0.439, 0.749) mt.YELLOW = M.Color(0.804, 0.804, 0.000) mt.BOLD_YELLOW = M.Color(1.000, 1.000, 0.000) mt.MAGENTA = M.Color(0.804, 0.000, 0.804) mt.BOLD_MAGENTA = M.Color(1.000, 0.000, 1.000) mt.CYAN = M.Color(0.000, 0.804, 0.804) mt.BOLD_CYAN = M.Color(0.000, 1.000, 1.000) ------------------------------------------------------------------------------ -- TermboxCell ------------------------------------------------------------------------------ mt = {} mt.__index = mt function mt:__new(rune, attr, bg_alpha, fg, bg) -- RUNE_MASK == (1U << 21) - 1 == 2097151 -- ATTR_MASK == ((1U << 5) - 1) << 21 == 65011712 -- ATTR_SHIFT == 21U == 21 -- BG_A_MASK = ((1U << 6) - 1) << 26 == 4227858432 -- BG_A_SHIFT == 26U == 26 return ffi.new(self, bor( band(rune, 2097151), band(lshift(attr, 21), 65011712), band(lshift(bg_alpha * 63, 26), 4227858432) ), fg.color, bg.color ) end function mt:Rune() return band(self.rune_attr, 2097151) end function mt:Attr() return rshift(band(self.rune_attr, 65011712), 21) end function mt:BG_A() return rshift(band(self.rune_attr, 4227858432), 26) / 63 end mt.BOLD = lshift(1, 0) mt.INVERT = lshift(1, 1) M.TermboxCell = ffi.metatype("TermboxCell", mt) ------------------------------------------------------------------------------ -- Termbox ------------------------------------------------------------------------------ local function MakeTermboxPartial(tb, a_min, a_max, b_min, b_max, offset) b_min, b_max = b_min + offset, b_max + offset local c_min, c_max = ngm.RectangleIntersection(a_min, a_max, b_min, b_max) return ffi.new("TermboxPartial", tb, c_min.x, c_min.y, c_max.x, c_max.y, offset.x, offset.y) end mt = {} mt.__index = mt binding.DefineMethods(mt, [[ Vec2i NG_Termbox_Size(Termbox *tb); void NG_Termbox_Clear(Termbox *tb, RGB565 fg, RGB565 bg, float bg_alpha); void NG_Termbox_SetCursor(Termbox *tb, const Vec2i &p); void NG_Termbox_SetCell(Termbox *tb, const Vec2i &p, const TermboxCell &cell); void NG_Termbox_SetImage(Termbox *tb, const Vec2i &p, const Vec2i &size, int id, const char *params); Vec2i NG_Termbox_CellSize(Termbox *tb); ]]) function mt:Partial(b_min, b_max) local size = self:Size() if not b_min then return ffi.new("TermboxPartial", self, 1, 1, size.x, size.y) else return MakeTermboxPartial(self, ngm.Vec2i(1, 1), size, b_min, b_max, ngm.Vec2i(0, 0)) end end M.Termbox = ffi.metatype("Termbox", mt) ------------------------------------------------------------------------------ -- TermboxPartial ------------------------------------------------------------------------------ mt = {} mt.__index = mt binding.DefineMethods(mt, [[ void NG_TermboxPartial_SetCell(TermboxPartial *tb, const Vec2i &p, const TermboxCell &cell); void NG_TermboxPartial_SetImage(TermboxPartial *tb, const Vec2i &p, const Vec2i &size, int id, const char *params); void NG_TermboxPartial_Fill(TermboxPartial *tb, const Vec2i &p, const Vec2i &size, const TermboxCell &cell); ]]) function mt:Intersection(b_min, b_max) return ngm.RectangleIntersection( ngm.Vec2i(self.min_x, self.min_y), ngm.Vec2i(self.max_x, self.max_y), b_min, b_max) end function mt:Partial(b_min, b_max) return MakeTermboxPartial( self.termbox, ngm.Vec2i(self.min_x, self.min_y), ngm.Vec2i(self.max_x, self.max_y), b_min, b_max, ngm.Vec2i(self.offset_x, self.offset_y)) end M.TermboxPartial = ffi.metatype("TermboxPartial", mt) ------------------------------------------------------------------------------ -- Window ------------------------------------------------------------------------------ M.WindowAlignment = { FLOATING = 0, NW = 1, NE = 2, SW = 3, SE = 4, } mt = {} mt.__index = mt binding.DefineMethods(mt, [[ Termbox *NG_Window_Termbox(Window *win); void NG_Window_SetDirtyPartial(Window *win); void NG_Window_SetResizable(Window *win, bool b); void NG_Window_SetAutoResize(Window *win, bool b); void NG_Window_Resize(Window *win, const Vec2i &size); Vec2i NG_Window_TermboxPosition(Window *win); ]]) M.Window = ffi.metatype("Window", mt) ------------------------------------------------------------------------------ return M
mit
soundsrc/premake-core
mobdebug.lua
14
68852
-- -- MobDebug -- Lua remote debugger -- Copyright 2011-15 Paul Kulchenko -- Based on RemDebug 1.0 Copyright Kepler Project 2005 -- -- use loaded modules or load explicitly on those systems that require that local require = require local io = io or require "io" local table = table or require "table" local string = string or require "string" local coroutine = coroutine or require "coroutine" local debug = require "debug" -- protect require "os" as it may fail on embedded systems without os module local os = os or (function(module) local ok, res = pcall(require, module) return ok and res or nil end)("os") local mobdebug = { _NAME = "mobdebug", _VERSION = "0.702", _COPYRIGHT = "Paul Kulchenko", _DESCRIPTION = "Mobile Remote Debugger for the Lua programming language", port = os and os.getenv and tonumber((os.getenv("MOBDEBUG_PORT"))) or 8172, checkcount = 200, yieldtimeout = 0.02, -- yield timeout (s) connecttimeout = 2, -- connect timeout (s) } local HOOKMASK = "lcr" local error = error local getfenv = getfenv local setfenv = setfenv local loadstring = loadstring or load -- "load" replaced "loadstring" in Lua 5.2 local pairs = pairs local setmetatable = setmetatable local tonumber = tonumber local unpack = table.unpack or unpack local rawget = rawget local gsub, sub, find = string.gsub, string.sub, string.find -- if strict.lua is used, then need to avoid referencing some global -- variables, as they can be undefined; -- use rawget to avoid complaints from strict.lua at run-time. -- it's safe to do the initialization here as all these variables -- should get defined values (if any) before the debugging starts. -- there is also global 'wx' variable, which is checked as part of -- the debug loop as 'wx' can be loaded at any time during debugging. local genv = _G or _ENV local jit = rawget(genv, "jit") local MOAICoroutine = rawget(genv, "MOAICoroutine") -- ngx_lua debugging requires a special handling as its coroutine.* -- methods use a different mechanism that doesn't allow resume calls -- from debug hook handlers. -- Instead, the "original" coroutine.* methods are used. -- `rawget` needs to be used to protect against `strict` checks, but -- ngx_lua hides those in a metatable, so need to use that. local metagindex = getmetatable(genv) and getmetatable(genv).__index local ngx = type(metagindex) == "table" and metagindex.rawget and metagindex:rawget("ngx") or nil local corocreate = ngx and coroutine._create or coroutine.create local cororesume = ngx and coroutine._resume or coroutine.resume local coroyield = ngx and coroutine._yield or coroutine.yield local corostatus = ngx and coroutine._status or coroutine.status local corowrap = coroutine.wrap if not setfenv then -- Lua 5.2+ -- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html -- this assumes f is a function local function findenv(f) local level = 1 repeat local name, value = debug.getupvalue(f, level) if name == '_ENV' then return level, value end level = level + 1 until name == nil return nil end getfenv = function (f) return(select(2, findenv(f)) or _G) end setfenv = function (f, t) local level = findenv(f) if level then debug.setupvalue(f, level, t) end return f end end -- check for OS and convert file names to lower case on windows -- (its file system is case insensitive, but case preserving), as setting a -- breakpoint on x:\Foo.lua will not work if the file was loaded as X:\foo.lua. -- OSX and Windows behave the same way (case insensitive, but case preserving). -- OSX can be configured to be case-sensitive, so check for that. This doesn't -- handle the case of different partitions having different case-sensitivity. local win = os and os.getenv and (os.getenv('WINDIR') or (os.getenv('OS') or ''):match('[Ww]indows')) and true or false local mac = not win and (os and os.getenv and os.getenv('DYLD_LIBRARY_PATH') or not io.open("/proc")) and true or false local iscasepreserving = win or (mac and io.open('/library') ~= nil) -- turn jit off based on Mike Pall's comment in this discussion: -- http://www.freelists.org/post/luajit/Debug-hooks-and-JIT,2 -- "You need to turn it off at the start if you plan to receive -- reliable hook calls at any later point in time." if jit and jit.off then jit.off() end local socket = require "socket" local coro_debugger local coro_debugee local coroutines = {}; setmetatable(coroutines, {__mode = "k"}) -- "weak" keys local events = { BREAK = 1, WATCH = 2, RESTART = 3, STACK = 4 } local breakpoints = {} local watches = {} local lastsource local lastfile local watchescnt = 0 local abort -- default value is nil; this is used in start/loop distinction local seen_hook = false local checkcount = 0 local step_into = false local step_over = false local step_level = 0 local stack_level = 0 local server local buf local outputs = {} local iobase = {print = print} local basedir = "" local deferror = "execution aborted at default debugee" local debugee = function () local a = 1 for _ = 1, 10 do a = a + 1 end error(deferror) end local function q(s) return string.gsub(s, '([%(%)%.%%%+%-%*%?%[%^%$%]])','%%%1') end local serpent = (function() ---- include Serpent module for serialization local n, v = "serpent", "0.30" -- (C) 2012-17 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local getmetatable = debug and debug.getmetatable or getmetatable local pairs = function(t) return next, t end -- avoid using __pairs in Lua 5.2+ local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(type(G[g]) == 'table' and G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local maxlen, metatostring = tonumber(opts.maxlength), opts.metatostring local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local numformat = opts.numformat or "%.17g" local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or numformat:format(s)) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..select(2, pcall(tostring, s))..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end -- protect from those cases where __tostring may fail if type(mt) == 'table' then local to, tr = pcall(function() return mt.__tostring(t) end) local so, sr = pcall(function() return mt.__serialize(t) end) if (opts.metatostring ~= false and to or so) then -- knows how to serialize itself seen[t] = insref or spath t = so and sr or tr ttype = type(t) end -- new value falls through to be serialized end if ttype == "table" then if level >= maxl then return tag..'{}'..comment('maxlvl', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty if maxlen and maxlen < 0 then return tag..'{}'..comment('maxlen', level) end local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.keyignore and opts.keyignore[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) if maxlen then maxlen = maxlen - #out[#out] if maxlen < 0 then break end end end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail,level) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath if opts.nocode then return tag.."function() --[[..skipped..]] end"..comment(t, level) end local ok, res = pcall(string.dump, t) local func = ok and "((loadstring or load)("..safestr(res)..",'@serialized'))"..comment(t, level) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end } end)() ---- end of Serpent module mobdebug.line = serpent.line mobdebug.dump = serpent.dump mobdebug.linemap = nil mobdebug.loadstring = loadstring local function removebasedir(path, basedir) if iscasepreserving then -- check if the lowercased path matches the basedir -- if so, return substring of the original path (to not lowercase it) return path:lower():find('^'..q(basedir:lower())) and path:sub(#basedir+1) or path else return string.gsub(path, '^'..q(basedir), '') end end local function stack(start) local function vars(f) local func = debug.getinfo(f, "f").func local i = 1 local locals = {} -- get locals while true do local name, value = debug.getlocal(f, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then locals[name] = {value, select(2,pcall(tostring,value))} end i = i + 1 end -- get varargs (these use negative indices) i = 1 while true do local name, value = debug.getlocal(f, -i) -- `not name` should be enough, but LuaJIT 2.0.0 incorrectly reports `(*temporary)` names here if not name or name ~= "(*vararg)" then break end locals[name:gsub("%)$"," "..i..")")] = {value, select(2,pcall(tostring,value))} i = i + 1 end -- get upvalues i = 1 local ups = {} while func do -- check for func as it may be nil for tail calls local name, value = debug.getupvalue(func, i) if not name then break end ups[name] = {value, select(2,pcall(tostring,value))} i = i + 1 end return locals, ups end local stack = {} local linemap = mobdebug.linemap for i = (start or 0), 100 do local source = debug.getinfo(i, "Snl") if not source then break end local src = source.source if src:find("@") == 1 then src = src:sub(2):gsub("\\", "/") if src:find("%./") == 1 then src = src:sub(3) end end table.insert(stack, { -- remove basedir from source {source.name, removebasedir(src, basedir), linemap and linemap(source.linedefined, source.source) or source.linedefined, linemap and linemap(source.currentline, source.source) or source.currentline, source.what, source.namewhat, source.short_src}, vars(i+1)}) if source.what == 'main' then break end end return stack end local function set_breakpoint(file, line) if file == '-' and lastfile then file = lastfile elseif iscasepreserving then file = string.lower(file) end if not breakpoints[line] then breakpoints[line] = {} end breakpoints[line][file] = true end local function remove_breakpoint(file, line) if file == '-' and lastfile then file = lastfile elseif file == '*' and line == 0 then breakpoints = {} elseif iscasepreserving then file = string.lower(file) end if breakpoints[line] then breakpoints[line][file] = nil end end local function has_breakpoint(file, line) return breakpoints[line] and breakpoints[line][iscasepreserving and string.lower(file) or file] end local function restore_vars(vars) if type(vars) ~= 'table' then return end -- locals need to be processed in the reverse order, starting from -- the inner block out, to make sure that the localized variables -- are correctly updated with only the closest variable with -- the same name being changed -- first loop find how many local variables there is, while -- the second loop processes them from i to 1 local i = 1 while true do local name = debug.getlocal(3, i) if not name then break end i = i + 1 end i = i - 1 local written_vars = {} while i > 0 do local name = debug.getlocal(3, i) if not written_vars[name] then if string.sub(name, 1, 1) ~= '(' then debug.setlocal(3, i, rawget(vars, name)) end written_vars[name] = true end i = i - 1 end i = 1 local func = debug.getinfo(3, "f").func while true do local name = debug.getupvalue(func, i) if not name then break end if not written_vars[name] then if string.sub(name, 1, 1) ~= '(' then debug.setupvalue(func, i, rawget(vars, name)) end written_vars[name] = true end i = i + 1 end end local function capture_vars(level, thread) level = (level or 0)+2 -- add two levels for this and debug calls local func = (thread and debug.getinfo(thread, level, "f") or debug.getinfo(level, "f") or {}).func if not func then return {} end local vars = {['...'] = {}} local i = 1 while true do local name, value = debug.getupvalue(func, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then vars[name] = value end i = i + 1 end i = 1 while true do local name, value if thread then name, value = debug.getlocal(thread, level, i) else name, value = debug.getlocal(level, i) end if not name then break end if string.sub(name, 1, 1) ~= '(' then vars[name] = value end i = i + 1 end -- get varargs (these use negative indices) i = 1 while true do local name, value if thread then name, value = debug.getlocal(thread, level, -i) else name, value = debug.getlocal(level, -i) end -- `not name` should be enough, but LuaJIT 2.0.0 incorrectly reports `(*temporary)` names here if not name or name ~= "(*vararg)" then break end vars['...'][i] = value i = i + 1 end -- returned 'vars' table plays a dual role: (1) it captures local values -- and upvalues to be restored later (in case they are modified in "eval"), -- and (2) it provides an environment for evaluated chunks. -- getfenv(func) is needed to provide proper environment for functions, -- including access to globals, but this causes vars[name] to fail in -- restore_vars on local variables or upvalues with `nil` values when -- 'strict' is in effect. To avoid this `rawget` is used in restore_vars. setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) }) return vars end local function stack_depth(start_depth) for i = start_depth, 0, -1 do if debug.getinfo(i, "l") then return i+1 end end return start_depth end local function is_safe(stack_level) -- the stack grows up: 0 is getinfo, 1 is is_safe, 2 is debug_hook, 3 is user function if stack_level == 3 then return true end for i = 3, stack_level do -- return if it is not safe to abort local info = debug.getinfo(i, "S") if not info then return true end if info.what == "C" then return false end end return true end local function in_debugger() local this = debug.getinfo(1, "S").source -- only need to check few frames as mobdebug frames should be close for i = 3, 7 do local info = debug.getinfo(i, "S") if not info then return false end if info.source == this then return true end end return false end local function is_pending(peer) -- if there is something already in the buffer, skip check if not buf and checkcount >= mobdebug.checkcount then peer:settimeout(0) -- non-blocking buf = peer:receive(1) peer:settimeout() -- back to blocking checkcount = 0 end return buf end local function readnext(peer, num) peer:settimeout(0) -- non-blocking local res, err, partial = peer:receive(num) peer:settimeout() -- back to blocking return res or partial or '', err end local function handle_breakpoint(peer) -- check if the buffer has the beginning of SETB/DELB command; -- this is to avoid reading the entire line for commands that -- don't need to be handled here. if not buf or not (buf:sub(1,1) == 'S' or buf:sub(1,1) == 'D') then return end -- check second character to avoid reading STEP or other S* and D* commands if #buf == 1 then buf = buf .. readnext(peer, 1) end if buf:sub(2,2) ~= 'E' then return end -- need to read few more characters buf = buf .. readnext(peer, 5-#buf) if buf ~= 'SETB ' and buf ~= 'DELB ' then return end local res, _, partial = peer:receive() -- get the rest of the line; blocking if not res then if partial then buf = buf .. partial end return end local _, _, cmd, file, line = (buf..res):find("^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if cmd == 'SETB' then set_breakpoint(file, tonumber(line)) elseif cmd == 'DELB' then remove_breakpoint(file, tonumber(line)) else -- this looks like a breakpoint command, but something went wrong; -- return here to let the "normal" processing to handle, -- although this is likely to not go well. return end buf = nil end local function normalize_path(file) local n repeat file, n = file:gsub("/+%.?/+","/") -- remove all `//` and `/./` references until n == 0 -- collapse all up-dir references: this will clobber UNC prefix (\\?\) -- and disk on Windows when there are too many up-dir references: `D:\foo\..\..\bar`; -- handle the case of multiple up-dir references: `foo/bar/baz/../../../more`; -- only remove one at a time as otherwise `../../` could be removed; repeat file, n = file:gsub("[^/]+/%.%./", "", 1) until n == 0 -- there may still be a leading up-dir reference left (as `/../` or `../`); remove it return (file:gsub("^(/?)%.%./", "%1")) end local function debug_hook(event, line) -- (1) LuaJIT needs special treatment. Because debug_hook is set for -- *all* coroutines, and not just the one being debugged as in regular Lua -- (http://lua-users.org/lists/lua-l/2011-06/msg00513.html), -- need to avoid debugging mobdebug's own code as LuaJIT doesn't -- always correctly generate call/return hook events (there are more -- calls than returns, which breaks stack depth calculation and -- 'step' and 'step over' commands stop working; possibly because -- 'tail return' events are not generated by LuaJIT). -- the next line checks if the debugger is run under LuaJIT and if -- one of debugger methods is present in the stack, it simply returns. if jit then -- when luajit is compiled with LUAJIT_ENABLE_LUA52COMPAT, -- coroutine.running() returns non-nil for the main thread. local coro, main = coroutine.running() if not coro or main then coro = 'main' end local disabled = coroutines[coro] == false or coroutines[coro] == nil and coro ~= (coro_debugee or 'main') if coro_debugee and disabled or not coro_debugee and (disabled or in_debugger()) then return end end -- (2) check if abort has been requested and it's safe to abort if abort and is_safe(stack_level) then error(abort) end -- (3) also check if this debug hook has not been visited for any reason. -- this check is needed to avoid stepping in too early -- (for example, when coroutine.resume() is executed inside start()). if not seen_hook and in_debugger() then return end if event == "call" then stack_level = stack_level + 1 elseif event == "return" or event == "tail return" then stack_level = stack_level - 1 elseif event == "line" then if mobdebug.linemap then local ok, mappedline = pcall(mobdebug.linemap, line, debug.getinfo(2, "S").source) if ok then line = mappedline end if not line then return end end -- may need to fall through because of the following: -- (1) step_into -- (2) step_over and stack_level <= step_level (need stack_level) -- (3) breakpoint; check for line first as it's known; then for file -- (4) socket call (only do every Xth check) -- (5) at least one watch is registered if not ( step_into or step_over or breakpoints[line] or watchescnt > 0 or is_pending(server) ) then checkcount = checkcount + 1; return end checkcount = mobdebug.checkcount -- force check on the next command -- this is needed to check if the stack got shorter or longer. -- unfortunately counting call/return calls is not reliable. -- the discrepancy may happen when "pcall(load, '')" call is made -- or when "error()" is called in a function. -- in either case there are more "call" than "return" events reported. -- this validation is done for every "line" event, but should be "cheap" -- as it checks for the stack to get shorter (or longer by one call). -- start from one level higher just in case we need to grow the stack. -- this may happen after coroutine.resume call to a function that doesn't -- have any other instructions to execute. it triggers three returns: -- "return, tail return, return", which needs to be accounted for. stack_level = stack_depth(stack_level+1) local caller = debug.getinfo(2, "S") -- grab the filename and fix it if needed local file = lastfile if (lastsource ~= caller.source) then file, lastsource = caller.source, caller.source -- technically, users can supply names that may not use '@', -- for example when they call loadstring('...', 'filename.lua'). -- Unfortunately, there is no reliable/quick way to figure out -- what is the filename and what is the source code. -- If the name doesn't start with `@`, assume it's a file name if it's all on one line. if find(file, "^@") or not find(file, "[\r\n]") then file = gsub(gsub(file, "^@", ""), "\\", "/") -- normalize paths that may include up-dir or same-dir references -- if the path starts from the up-dir or reference, -- prepend `basedir` to generate absolute path to keep breakpoints working. -- ignore qualified relative path (`D:../`) and UNC paths (`\\?\`) if find(file, "^%.%./") then file = basedir..file end if find(file, "/%.%.?/") then file = normalize_path(file) end -- need this conversion to be applied to relative and absolute -- file names as you may write "require 'Foo'" to -- load "foo.lua" (on a case insensitive file system) and breakpoints -- set on foo.lua will not work if not converted to the same case. if iscasepreserving then file = string.lower(file) end if find(file, "^%./") then file = sub(file, 3) else file = gsub(file, "^"..q(basedir), "") end -- some file systems allow newlines in file names; remove these. file = gsub(file, "\n", ' ') else file = mobdebug.line(file) end -- set to true if we got here; this only needs to be done once per -- session, so do it here to at least avoid setting it for every line. seen_hook = true lastfile = file end if is_pending(server) then handle_breakpoint(server) end local vars, status, res if (watchescnt > 0) then vars = capture_vars(1) for index, value in pairs(watches) do setfenv(value, vars) local ok, fired = pcall(value) if ok and fired then status, res = cororesume(coro_debugger, events.WATCH, vars, file, line, index) break -- any one watch is enough; don't check multiple times end end end -- need to get into the "regular" debug handler, but only if there was -- no watch that was fired. If there was a watch, handle its result. local getin = (status == nil) and (step_into -- when coroutine.running() return `nil` (main thread in Lua 5.1), -- step_over will equal 'main', so need to check for that explicitly. or (step_over and step_over == (coroutine.running() or 'main') and stack_level <= step_level) or has_breakpoint(file, line) or is_pending(server)) if getin then vars = vars or capture_vars(1) step_into = false step_over = false status, res = cororesume(coro_debugger, events.BREAK, vars, file, line) end -- handle 'stack' command that provides stack() information to the debugger while status and res == 'stack' do -- resume with the stack trace and variables if vars then restore_vars(vars) end -- restore vars so they are reflected in stack values status, res = cororesume(coro_debugger, events.STACK, stack(3), file, line) end -- need to recheck once more as resume after 'stack' command may -- return something else (for example, 'exit'), which needs to be handled if status and res and res ~= 'stack' then if not abort and res == "exit" then mobdebug.onexit(1, true); return end if not abort and res == "done" then mobdebug.done(); return end abort = res -- only abort if safe; if not, there is another (earlier) check inside -- debug_hook, which will abort execution at the first safe opportunity if is_safe(stack_level) then error(abort) end elseif not status and res then error(res, 2) -- report any other (internal) errors back to the application end if vars then restore_vars(vars) end -- last command requested Step Over/Out; store the current thread if step_over == true then step_over = coroutine.running() or 'main' end end end local function stringify_results(params, status, ...) if not status then return status, ... end -- on error report as it params = params or {} if params.nocode == nil then params.nocode = true end if params.comment == nil then params.comment = 1 end local t = {...} for i,v in pairs(t) do -- stringify each of the returned values local ok, res = pcall(mobdebug.line, v, params) t[i] = ok and res or ("%q"):format(res):gsub("\010","n"):gsub("\026","\\026") end -- stringify table with all returned values -- this is done to allow each returned value to be used (serialized or not) -- intependently and to preserve "original" comments return pcall(mobdebug.dump, t, {sparse = false}) end local function isrunning() return coro_debugger and (corostatus(coro_debugger) == 'suspended' or corostatus(coro_debugger) == 'running') end -- this is a function that removes all hooks and closes the socket to -- report back to the controller that the debugging is done. -- the script that called `done` can still continue. local function done() if not (isrunning() and server) then return end if not jit then for co, debugged in pairs(coroutines) do if debugged then debug.sethook(co) end end end debug.sethook() server:close() coro_debugger = nil -- to make sure isrunning() returns `false` seen_hook = nil -- to make sure that the next start() call works abort = nil -- to make sure that callback calls use proper "abort" value end local function debugger_loop(sev, svars, sfile, sline) local command local app, osname local eval_env = svars or {} local function emptyWatch () return false end local loaded = {} for k in pairs(package.loaded) do loaded[k] = true end while true do local line, err local wx = rawget(genv, "wx") -- use rawread to make strict.lua happy if (wx or mobdebug.yield) and server.settimeout then server:settimeout(mobdebug.yieldtimeout) end while true do line, err = server:receive() if not line and err == "timeout" then -- yield for wx GUI applications if possible to avoid "busyness" app = app or (wx and wx.wxGetApp and wx.wxGetApp()) if app then local win = app:GetTopWindow() local inloop = app:IsMainLoopRunning() osname = osname or wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName() if win and not inloop then -- process messages in a regular way -- and exit as soon as the event loop is idle if osname == 'Unix' then wx.wxTimer(app):Start(10, true) end local exitLoop = function() win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_IDLE) win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_TIMER) app:ExitMainLoop() end win:Connect(wx.wxEVT_IDLE, exitLoop) win:Connect(wx.wxEVT_TIMER, exitLoop) app:MainLoop() end elseif mobdebug.yield then mobdebug.yield() end elseif not line and err == "closed" then error("Debugger connection closed", 0) else -- if there is something in the pending buffer, prepend it to the line if buf then line = buf .. line; buf = nil end break end end if server.settimeout then server:settimeout() end -- back to blocking command = string.sub(line, string.find(line, "^[A-Z]+")) if command == "SETB" then local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if file and line then set_breakpoint(file, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "DELB" then local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if file and line then remove_breakpoint(file, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXEC" then -- extract any optional parameters local params = string.match(line, "--%s*(%b{})%s*$") local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$") if chunk then local func, res = mobdebug.loadstring(chunk) local status if func then local pfunc = params and loadstring("return "..params) -- use internal function params = pfunc and pfunc() params = (type(params) == "table" and params or {}) local stack = tonumber(params.stack) -- if the requested stack frame is not the current one, then use a new capture -- with a specific stack frame: `capture_vars(0, coro_debugee)` local env = stack and coro_debugee and capture_vars(stack-1, coro_debugee) or eval_env setfenv(func, env) status, res = stringify_results(params, pcall(func, unpack(env['...'] or {}))) end if status then if mobdebug.onscratch then mobdebug.onscratch(res) end server:send("200 OK " .. tostring(#res) .. "\n") server:send(res) else -- fix error if not set (for example, when loadstring is not present) if not res then res = "Unknown error" end server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "LOAD" then local _, _, size, name = string.find(line, "^[A-Z]+%s+(%d+)%s+(%S.-)%s*$") size = tonumber(size) if abort == nil then -- no LOAD/RELOAD allowed inside start() if size > 0 then server:receive(size) end if sfile and sline then server:send("201 Started " .. sfile .. " " .. tostring(sline) .. "\n") else server:send("200 OK 0\n") end else -- reset environment to allow required modules to load again -- remove those packages that weren't loaded when debugger started for k in pairs(package.loaded) do if not loaded[k] then package.loaded[k] = nil end end if size == 0 and name == '-' then -- RELOAD the current script being debugged server:send("200 OK 0\n") coroyield("load") else -- receiving 0 bytes blocks (at least in luasocket 2.0.2), so skip reading local chunk = size == 0 and "" or server:receive(size) if chunk then -- LOAD a new script for debugging local func, res = mobdebug.loadstring(chunk, "@"..name) if func then server:send("200 OK 0\n") debugee = func coroyield("load") else server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end end end elseif command == "SETW" then local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)%s*$") if exp then local func, res = mobdebug.loadstring("return(" .. exp .. ")") if func then watchescnt = watchescnt + 1 local newidx = #watches + 1 watches[newidx] = func server:send("200 OK " .. tostring(newidx) .. "\n") else server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "DELW" then local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)%s*$") index = tonumber(index) if index > 0 and index <= #watches then watchescnt = watchescnt - (watches[index] ~= emptyWatch and 1 or 0) watches[index] = emptyWatch server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "RUN" then server:send("200 OK\n") local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "STEP" then server:send("200 OK\n") step_into = true local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "OVER" or command == "OUT" then server:send("200 OK\n") step_over = true -- OVER and OUT are very similar except for -- the stack level value at which to stop if command == "OUT" then step_level = stack_level - 1 else step_level = stack_level end local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "BASEDIR" then local _, _, dir = string.find(line, "^[A-Z]+%s+(.+)%s*$") if dir then basedir = iscasepreserving and string.lower(dir) or dir -- reset cached source as it may change with basedir lastsource = nil server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "SUSPEND" then -- do nothing; it already fulfilled its role elseif command == "DONE" then coroyield("done") return -- done with all the debugging elseif command == "STACK" then -- first check if we can execute the stack command -- as it requires yielding back to debug_hook it cannot be executed -- if we have not seen the hook yet as happens after start(). -- in this case we simply return an empty result local vars, ev = {} if seen_hook then ev, vars = coroyield("stack") end if ev and ev ~= events.STACK then server:send("401 Error in Execution " .. tostring(#vars) .. "\n") server:send(vars) else local params = string.match(line, "--%s*(%b{})%s*$") local pfunc = params and loadstring("return "..params) -- use internal function params = pfunc and pfunc() params = (type(params) == "table" and params or {}) if params.nocode == nil then params.nocode = true end if params.sparse == nil then params.sparse = false end -- take into account additional levels for the stack frames and data management if tonumber(params.maxlevel) then params.maxlevel = tonumber(params.maxlevel)+4 end local ok, res = pcall(mobdebug.dump, vars, params) if ok then server:send("200 OK " .. tostring(res) .. "\n") else server:send("401 Error in Execution " .. tostring(#res) .. "\n") server:send(res) end end elseif command == "OUTPUT" then local _, _, stream, mode = string.find(line, "^[A-Z]+%s+(%w+)%s+([dcr])%s*$") if stream and mode and stream == "stdout" then -- assign "print" in the global environment local default = mode == 'd' genv.print = default and iobase.print or corowrap(function() -- wrapping into coroutine.wrap protects this function from -- being stepped through in the debugger. -- don't use vararg (...) as it adds a reference for its values, -- which may affect how they are garbage collected while true do local tbl = {coroutine.yield()} if mode == 'c' then iobase.print(unpack(tbl)) end for n = 1, #tbl do tbl[n] = select(2, pcall(mobdebug.line, tbl[n], {nocode = true, comment = false})) end local file = table.concat(tbl, "\t").."\n" server:send("204 Output " .. stream .. " " .. tostring(#file) .. "\n" .. file) end end) if not default then genv.print() end -- "fake" print to start printing loop server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXIT" then server:send("200 OK\n") coroyield("exit") else server:send("400 Bad Request\n") end end end local function output(stream, data) if server then return server:send("204 Output "..stream.." "..tostring(#data).."\n"..data) end end local function connect(controller_host, controller_port) local sock, err = socket.tcp() if not sock then return nil, err end if sock.settimeout then sock:settimeout(mobdebug.connecttimeout) end local res, err = sock:connect(controller_host, tostring(controller_port)) if sock.settimeout then sock:settimeout() end if not res then return nil, err end return sock end local lasthost, lastport -- Starts a debug session by connecting to a controller local function start(controller_host, controller_port) -- only one debugging session can be run (as there is only one debug hook) if isrunning() then return end lasthost = controller_host or lasthost lastport = controller_port or lastport controller_host = lasthost or "localhost" controller_port = lastport or mobdebug.port local err server, err = mobdebug.connect(controller_host, controller_port) if server then -- correct stack depth which already has some calls on it -- so it doesn't go into negative when those calls return -- as this breaks subsequence checks in stack_depth(). -- start from 16th frame, which is sufficiently large for this check. stack_level = stack_depth(16) -- provide our own traceback function to report errors remotely -- but only under Lua 5.1/LuaJIT as it's not called under Lua 5.2+ -- (http://lua-users.org/lists/lua-l/2016-05/msg00297.html) local function f() return function()end end if f() ~= f() then -- Lua 5.1 or LuaJIT local dtraceback = debug.traceback debug.traceback = function (...) if select('#', ...) >= 1 then local thr, err, lvl = ... if type(thr) ~= 'thread' then err, lvl = thr, err end local trace = dtraceback(err, (lvl or 1)+1) if genv.print == iobase.print then -- no remote redirect return trace else genv.print(trace) -- report the error remotely return -- don't report locally to avoid double reporting end end -- direct call to debug.traceback: return the original. -- debug.traceback(nil, level) doesn't work in Lua 5.1 -- (http://lua-users.org/lists/lua-l/2011-06/msg00574.html), so -- simply remove first frame from the stack trace local tb = dtraceback("", 2) -- skip debugger frames -- if the string is returned, then remove the first new line as it's not needed return type(tb) == "string" and tb:gsub("^\n","") or tb end end coro_debugger = corocreate(debugger_loop) debug.sethook(debug_hook, HOOKMASK) seen_hook = nil -- reset in case the last start() call was refused step_into = true -- start with step command return true else print(("Could not connect to %s:%s: %s") :format(controller_host, controller_port, err or "unknown error")) end end local function controller(controller_host, controller_port, scratchpad) -- only one debugging session can be run (as there is only one debug hook) if isrunning() then return end lasthost = controller_host or lasthost lastport = controller_port or lastport controller_host = lasthost or "localhost" controller_port = lastport or mobdebug.port local exitonerror = not scratchpad local err server, err = mobdebug.connect(controller_host, controller_port) if server then local function report(trace, err) local msg = err .. "\n" .. trace server:send("401 Error in Execution " .. tostring(#msg) .. "\n") server:send(msg) return err end seen_hook = true -- allow to accept all commands coro_debugger = corocreate(debugger_loop) while true do step_into = true -- start with step command abort = false -- reset abort flag from the previous loop if scratchpad then checkcount = mobdebug.checkcount end -- force suspend right away coro_debugee = corocreate(debugee) debug.sethook(coro_debugee, debug_hook, HOOKMASK) local status, err = cororesume(coro_debugee, unpack(arg or {})) -- was there an error or is the script done? -- 'abort' state is allowed here; ignore it if abort then if tostring(abort) == 'exit' then break end else if status then -- no errors if corostatus(coro_debugee) == "suspended" then -- the script called `coroutine.yield` in the "main" thread error("attempt to yield from the main thread", 3) end break -- normal execution is done elseif err and not string.find(tostring(err), deferror) then -- report the error back -- err is not necessarily a string, so convert to string to report report(debug.traceback(coro_debugee), tostring(err)) if exitonerror then break end -- check if the debugging is done (coro_debugger is nil) if not coro_debugger then break end -- resume once more to clear the response the debugger wants to send -- need to use capture_vars(0) to capture only two (default) level, -- as even though there is controller() call, because of the tail call, -- the caller may not exist for it; -- This is not entirely safe as the user may see the local -- variable from console, but they will be reset anyway. -- This functionality is used when scratchpad is paused to -- gain access to remote console to modify global variables. local status, err = cororesume(coro_debugger, events.RESTART, capture_vars(0)) if not status or status and err == "exit" then break end end end end else print(("Could not connect to %s:%s: %s") :format(controller_host, controller_port, err or "unknown error")) return false end return true end local function scratchpad(controller_host, controller_port) return controller(controller_host, controller_port, true) end local function loop(controller_host, controller_port) return controller(controller_host, controller_port, false) end local function on() if not (isrunning() and server) then return end -- main is set to true under Lua5.2 for the "main" chunk. -- Lua5.1 returns co as `nil` in that case. local co, main = coroutine.running() if main then co = nil end if co then coroutines[co] = true debug.sethook(co, debug_hook, HOOKMASK) else if jit then coroutines.main = true end debug.sethook(debug_hook, HOOKMASK) end end local function off() if not (isrunning() and server) then return end -- main is set to true under Lua5.2 for the "main" chunk. -- Lua5.1 returns co as `nil` in that case. local co, main = coroutine.running() if main then co = nil end -- don't remove coroutine hook under LuaJIT as there is only one (global) hook if co then coroutines[co] = false if not jit then debug.sethook(co) end else if jit then coroutines.main = false end if not jit then debug.sethook() end end -- check if there is any thread that is still being debugged under LuaJIT; -- if not, turn the debugging off if jit then local remove = true for _, debugged in pairs(coroutines) do if debugged then remove = false; break end end if remove then debug.sethook() end end end -- Handles server debugging commands local function handle(params, client, options) -- when `options.verbose` is not provided, use normal `print`; verbose output can be -- disabled (`options.verbose == false`) or redirected (`options.verbose == function()...end`) local verbose = not options or options.verbose ~= nil and options.verbose local print = verbose and (type(verbose) == "function" and verbose or print) or function() end local file, line, watch_idx local _, _, command = string.find(params, "^([a-z]+)") if command == "run" or command == "step" or command == "out" or command == "over" or command == "exit" then client:send(string.upper(command) .. "\n") client:receive() -- this should consume the first '200 OK' response while true do local done = true local breakpoint = client:receive() if not breakpoint then print("Program finished") return nil, nil, false end local _, _, status = string.find(breakpoint, "^(%d+)") if status == "200" then -- don't need to do anything elseif status == "202" then _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") if file and line then print("Paused at file " .. file .. " line " .. line) end elseif status == "203" then _, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+(.-)%s+(%d+)%s+(%d+)%s*$") if file and line and watch_idx then print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])") end elseif status == "204" then local _, _, stream, size = string.find(breakpoint, "^204 Output (%w+) (%d+)$") if stream and size then local size = tonumber(size) local msg = size > 0 and client:receive(size) or "" print(msg) if outputs[stream] then outputs[stream](msg) end -- this was just the output, so go back reading the response done = false end elseif status == "401" then local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$") if size then local msg = client:receive(tonumber(size)) print("Error in remote application: " .. msg) return nil, nil, msg end else print("Unknown error") return nil, nil, "Debugger error: unexpected response '" .. breakpoint .. "'" end if done then break end end elseif command == "done" then client:send(string.upper(command) .. "\n") -- no response is expected elseif command == "setb" or command == "asetb" then _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") if file and line then -- if this is a file name, and not a file source if not file:find('^".*"$') then file = string.gsub(file, "\\", "/") -- convert slash file = removebasedir(file, basedir) end client:send("SETB " .. file .. " " .. line .. "\n") if command == "asetb" or client:receive() == "200 OK" then set_breakpoint(file, line) else print("Error: breakpoint not inserted") end else print("Invalid command") end elseif command == "setw" then local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") if exp then client:send("SETW " .. exp .. "\n") local answer = client:receive() local _, _, watch_idx = string.find(answer, "^200 OK (%d+)%s*$") if watch_idx then watches[watch_idx] = exp print("Inserted watch exp no. " .. watch_idx) else local _, _, size = string.find(answer, "^401 Error in Expression (%d+)$") if size then local err = client:receive(tonumber(size)):gsub(".-:%d+:%s*","") print("Error: watch expression not set: " .. err) else print("Error: watch expression not set") end end else print("Invalid command") end elseif command == "delb" or command == "adelb" then _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") if file and line then -- if this is a file name, and not a file source if not file:find('^".*"$') then file = string.gsub(file, "\\", "/") -- convert slash file = removebasedir(file, basedir) end client:send("DELB " .. file .. " " .. line .. "\n") if command == "adelb" or client:receive() == "200 OK" then remove_breakpoint(file, line) else print("Error: breakpoint not removed") end else print("Invalid command") end elseif command == "delallb" then local file, line = "*", 0 client:send("DELB " .. file .. " " .. tostring(line) .. "\n") if client:receive() == "200 OK" then remove_breakpoint(file, line) else print("Error: all breakpoints not removed") end elseif command == "delw" then local _, _, index = string.find(params, "^[a-z]+%s+(%d+)%s*$") if index then client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression not removed") end else print("Invalid command") end elseif command == "delallw" then for index, exp in pairs(watches) do client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed") end end elseif command == "eval" or command == "exec" or command == "load" or command == "loadstring" or command == "reload" then local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") if exp or (command == "reload") then if command == "eval" or command == "exec" then exp = (exp:gsub("%-%-%[(=*)%[.-%]%1%]", "") -- remove comments :gsub("%-%-.-\n", " ") -- remove line comments :gsub("\n", " ")) -- convert new lines if command == "eval" then exp = "return " .. exp end client:send("EXEC " .. exp .. "\n") elseif command == "reload" then client:send("LOAD 0 -\n") elseif command == "loadstring" then local _, _, _, file, lines = string.find(exp, "^([\"'])(.-)%1%s(.+)") if not file then _, _, file, lines = string.find(exp, "^(%S+)%s(.+)") end client:send("LOAD " .. tostring(#lines) .. " " .. file .. "\n") client:send(lines) else local file = io.open(exp, "r") if not file and pcall(require, "winapi") then -- if file is not open and winapi is there, try with a short path; -- this may be needed for unicode paths on windows winapi.set_encoding(winapi.CP_UTF8) local shortp = winapi.short_path(exp) file = shortp and io.open(shortp, "r") end if not file then return nil, nil, "Cannot open file " .. exp end -- read the file and remove the shebang line as it causes a compilation error local lines = file:read("*all"):gsub("^#!.-\n", "\n") file:close() local file = string.gsub(exp, "\\", "/") -- convert slash file = removebasedir(file, basedir) client:send("LOAD " .. tostring(#lines) .. " " .. file .. "\n") if #lines > 0 then client:send(lines) end end while true do local params, err = client:receive() if not params then return nil, nil, "Debugger connection " .. (err or "error") end local done = true local _, _, status, len = string.find(params, "^(%d+).-%s+(%d+)%s*$") if status == "200" then len = tonumber(len) if len > 0 then local status, res local str = client:receive(len) -- handle serialized table with results local func, err = loadstring(str) if func then status, res = pcall(func) if not status then err = res elseif type(res) ~= "table" then err = "received "..type(res).." instead of expected 'table'" end end if err then print("Error in processing results: " .. err) return nil, nil, "Error in processing results: " .. err end print(unpack(res)) return res[1], res end elseif status == "201" then _, _, file, line = string.find(params, "^201 Started%s+(.-)%s+(%d+)%s*$") elseif status == "202" or params == "200 OK" then -- do nothing; this only happens when RE/LOAD command gets the response -- that was for the original command that was aborted elseif status == "204" then local _, _, stream, size = string.find(params, "^204 Output (%w+) (%d+)$") if stream and size then local size = tonumber(size) local msg = size > 0 and client:receive(size) or "" print(msg) if outputs[stream] then outputs[stream](msg) end -- this was just the output, so go back reading the response done = false end elseif status == "401" then len = tonumber(len) local res = client:receive(len) print("Error in expression: " .. res) return nil, nil, res else print("Unknown error") return nil, nil, "Debugger error: unexpected response after EXEC/LOAD '" .. params .. "'" end if done then break end end else print("Invalid command") end elseif command == "listb" then for l, v in pairs(breakpoints) do for f in pairs(v) do print(f .. ": " .. l) end end elseif command == "listw" then for i, v in pairs(watches) do print("Watch exp. " .. i .. ": " .. v) end elseif command == "suspend" then client:send("SUSPEND\n") elseif command == "stack" then local opts = string.match(params, "^[a-z]+%s+(.+)$") client:send("STACK" .. (opts and " "..opts or "") .."\n") local resp = client:receive() local _, _, status, res = string.find(resp, "^(%d+)%s+%w+%s+(.+)%s*$") if status == "200" then local func, err = loadstring(res) if func == nil then print("Error in stack information: " .. err) return nil, nil, err end local ok, stack = pcall(func) if not ok then print("Error in stack information: " .. stack) return nil, nil, stack end for _,frame in ipairs(stack) do print(mobdebug.line(frame[1], {comment = false})) end return stack elseif status == "401" then local _, _, len = string.find(resp, "%s+(%d+)%s*$") len = tonumber(len) local res = len > 0 and client:receive(len) or "Invalid stack information." print("Error in expression: " .. res) return nil, nil, res else print("Unknown error") return nil, nil, "Debugger error: unexpected response after STACK" end elseif command == "output" then local _, _, stream, mode = string.find(params, "^[a-z]+%s+(%w+)%s+([dcr])%s*$") if stream and mode then client:send("OUTPUT "..stream.." "..mode.."\n") local resp, err = client:receive() if not resp then print("Unknown error: "..err) return nil, nil, "Debugger connection error: "..err end local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") if status == "200" then print("Stream "..stream.." redirected") outputs[stream] = type(options) == 'table' and options.handler or nil -- the client knows when she is doing, so install the handler elseif type(options) == 'table' and options.handler then outputs[stream] = options.handler else print("Unknown error") return nil, nil, "Debugger error: can't redirect "..stream end else print("Invalid command") end elseif command == "basedir" then local _, _, dir = string.find(params, "^[a-z]+%s+(.+)$") if dir then dir = string.gsub(dir, "\\", "/") -- convert slash if not string.find(dir, "/$") then dir = dir .. "/" end local remdir = dir:match("\t(.+)") if remdir then dir = dir:gsub("/?\t.+", "/") end basedir = dir client:send("BASEDIR "..(remdir or dir).."\n") local resp, err = client:receive() if not resp then print("Unknown error: "..err) return nil, nil, "Debugger connection error: "..err end local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") if status == "200" then print("New base directory is " .. basedir) else print("Unknown error") return nil, nil, "Debugger error: unexpected response after BASEDIR" end else print(basedir) end elseif command == "help" then print("setb <file> <line> -- sets a breakpoint") print("delb <file> <line> -- removes a breakpoint") print("delallb -- removes all breakpoints") print("setw <exp> -- adds a new watch expression") print("delw <index> -- removes the watch expression at index") print("delallw -- removes all watch expressions") print("run -- runs until next breakpoint") print("step -- runs until next line, stepping into function calls") print("over -- runs until next line, stepping over function calls") print("out -- runs until line after returning from current function") print("listb -- lists breakpoints") print("listw -- lists watch expressions") print("eval <exp> -- evaluates expression on the current context and returns its value") print("exec <stmt> -- executes statement on the current context") print("load <file> -- loads a local file for debugging") print("reload -- restarts the current debugging session") print("stack -- reports stack trace") print("output stdout <d|c|r> -- capture and redirect io stream (default|copy|redirect)") print("basedir [<path>] -- sets the base path of the remote application, or shows the current one") print("done -- stops the debugger and continues application execution") print("exit -- exits debugger and the application") else local _, _, spaces = string.find(params, "^(%s*)$") if spaces then return nil, nil, "Empty command" else print("Invalid command") return nil, nil, "Invalid command" end end return file, line end -- Starts debugging server local function listen(host, port) host = host or "*" port = port or mobdebug.port local socket = require "socket" print("Lua Remote Debugger") print("Run the program you wish to debug") local server = socket.bind(host, port) local client = server:accept() client:send("STEP\n") client:receive() local breakpoint = client:receive() local _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") if file and line then print("Paused at file " .. file ) print("Type 'help' for commands") else local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)%s*$") if size then print("Error in remote application: ") print(client:receive(size)) end end while true do io.write("> ") local file, line, err = handle(io.read("*line"), client) if not file and err == false then break end -- completed debugging end client:close() end local cocreate local function coro() if cocreate then return end -- only set once cocreate = cocreate or coroutine.create coroutine.create = function(f, ...) return cocreate(function(...) mobdebug.on() return f(...) end, ...) end end local moconew local function moai() if moconew then return end -- only set once moconew = moconew or (MOAICoroutine and MOAICoroutine.new) if not moconew then return end MOAICoroutine.new = function(...) local thread = moconew(...) -- need to support both thread.run and getmetatable(thread).run, which -- was used in earlier MOAI versions local mt = thread.run and thread or getmetatable(thread) local patched = mt.run mt.run = function(self, f, ...) return patched(self, function(...) mobdebug.on() return f(...) end, ...) end return thread end end -- make public functions available mobdebug.setbreakpoint = set_breakpoint mobdebug.removebreakpoint = remove_breakpoint mobdebug.listen = listen mobdebug.loop = loop mobdebug.scratchpad = scratchpad mobdebug.handle = handle mobdebug.connect = connect mobdebug.start = start mobdebug.on = on mobdebug.off = off mobdebug.moai = moai mobdebug.coro = coro mobdebug.done = done mobdebug.pause = function() step_into = true end mobdebug.yield = nil -- callback mobdebug.output = output mobdebug.onexit = os and os.exit or done mobdebug.onscratch = nil -- callback mobdebug.basedir = function(b) if b then basedir = b end return basedir end return mobdebug
bsd-3-clause
radare/radare
api/lua/radare/api.lua
5
16275
-- -- radare lua api -- -- 2008 pancake <youterm.com> -- ========== -- -- -- -- Namespaces -- -- -- -- ========== -- Radare = {} Radare.Analyze = {} Radare.Print = {} Radare.Search = {} Radare.Config = {} Radare.Code = {} Radare.Hash = {} Radare.Debugger = {} Radare.Write = {} Radare.Utils = {} -- ================= -- -- -- -- Namespace aliases -- -- -- -- ================= -- r = Radare a = Radare.Analyze p = Radare.Print cfg = Radare.Config code = Radare.Code hash = Radare.Hash s = Radare.Search d = Radare.Debugger w = Radare.Write u = Radare.Utils -- ================ -- -- -- -- Helper functions -- -- -- -- ================ -- function help(table) if table == nil then print "Use help(Radare), help(Radare.Debugger) or help(Radare.Print)" print "These namespaces has been aliased as 'r', 'd' and 'p'." else for key,val in pairs(table) do print(" "..key) end end return 0 end function list(table) local i i = 0 if table == nil then print "List the contents of a table" else --for key,val in pairs(table) do print(" "..key) end for k,v in pairs(table) do if v == nil then print(" "..k) -- XXX crash else print(" "..k..": "..v) -- k('?') end i = i + 1 end end return n end -- join strings from a table function join(delimiter, list) local len = getn(list) if len == 0 then return "" end local string = list[1] for i = 2, len do string = string .. delimiter .. list[i] end return string end -- split a string by a separator function split(text, sep) sep = sep or "\n" text = chomp(text) local lines = {} local pos = 1 while true do local b,e = text:find(sep, pos) if not b then table.insert(lines, text:sub(pos)) break end table.insert(lines, text:sub(pos,b-1)) pos = e + 1 end return lines end function chomp(text) if text == nil then return "" end return string.gsub(text, "\n$", "") end function chop(text) if text == nil then return "" end text = string.gsub(text, "\ *$", "") return string.gsub(text, "^\ *", "") end function hexpairs(buf) for byte=1, #buf, 16 do local chunk = buf:sub(byte, byte+15) io.write(string.format('%08X ',byte-1)) chunk:gsub('.', function (c) io.write(string.format('%02X ',string.byte(c))) end) io.write(string.rep(' ',3*(16-#chunk))) io.write(' ',chunk:gsub('%c','.'),"\n") end end function hexdump(buf) for i=1,math.ceil(#buf/16) * 16 do if (i-1) % 16 == 0 then io.write(string.format('%08X ', i-1)) end io.write( i > #buf and ' ' or string.format('%02X ', buf:byte(i)) ) if i % 8 == 0 then io.write(' ') end if i % 16 == 0 then io.write( buf:sub(i-16+1, i):gsub('%c','.'), '\n' ) end end end -- ==================== -- -- -- -- Radare API functions -- -- -- -- ==================== -- function Radare.get(value) -- | cut -d ' ' -f 1"); foo = split( string.gsub( cmd_str("? "..value),'(0x[^ ])', function(x)return x end),';') return tonumber(foo[1]) end Radare.bytes_help = 'Radare.bytes(addr)\tReturn hexpair string with block_size bytes at [addr]' function Radare.bytes(addr) local res = split(Radare.cmd("pX @"..addr), " ") -- TODO return res; end Radare.cmd_help = 'Radare.cmd(command)\tExecutes a radare command and returns its output' function Radare.cmd(cmd) return chomp(cmd_str(cmd)) end Radare.system_help = 'Radare.system(command)\tExecute an IO system command' function Radare.system(command) r.cmd("!!"..command) -- todo handle errors here return 0 end Radare.iosystem_help = 'Radare.iosystem(command)\tExecute an IO system command' function Radare.iosystem(command) r.cmd("!"..command) -- todo handle errors here return 0 end function Radare.open(filename) r.cmd("o "..filename) -- todo handle errors here return 0 end function Radare.attach(pid) return r.cmd("o pid://"..pid) end function Radare.debug(filename) return r.cmd("o dbg://"..filename) end function Radare.seek(offset) r.cmd("s "..offset) return 0 end function Radare.undo_seek() r.cmd("u") -- todo handle errors here return 0 end function Radare.redo_seek() r.cmd("uu") -- todo handle errors here return 0 end function Radare.resize(newsize) r.cmd("r "..newsize) -- todo handle errors here return 0 end function Radare.fortune() return r.cmd("fortune") end function Radare.interpret(file) -- control block size r.cmd(". "..file) return 0 end function Radare.copy(size,address) -- control block size if address == nil then r.cmd("y "..size) else r.cmd("y "..size.." @ "..address) end return 0 end function Radare.paste(address) -- control block size if address == nil then r.cmd("yy ") else r.cmd("yy @ "..address) end r.cmd("y "..offset) return 0 end function Radare.endian(big) r.cmd("eval cfg.bigendian = "..big) return 0 end function Radare.flag(name, address) -- rename to r.set() ? if address == nil then r.cmd("f "..name) else r.cmd("f "..name.." @ "..address) end return 0 end function Radare.flag_get(name) -- rename to r.get() ? local foo = str.split(r.cmd("? "..name), " ") return foo[1] end function Radare.flag_remove(name) -- rename to r.remove() ? r.cmd("f -"..name) return 0 end function Radare.flag_rename(oldname, newname) r.cmd("fr "..oldname.." "..newname) return 0 end function Radare.flag_list(filter) local list = split(r.cmd("f")) local ret = {} local i = 1 while list[i] ~= nil do local foo = split(list[i], " ") ret[i] = foo[4] i = i + 1 end return ret end function Radare.eval(key, value) if value == nil then return r.cmd("eval "..key) end return r.cmd("eval "..key.." = "..value) end function Radare.cmp(value, address) if address == nil then r.cmd("c "..value) else r.cmd("c "..value.." @ "..address) end -- parse output and get ret value return 0 end function Radare.cmp_file(file, address) if address == nil then r.cmd("cf "..file) else r.cmd("cf "..file.." @ "..address) end -- parse output and get ret value return 0 end function Radare.quit() r.cmd("q"); return 0 end function Radare.exit() return r.quit() end -- Radare.Analyze function Radare.Analyze.opcode(addr) if addr == nil then addr = "" else addr= "@ "..addr end local res = split(Radare.cmd("ao "..addr),"\n") local ret = {} for i = 1, #res do local line = split(res[i], "=") ret[chop(line[1])] = chop(line[2]) end return ret; end function Radare.Analyze.block(addr) if addr == nil then addr = "" else addr= "@ "..addr end local res = split(Radare.cmd("ab "..addr),"\n") local ret = {} for i = 1, #res do local line = split(res[i], "=") ret[chop(line[1])] = chop(line[2]) end return ret; end -- Radare.Debugger API function Radare.Debugger.step(times) r.cmd("!step "..times); return Radare.Debugger end function Radare.Debugger.attach(pid) r.cmd("!attach "..pid); return Radare.Debugger end function Radare.Debugger.detach(pid) r.cmd("!detach") return Radare.Debugger end function Radare.Debugger.jmp(address) r.cmd("!jmp "..address) return Radare.Debugger end function Radare.Debugger.set(register, value) r.cmd("!set "..register.." "..value) return Radare.Debugger end function Radare.Debugger.call(address) r.cmd("!call "..address) return Radare.Debugger end function Radare.Debugger.dump(name) r.cmd("!dump "..name) return Radare.Debugger end function Radare.Debugger.restore(name) r.cmd("!restore "..name) return Radare.Debugger end function Radare.Debugger.bp(address) r.cmd("!bp "..address) return Radare.Debugger end -- print stuff function Radare.Print.hex(size, address) if size == nil then size = "" end if address == nil then return r.cmd(":pX "..size) else return r.cmd(":pX "..size.." @ "..address) end end function Radare.Print.dis(nops, address) if nops == nil then nops = "" end if address == nil then return r.cmd("pd "..nops) else return r.cmd("pd "..nops.." @ "..address) end end function Radare.Print.disasm(size, address) if size == nil then size = "" end if address == nil then return r.cmd("pD "..size) else return r.cmd("pD "..size.." @ "..address) end end function Radare.Print.bin(size, address) -- size has no sense here if size == nil then size = "" end if address == nil then return r.cmd(":pb "..size) else return r.cmd(":pb "..size.." @ "..address) end end function Radare.Print.string(address) -- size has no sense here if address == nil then return r.cmd("pz ") else return r.cmd("pz @ "..address) end end function Radare.Print.oct(size,address) -- size has no sense here if size == nil then size = "" end if address == nil then return r.cmd(":po "..size) end return r.cmd(":po "..size.."@ "..address) end -- search stuff function Radare.Search.parse(string) local res = split(string,"\n") local ret = {} for i = 1, #res do local line = split(res[i], " ") ret[i] = line[3] end return ret; end function Radare.Search.string(string) return Radare.Search.parse(Radare.cmd("/ "..string)) end function Radare.Search.hex(string) return Radare.Search.parse(Radare.cmd("/x "..string)) end function Radare.Search.replace(hex_search, hex_write, delta) if delta == nil then Radare.Config.set("cmd.hit","wx "..hex_write) else Radare.Config.set("cmd.hit","wx "..hex_write.." @ +"..delta) end return Radare.Search.parse(Radare.cmd("/x "..hex_search)) end -- write stuff function Radare.Write.hex(string, address) if address == nil then return r.cmd("wx "..string) else return r.cmd("wx "..string.." @ "..address) end end function Radare.Write.string(string, address) if address == nil then return r.cmd("w ", string) else return r.cmd("w "..string.." @ "..address) end end function Radare.Write.wide_string(string, address) if address == nil then return r.cmd("ws "..string) else return r.cmd("ws "..string.." @ "..address) end end function Radare.asm(string) return r.cmd("!rasm '".. string.."'") end function Radare.Write.asm(string, address) if address == nil then return r.cmd("wa ".. string) else return r.cmd("wa "..string.." @ "..address) end end function Radare.Write.rscasm(string, address) if address == nil then return r.cmd("wA "..string) else return r.cmd("wA "..string.." @ "..address) end end function Radare.Write.from_file(filename, address) if address == nil then return r.cmd("wf "..filename) else return r.cmd("wf "..filename.." @ "..address) end end -- config stuff -- eval like function Radare.Config.verbose(level) Radare.Config.set("asm.syntax","intel") Radare.Config.set("asm.lines","false") Radare.Config.set("asm.offset","false") Radare.Config.set("asm.bytes","false") Radare.Config.set("asm.flags","false") Radare.Config.set("asm.split","false") Radare.Config.set("scr.color","false") Radare.Config.set("asm.comments","false") if level >= 1 then Radare.Config.set("asm.size", "true") end if level >= 2 then Radare.Config.set("asm.offset", "true") end if level >= 3 then Radare.Config.set("asm.lines", "true") Radare.Config.set("asm.bytes", "true") Radare.Config.set("asm.split", "true") Radare.Config.set("asm.flags", "true") Radare.Config.set("scr.color", "true") Radare.Config.set("asm.comments","true") end end -- TODO: store/restore eval config local Radare_Config_storage = {} function Radare.Config.store() local lines = split(r.cmd("e"),"\n") for i = 1, #lines do local a = split(lines[i],"=") if a[1] ~= nil then if a[2] == nil then a[2]="" end if (string.match(a[1], "file") ~= nil) then -- ignore else -- TODO. should store everything! (but no reopen :O) if (string.match(a[1], "asm") ~= nil) or (string.match(a[1], "scr") ~= nil) then Radare_Config_storage[a[1]] = a[2] Radare_Config_storage[a[1]] = a[2] end end end end end function Radare.Config.restore() for a,b in pairs(Radare_Config_storage) do Radare.Config.set(a,b) -- print (a.." = "..b) end end function Radare.Config.set(key, val) r.cmd("eval "..key.."="..val) return val end function Radare.Config.color(value) r.cmd("eval scr.color ="..value) return value end function Radare.Config.get(key) return r.cmd("eval "..key) end function Radare.Config.limit(sizs) return r.cmd("eval cfg.limit = "..size) end -- crypto stuff function Radare.Hash.md5(size, address) if size == nil then size = "" end if address == nil then return r.cmd("#md5 "..size) end return r.cmd("#md5 "..size.."@"..address) end function Radare.Hash.crc32(size, address) if size == nil then size = "" end if address == nil then return r.cmd("#crc32 "..size) end return r.cmd("#crc32 "..size.."@"..address) end function Radare.Hash.md4(size, address) if size == nil then size = "" end if address == nil then return r.cmd("#md4 "..size) end return r.cmd("#md4 "..size.."@"..address) end function Radare.Hash.sha1(size, address) if size == nil then size = "" end if address == nil then return r.cmd("#sha1 "..size) end return r.cmd("#sha1 "..size.."@"..address) end function Radare.Hash.sha256(size, address) if size == nil then size = "" end if address == nil then return r.cmd("#sha256 "..size) end return r.cmd("#sha256 "..size.."@"..address) end function Radare.Hash.sha384(size, address) if size == nil then size = "" end if address == nil then return r.cmd("#sha384 "..size) end return r.cmd("#sha384 "..size.."@"..address) end function Radare.Hash.sha512(size, address) if size == nil then size = "" end if address == nil then return r.cmd("#sha512 "..size) end return r.cmd("#sha512 "..size.."@"..address) end function Radare.Hash.hash(algo, size, address) if size == nil then size = "" end eval("#"..algo.." "..size) end function Radare.Hash.sha512(size, address) return hash("sha512", size, address) --if size == nil then size = "" end --if address == nil then return r.cmd("#sha512 "..size) end --return r.cmd("#sha512 "..size.."@"..address) end -- code api function Radare.Code.comment(offset, message) -- TODO: if only offset passed, return comment string r.cmd("CC "..message.." @ "..offset) return Radare.Code end function Radare.Code.code(offset, len) r.cmd("Cc "..len.." @ "..offset) return Radare.Code end function Radare.Code.data(offset, len) r.cmd("Cd "..len.." @ "..offset) return Radare.Code end function Radare.Code.string(offset, len) r.cmd("Cs "..len.." @ "..offset) return Radare.Code end -- change a signal handler of the child process function Radare.Debugger.signal(signum, sighandler) r.cmd("!signal "..signum.." "..sighandler) return Radare.Debugger end function Radare.Debugger.bp_remove(address) r.cmd("!bp -"..address); return Radare.Debugger end function Radare.Debugger.continue(address) if address == nil then r.cmd("!cont"); else r.cmd("!cont "..address); end return Radare.Debugger end function Radare.Debugger.step(num) r.cmd("!step "..num) return Radare.Debugger end function Radare.Debugger.step(num) r.cmd("!step "..num) return Radare.Debugger end function Radare.Debugger.step_over() r.cmd("!stepo"); return Radare.Debugger end function Radare.Debugger.step_until_user_code() r.cmd("!stepu"); return Radare.Debugger end function Radare.Debugger.add_bp(addr) r.cmd("!bp "..addr) return Radare.Debugger end function Radare.Debugger.remove_bp(addr) r.cmd("!bp -"..addr) return Radare.Debugger end function Radare.Debugger.alloc(size) return cmd_str("!alloc "..size) end function Radare.Debugger.free(addr) -- rename to dealloc? return cmd_str("!free "..addr) end function Radare.Debugger.dump(dirname) r.cmd("!dump "..dirname) return Radare.Debugger end function Radare.Debugger.restore(dirname) r.cmd("!restore "..dirname) return Radare.Debugger end function Radare.Debugger.jump(addr) r.cmd("!jmp "..addr) return Radare.Debugger end function Radare.Debugger.backtrace() local res = split(Radare.cmd("!bt"),"\n") local ret = {} for i = 1, #res do local line = split(res[i], " ") ret[i] = line[2] end return ret; end print "[radare.lua] Type 'help()' or 'quit' to return to radare shell."
gpl-2.0
LionKingTeam/Lion.king.bot
libs/serpent.lua
31
8016
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end } -- کد های پایین در ربات نشان داده نمیشوند -- http://permag.ir -- @permag_ir -- @permag_bots -- @permag
gpl-3.0
Jichao/skia
tools/lua/skia.lua
207
1863
-- Experimental helpers for skia -- function string.startsWith(String,Start) return string.sub(String,1,string.len(Start))==Start end function string.endsWith(String,End) return End=='' or string.sub(String,-string.len(End))==End end Sk = {} function Sk.isFinite(x) return x * 0 == 0 end ------------------------------------------------------------------------------- Sk.Rect = { left = 0, top = 0, right = 0, bottom = 0 } Sk.Rect.__index = Sk.Rect function Sk.Rect.new(l, t, r, b) local rect if r then -- 4 arguments rect = { left = l, top = t, right = r, bottom = b } elseif l then -- 2 arguments rect = { right = l, bottom = t } else -- 0 arguments rect = {} end setmetatable(rect, Sk.Rect) return rect; end function Sk.Rect:width() return self.right - self.left end function Sk.Rect:height() return self.bottom - self.top end function Sk.Rect:isEmpty() return self:width() <= 0 or self:height() <= 0 end function Sk.Rect:isFinite() local value = self.left * 0 value = value * self.top value = value * self.right value = value * self.bottom return 0 == value end function Sk.Rect:setEmpty() self.left = 0 self.top = 0 self.right = 0 self.bottom = 0 end function Sk.Rect:set(l, t, r, b) self.left = l self.top = t self.right = r self.bottom = b end function Sk.Rect:offset(dx, dy) dy = dy or dx self.left = self.left + dx self.top = self.top + dy self.right = self.right + dx self.bottom = self.bottom + dy end function Sk.Rect:inset(dx, dy) dy = dy or dx self.left = self.left + dx self.top = self.top + dy self.right = self.right - dx self.bottom = self.bottom - dy end -------------------------------------------------------------------------------
bsd-3-clause
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/osx/syscalls.lua
18
1899
-- OSX specific syscalls local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" return function(S, hh, c, C, types) local ret64, retnum, retfd, retbool, retptr = hh.ret64, hh.retnum, hh.retfd, hh.retbool, hh.retptr local ffi = require "ffi" local errno = ffi.errno local h = require "syscall.helpers" local istype, mktype, getfd = h.istype, h.mktype, h.getfd local t, pt, s = types.t, types.pt, types.s -- TODO lutimes is implemented using setattrlist(2) in OSX function S.grantpt(fd) return S.ioctl(fd, "TIOCPTYGRANT") end function S.unlockpt(fd) return S.ioctl(fd, "TIOCPTYUNLK") end function S.ptsname(fd) local buf = t.buffer(128) local ok, err = S.ioctl(fd, "TIOCPTYGNAME", buf) if not ok then return nil, err end return ffi.string(buf) end function S.mach_absolute_time() return C.mach_absolute_time() end function S.mach_task_self() return C.mach_task_self_ end function S.mach_host_self() return C.mach_host_self() end function S.mach_port_deallocate(task, name) return retbool(C.mach_port_deallocate(task or S.mach_task_self(), name)) end function S.host_get_clock_service(host, clock_id, clock_serv) clock_serv = clock_serv or t.clock_serv1() local ok, err = C.host_get_clock_service(host or S.mach_host_self(), c.CLOCKTYPE[clock_id or "SYSTEM"], clock_serv) if not ok then return nil, err end return clock_serv[0] end -- TODO when mach ports do gc, can add 'clock_serv or S.host_get_clock_service()' function S.clock_get_time(clock_serv, cur_time) cur_time = cur_time or t.mach_timespec() local ok, err = C.clock_get_time(clock_serv, cur_time) if not ok then return nil, err end return cur_time end return S end
apache-2.0
koeppea/ettercap
src/lua/share/third-party/stdlib/src/object.lua
12
1911
--- Prototype-based objects -- <ul> -- <li>Create an object/class:</li> -- <ul> -- <li>Either, if the <code>_init</code> field is a list: -- <ul> -- <li><code>object/Class = prototype {value, ...; field = value, ...}</code></li> -- <li>Named values are assigned to the corresponding fields, and unnamed values -- to the fields given by <code>_init</code>.</li> -- </ul> -- <li>Or, if the <code>_init</code> field is a function: -- <ul> -- <li><code>object/Class = prototype (value, ...)</code></li> -- <li>The given values are passed as arguments to the <code>_init</code> function.</li> -- </ul> -- <li>An object's metatable is itself.</li> -- <li>Private fields and methods start with "<code>_</code>".</li> -- </ul> -- <li>Access an object field: <code>object.field</code></li> -- <li>Call an object method: <code>object:method (...)</code></li> -- <li>Call a class method: <code>Class.method (object, ...)</code></li> -- <li>Add a field: <code>object.field = x</code></li> -- <li>Add a method: <code>function object:method (...) ... end</code></li> -- </li> require "table_ext" --- Root object -- @class table -- @name Object -- @field _init constructor method or list of fields to be initialised by the -- constructor -- @field _clone object constructor which provides the behaviour for <code>_init</code> -- documented above local Object = { _init = {}, _clone = function (self, ...) local object = table.clone (self) if type (self._init) == "table" then table.merge (object, table.clone_rename (self._init, ...)) else object = self._init (object, ...) end return setmetatable (object, object) end, -- Sugar instance creation __call = function (...) -- First (...) gets first element of list return (...)._clone (...) end, } setmetatable (Object, Object) return Object
gpl-2.0
LaFamiglia/Illarion-Content
item/id_24_shovel.lua
1
6351
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_24_shovel' WHERE itm_id=24; local common = require("base.common") local treasure = require("item.base.treasure") local transformation_dog = require("alchemy.teaching.transformation_dog") local claydigging = require("content.gatheringcraft.claydigging") local sanddigging = require("content.gatheringcraft.sanddigging") local metal = require("item.general.metal") local M = {} M.LookAtItem = metal.LookAtItem -- @return True if found a treasure. local function DigForTreasure(User) local TargetPos = common.GetFrontPosition(User) local groundTile = world:getField(TargetPos):tile() local groundType = common.GetGroundType(groundTile) if groundType ~= common.GroundType.rocks then return treasure.performDiggingForTreasure(User, TargetPos, { maximalLevel = (User:getSkill(Character.mining) / 10) + 1, msgDiggingOut = { de = "Du gräbst mit deiner Schaufel in den Boden und stößt auf etwas hartes, von dem ein " .. "hölzerner Klang ausgeht. Noch einmal graben und du hältst den Schatz in deinen Händen.", en = "You dig with your shovel into the ground and hit suddenly something hard and wooden " .. "sounding. You only have to dig another time to get the treasure." }} ) end return false end local function DigForNothing(User) local TargetPos = common.GetFrontPosition(User) local groundTile = world:getField( TargetPos ):tile() local groundType = common.GetGroundType( groundTile ) if ( groundType == common.GroundType.field ) then common.HighInformNLS( User, "Du gräbst ein kleines Loch in den Ackerboden, doch findest du hier gar nichts.", "You dig a small hole into the farming ground. But you find nothing.") elseif ( groundType == common.GroundType.sand ) then common.HighInformNLS( User, "Du gräbst ein kleines Loch in den Sand, doch findest du hier gar nichts.", "You dig a small hole into the sand. But you find nothing.") elseif ( groundType == common.GroundType.dirt ) then common.HighInformNLS( User, "Du gräbst ein kleines Loch in den Dreck, doch findest du hier gar nichts.", "You dig a small hole into the dirt. But you find nothing.") elseif ( groundType == common.GroundType.forest ) then common.HighInformNLS( User, "Du gräbst ein kleines Loch in den Waldboden, doch findest du hier gar nichts.", "You dig a small hole into the forest ground. But you find nothing.") elseif ( groundType == common.GroundType.grass ) then common.HighInformNLS( User, "Du gräbst ein kleines Loch in die Wiese, doch findest du hier gar nichts.", "You dig a small hole into the grass. But you find nothing.") elseif ( groundType == common.GroundType.rocks ) then common.HighInformNLS( User, "Der Boden besteht hier aus solidem Stein. Mit einer Schaufel hast du eindeutig das falsche Werkzeug.", "The ground here is heavy stone. With a shovel you have the wrong tool here for sure.") elseif ( groundType == common.GroundType.water ) then common.HighInformNLS( User, "Im Wasser mit einer Schaufel zu graben geht zwar relativ leicht, doch der Effekt ist recht gering.", "To dig with a shovel in the water is pretty easy. But sadly there is no effect in doing this.") else common.HighInformNLS(User, "Du versuchst an dieser Stelle zu graben, findest aber nichts.", "You attempt to dig here, but you don't find anything.") end end local function getPit(User, itemId) local pitItem = common.GetFrontItem(User) if (pitItem ~= nil and pitItem.id == itemId) then return pitItem end pitItem = common.GetItemInArea(User.pos, itemId) return pitItem end function M.UseItem(User, SourceItem, ltstate) local toolItem = User:getItemAt(5) if ( toolItem.id ~=24 ) then toolItem = User:getItemAt(6) if ( toolItem.id ~= 24 ) then common.HighInformNLS( User, "Du musst die Schaufel in der Hand haben!", "You have to hold the shovel in your hand!" ) return end end if not common.FitForWork( User ) then -- check minimal food points return end -- check for alchemy scroll if transformation_dog.DigForTeachingScroll(User) then return end -- check for treasure if DigForTreasure(User) then return end local pitItem -- check for sand pit local SAND_PIT = 1208 pitItem = getPit(User, SAND_PIT) if (pitItem ~= nil) then sanddigging.StartGathering(User, pitItem, ltstate) return end local EMPTY_SAND_PIT = 3632 pitItem = getPit(User, EMPTY_SAND_PIT) if (pitItem ~= nil) then User:inform( "An dieser Stelle gibt es nicht mehrs zu holen.", "There isn't anything left in this pit.", Character.highPriority); return end -- check for clay pit local CLAY_PIT = 1206 pitItem = getPit(User, CLAY_PIT) if (pitItem ~= nil) then claydigging.StartGathering(User, pitItem, ltstate) return end local EMPTY_CLAY_PIT = 3633 pitItem = getPit(User, EMPTY_CLAY_PIT) if (pitItem ~= nil) then User:inform( "An dieser Stelle gibt es nicht mehrs zu holen.", "There isn't anything left in this pit.", Character.highPriority); return end -- inform the user that he digs for nothing DigForNothing(User) end return M
agpl-3.0
nood32/MEEDOBOT
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-2.0
Zenolisk/Rebellion
gamemode/libs/sh_anim.lua
1
7663
anim = anim or {} anim.classes = anim.classes or {} function anim.SetModelClass(class, model) model = string.lower(model) anim.classes[model] = class end function anim.GetClass(model) return anim.classes[model] or (string.find(model, "female") and "citizen_female" or "citizen_male") end -- C++ Weapons do not have their holdtypes accessible by Lua. local holdTypes = { weapon_physgun = "smg", weapon_physcannon = "smg", weapon_stunstick = "melee", weapon_crowbar = "melee", weapon_stunstick = "melee", weapon_357 = "pistol", weapon_pistol = "pistol", weapon_smg1 = "smg", weapon_ar2 = "smg", weapon_crossbow = "smg", weapon_shotgun = "shotgun", weapon_frag = "grenade", weapon_slam = "grenade", weapon_rpg = "rpg", weapon_bugbait = "melee", weapon_annabelle = "shotgun", gmod_tool = "pistol" } -- We don't want to make a table for all of the holdtypes, so just alias them. local translateHoldType = { melee2 = "melee", fist = "melee", knife = "melee", ar2 = "smg", physgun = "smg", crossbow = "smg", slam = "grenade", passive = "normal", rpg = "rpg" } function util.GetHoldType(weapon) local holdType = holdTypes[weapon:GetClass()] if (holdType) then return holdType elseif (weapon.HoldType) then return translateHoldType[weapon.HoldType] or weapon.HoldType else return "normal" end end anim.SetModelClass("models/Humans/Group03/Male_01.mdl", "citizen_male") anim.SetModelClass("models/Humans/Group03/Male_02.mdl", "citizen_male") anim.SetModelClass("models/Humans/Group03/Male_03.mdl", "citizen_male") anim.SetModelClass("models/Humans/Group03/Male_04.mdl", "citizen_male") anim.SetModelClass("models/Humans/Group03/Male_05.mdl", "citizen_male") anim.SetModelClass("models/Humans/Group03/Male_06.mdl", "citizen_male") anim.SetModelClass("models/Humans/Group03/Male_07.mdl", "citizen_male") anim.SetModelClass("models/Humans/Group03/Male_08.mdl", "citizen_male") anim.SetModelClass("models/Humans/Group03/Male_09.mdl", "citizen_male") -- Male citizen animation tree. anim.citizen_male = { normal = { idle = ACT_IDLE_ANGRY_SMG1, idle_crouch = ACT_COVER_LOW, walk = ACT_WALK_AIM_RIFLE_STIMULATED, walk_crouch = ACT_WALK_CROUCH_AIM_RIFLE, sprint = "sprint_all", run = ACT_RUN_AIM_RIFLE_STIMULATED, run_crouch = ACT_RUN_CROUCH }, pistol = { idle = ACT_IDLE_ANGRY_SMG1, idle_crouch = ACT_RANGE_AIM_SMG1_LOW, walk = ACT_WALK_AIM_RIFLE_STIMULATED, walk_crouch = ACT_WALK_CROUCH_AIM_RIFLE, run = ACT_RUN_AIM_RIFLE_STIMULATED, run_crouch = ACT_RUN_CROUCH, sprint = "sprint_all", attack = ACT_GESTURE_RANGE_ATTACK_PISTOL, reload = ACT_RELOAD_PISTOL }, smg = { idle = ACT_IDLE_ANGRY_SMG1, idle_crouch = ACT_RANGE_AIM_SMG1_LOW, walk = ACT_WALK_AIM_RIFLE_STIMULATED, walk_crouch = ACT_WALK_CROUCH_AIM_RIFLE, run = ACT_RUN_AIM_RIFLE_STIMULATED, run_crouch = ACT_RUN_CROUCH, sprint = "sprint_all", attack = ACT_GESTURE_RANGE_ATTACK_SMG1, reload = ACT_GESTURE_RELOAD_SMG1 }, shotgun = { idle = ACT_IDLE_ANGRY_SMG1, idle_crouch = ACT_RANGE_AIM_SMG1_LOW, walk = ACT_WALK_AIM_RIFLE_STIMULATED, walk_crouch = ACT_WALK_CROUCH_AIM_RIFLE, run = ACT_RUN_AIM_RIFLE_STIMULATED, run_crouch = ACT_RUN_CROUCH, sprint = "sprint_all", attack = ACT_GESTURE_RANGE_ATTACK_SHOTGUN }, grenade = { idle = ACT_IDLE_MANNEDGUN, idle_crouch = ACT_RANGE_AIM_SMG1_LOW, walk = ACT_WALK_AIM_RIFLE, walk_crouch = ACT_WALK_CROUCH_AIM_RIFLE, run = ACT_RUN_AIM_RIFLE_STIMULATED, run_crouch = ACT_RUN_CROUCH, sprint = "sprint_all", attack = ACT_RANGE_ATTACK_THROW }, melee = { idle = ACT_IDLE_ANGRY_MELEE, idle_crouch = ACT_COVER_LOW, walk = ACT_WALK_AIM_RIFLE, walk_crouch = ACT_WALK_CROUCH, run = ACT_RUN, run_crouch = ACT_RUN_CROUCH, sprint = "sprint_all", attack = ACT_MELEE_ATTACK_SWING }, glide = ACT_GLIDE } local math_NormalizeAngle = math.NormalizeAngle local string_find = string.find local string_lower = string.lower local getAnimClass = anim.GetClass local Length2D = FindMetaTable("Vector").Length2D function GM:CalcMainActivity(client, velocity) local model = string_lower(client:GetModel()) local class = getAnimClass(model) if (string_find(model, "/player/") or string_find(model, "/playermodel") or class == "player") then return self.BaseClass:CalcMainActivity(client, velocity) end if (client:Alive()) then client.CalcSeqOverride = -1 local weapon = client:GetActiveWeapon() local holdType = "normal" local action = "idle" local length2D = Length2D(velocity) if (length2D >= reb.config.sprintSpeed) then action = "sprint" elseif (length2D >= reb.config.runSpeed) then action = "run" elseif (length2D >= reb.config.walkSpeed + 20 and client:Crouching()) then action = "run" elseif (length2D >= reb.config.walkSpeed - 80) then action = "walk" end if (client:Crouching()) then action = action.."_crouch" end local animClass = anim[class] if (!animClass) then class = "citizen_male" end if (!animClass[holdType]) then holdType = "normal" end if (!animClass[holdType][action]) then action = "idle" end local animation = animClass[holdType][action] local value = ACT_IDLE if (!client:OnGround()) then client.CalcIdeal = animClass.glide or ACT_GLIDE elseif (client:InVehicle()) then if weapon.Base == "reb_wep_base" then client.CalcIdeal = ACT_HL2MP_SIT_SMG1 else client.CalcIdeal = ACT_HL2MP_SIT end elseif (animation) then value = animation if (type(value) == "string") then client.CalcSeqOverride = client:LookupSequence(value) else client.CalcIdeal = value end end local override = client:GetNWFloat("seq") if (override) then client.CalcSeqOverride = client:LookupSequence(override) end if (CLIENT) then client:SetIK(false) end local eyeAngles = client:EyeAngles() local yaw = velocity:Angle().yaw local normalized = math_NormalizeAngle(yaw - eyeAngles.y) client:SetPoseParameter("move_yaw", normalized) return client.CalcIdeal or ACT_IDLE, client.CalcSeqOverride or -1 end end function GM:DoAnimationEvent(client, event, data) local model = string_lower(client:GetModel()) local class = getAnimClass(model) if (string_find(model, "/player/") or string_find(model, "/playermodel") or class == "player") then return self.BaseClass:DoAnimationEvent(client, event, data) end local weapon = client:GetActiveWeapon() local holdType = "normal" local class = anim.GetClass(model) if (!anim[class]) then class = "citizen_male" end if (IsValid(weapon)) then holdType = util.GetHoldType(weapon) end if (!anim[class][holdType]) then holdType = "normal" end local animation = anim[class][holdType] if (event == PLAYERANIMEVENT_ATTACK_PRIMARY) then client:AnimRestartGesture(GESTURE_SLOT_ATTACK_AND_RELOAD, animation.attack or ACT_GESTURE_RANGE_ATTACK_SMG1, true) return ACT_VM_PRIMARYATTACK elseif (event == PLAYERANIMEVENT_ATTACK_SECONDARY) then client:AnimRestartGesture(GESTURE_SLOT_ATTACK_AND_RELOAD, animation.attack or ACT_GESTURE_RANGE_ATTACK_SMG1, true) return ACT_VM_SECONDARYATTACK elseif (event == PLAYERANIMEVENT_RELOAD) then client:AnimRestartGesture(GESTURE_SLOT_ATTACK_AND_RELOAD, animation.reload or ACT_GESTURE_RELOAD_SMG1, true) return ACT_INVALID elseif (event == PLAYERANIMEVENT_JUMP) then client.m_bJumping = true client.m_bFistJumpFrame = true client.m_flJumpStartTime = CurTime() client:AnimRestartMainSequence() return ACT_INVALID elseif (event == PLAYERANIMEVENT_CANCEL_RELOAD) then client:AnimResetGestureSlot(GESTURE_SLOT_ATTACK_AND_RELOAD) return ACT_INVALID end return nil end
mit
pigparadise/skynet
lualib/http/httpd.lua
101
3708
local internal = require "http.internal" local table = table local string = string local type = type local httpd = {} local http_status_msg = { [100] = "Continue", [101] = "Switching Protocols", [200] = "OK", [201] = "Created", [202] = "Accepted", [203] = "Non-Authoritative Information", [204] = "No Content", [205] = "Reset Content", [206] = "Partial Content", [300] = "Multiple Choices", [301] = "Moved Permanently", [302] = "Found", [303] = "See Other", [304] = "Not Modified", [305] = "Use Proxy", [307] = "Temporary Redirect", [400] = "Bad Request", [401] = "Unauthorized", [402] = "Payment Required", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [406] = "Not Acceptable", [407] = "Proxy Authentication Required", [408] = "Request Time-out", [409] = "Conflict", [410] = "Gone", [411] = "Length Required", [412] = "Precondition Failed", [413] = "Request Entity Too Large", [414] = "Request-URI Too Large", [415] = "Unsupported Media Type", [416] = "Requested range not satisfiable", [417] = "Expectation Failed", [500] = "Internal Server Error", [501] = "Not Implemented", [502] = "Bad Gateway", [503] = "Service Unavailable", [504] = "Gateway Time-out", [505] = "HTTP Version not supported", } local function readall(readbytes, bodylimit) local tmpline = {} local body = internal.recvheader(readbytes, tmpline, "") if not body then return 413 -- Request Entity Too Large end local request = assert(tmpline[1]) local method, url, httpver = request:match "^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$" assert(method and url and httpver) httpver = assert(tonumber(httpver)) if httpver < 1.0 or httpver > 1.1 then return 505 -- HTTP Version not supported end local header = internal.parseheader(tmpline,2,{}) if not header then return 400 -- Bad request end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then return 501 -- Not Implemented end end if mode == "chunked" then body, header = internal.recvchunkedbody(readbytes, bodylimit, header, body) if not body then return 413 end else -- identity mode if length then if bodylimit and length > bodylimit then return 413 end if #body >= length then body = body:sub(1,length) else local padding = readbytes(length - #body) body = body .. padding end end end return 200, url, method, header, body end function httpd.read_request(...) local ok, code, url, method, header, body = pcall(readall, ...) if ok then return code, url, method, header, body else return nil, code end end local function writeall(writefunc, statuscode, bodyfunc, header) local statusline = string.format("HTTP/1.1 %03d %s\r\n", statuscode, http_status_msg[statuscode] or "") writefunc(statusline) if header then for k,v in pairs(header) do if type(v) == "table" then for _,v in ipairs(v) do writefunc(string.format("%s: %s\r\n", k,v)) end else writefunc(string.format("%s: %s\r\n", k,v)) end end end local t = type(bodyfunc) if t == "string" then writefunc(string.format("content-length: %d\r\n\r\n", #bodyfunc)) writefunc(bodyfunc) elseif t == "function" then writefunc("transfer-encoding: chunked\r\n") while true do local s = bodyfunc() if s then if s ~= "" then writefunc(string.format("\r\n%x\r\n", #s)) writefunc(s) end else writefunc("\r\n0\r\n\r\n") break end end else assert(t == "nil") writefunc("\r\n") end end function httpd.write_response(...) return pcall(writeall, ...) end return httpd
mit
jsenellart-systran/OpenNMT
test/onmt/HookManagerTest.lua
4
2697
require('onmt.init') local tester = ... local hookManagerTest = torch.TestSuite() function hookManagerTest.nohook() local hookManager = onmt.utils.HookManager.new({}) tester:eq(hookManager.hooks, {}) hookManager = onmt.utils.HookManager.new({hook_file=''}) tester:eq(hookManager.hooks, {}) end function hookManagerTest.badhook() local logger_save = _G.logger _G.logger=nil local _, err = pcall( function() onmt.utils.HookManager.new({hook_file='bad'}) end) tester:assert(err~=nil) _G.logger = logger_save end function hookManagerTest.options() local logger_save = _G.logger _G.logger=nil local hookManager local _, err = pcall( function() hookManager = onmt.utils.HookManager.new({hook_file='test.data.testhooks'}) tester:ne(hookManager.hooks["declareOpts"], nil) end) tester:assert(err==nil) if hookManager then local cmd = onmt.utils.ExtendedCmdLine.new('train.lua') onmt.data.SampledVocabDataset.declareOpts(cmd) cmd:text('Other options') cmd:text('') onmt.utils.Memory.declareOpts(cmd) onmt.utils.Profiler.declareOpts(cmd) tester:assert(cmd.options['-sample_vocab']~=nil) tester:assert(cmd.options['-disable_mem_optimization']~=nil) tester:assert(cmd.options['-profiler']~=nil) tester:eq(cmd.options['-sample_vocab_type'], nil) tester:eq(cmd.options['-sample_vocab'].default, false) -- insert on the fly the option depending if there is a hook selected onmt.utils.HookManager.updateOpt({'-hook_file','test.data.testhooks'}, cmd) -- removed profiler option tester:eq(cmd.options['-profiler'], nil) -- new sample_vocab_type option tester:ne(cmd.options['-sample_vocab_type'], nil) -- sample_vocab true by default tester:eq(cmd.options['-sample_vocab'].default, true) -- new happy options tester:ne(cmd.options['-happy'], nil) end _G.logger = logger_save end function hookManagerTest.function_call() local logger_save = _G.logger local hookmanager_save = _G.hookManager _G.logger=nil local hookManager local _, err = pcall( function() hookManager = onmt.utils.HookManager.new({hook_file='test.data.testhooks'}) tester:ne(hookManager.hooks["declareOpts"], nil) end) tester:assert(err==nil) if hookManager then _G.hookManager = onmt.utils.HookManager.new() local tokenizer = require('tools.utils.tokenizer') tester:ne(tokenizer.tokenize({segment_alphabet={}},"it is a test"), "XX") _G.hookManager = hookManager tester:eq(tokenizer.tokenize({segment_alphabet={}},"it is a test"), "XX") end _G.logger = logger_save _G.hookManager = hookmanager_save end return hookManagerTest
mit
ninjalulz/forgottenserver
data/movements/scripts/tiles.lua
4
1953
local increasing = {[416] = 417, [426] = 425, [446] = 447, [3216] = 3217, [3202] = 3215, [11062] = 11063} local decreasing = {[417] = 416, [425] = 426, [447] = 446, [3217] = 3216, [3215] = 3202, [11063] = 11062} function onStepIn(creature, item, position, fromPosition) if not increasing[item.itemid] then return true end if not creature:isPlayer() or creature:isInGhostMode() then return true end item:transform(increasing[item.itemid]) if item.actionid >= actionIds.levelDoor then if creature:getLevel() < item.actionid - actionIds.levelDoor then creature:teleportTo(fromPosition, false) position:sendMagicEffect(CONST_ME_MAGIC_BLUE) creature:sendTextMessage(MESSAGE_EVENT_ADVANCE, "The tile seems to be protected against unwanted intruders.") end return true end if Tile(position):hasFlag(TILESTATE_PROTECTIONZONE) then local lookPosition = creature:getPosition() lookPosition:getNextPosition(creature:getDirection()) local depotItem = Tile(lookPosition):getItemByType(ITEM_TYPE_DEPOT) if depotItem then local depotItems = creature:getDepotChest(getDepotId(depotItem:getUniqueId()), true):getItemHoldingCount() creature:sendTextMessage(MESSAGE_STATUS_DEFAULT, "Your depot contains " .. depotItems .. " item" .. (depotItems > 1 and "s." or ".")) creature:addAchievementProgress("Safely Stored Away", 1000) return true end end if item.actionid ~= 0 and creature:getStorageValue(item.actionid) <= 0 then creature:teleportTo(fromPosition, false) position:sendMagicEffect(CONST_ME_MAGIC_BLUE) creature:sendTextMessage(MESSAGE_EVENT_ADVANCE, "The tile seems to be protected against unwanted intruders.") return true end return true end function onStepOut(creature, item, position, fromPosition) if not decreasing[item.itemid] then return true end if creature:isPlayer() and creature:isInGhostMode() then return true end item:transform(decreasing[item.itemid]) return true end
gpl-2.0
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/freebsd/ioctl.lua
24
4451
-- ioctls, filling in as needed local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(types) local s, t = types.s, types.t local strflag = require("syscall.helpers").strflag local bit = require "syscall.bit" local band = bit.band local function bor(...) local r = bit.bor(...) if r < 0 then r = r + 4294967296 end -- TODO see note in NetBSD return r end local lshift = bit.lshift local rshift = bit.rshift local IOC = { VOID = 0x20000000, OUT = 0x40000000, IN = 0x80000000, PARM_SHIFT = 13, } IOC.PARM_MASK = lshift(1, IOC.PARM_SHIFT) - 1 IOC.INOUT = IOC.IN + IOC.OUT IOC.DIRMASK = IOC.IN + IOC.OUT + IOC.VOID local function ioc(dir, ch, nr, size) return t.ulong(bor(dir, lshift(band(size, IOC.PARM_MASK), 16), lshift(ch, 8), nr)) end local singletonmap = { int = "int1", char = "char1", uint = "uint1", uint64 = "uint64_1", off = "off1", } local function _IOC(dir, ch, nr, tp) if type(ch) == "string" then ch = ch:byte() end if type(tp) == "number" then return ioc(dir, ch, nr, tp) end local size = s[tp] local singleton = singletonmap[tp] ~= nil tp = singletonmap[tp] or tp return {number = ioc(dir, ch, nr, size), read = dir == IOC.OUT or dir == IOC.INOUT, write = dir == IOC.IN or dir == IOC.INOUT, type = t[tp], singleton = singleton} end local _IO = function(ch, nr) return _IOC(IOC.VOID, ch, nr, 0) end local _IOR = function(ch, nr, tp) return _IOC(IOC.OUT, ch, nr, tp) end local _IOW = function(ch, nr, tp) return _IOC(IOC.IN, ch, nr, tp) end local _IOWR = function(ch, nr, tp) return _IOC(IOC.INOUT, ch, nr, tp) end local _IOWINT = function(ch, nr) return _IOC(IOC.VOID, ch, nr, "int") end local ioctl = strflag { -- tty ioctls TIOCEXCL = _IO('t', 13), TIOCNXCL = _IO('t', 14), TIOCGPTN = _IOR('t', 15, "int"), TIOCFLUSH = _IOW('t', 16, "int"), TIOCGETA = _IOR('t', 19, "termios"), TIOCSETA = _IOW('t', 20, "termios"), TIOCSETAW = _IOW('t', 21, "termios"), TIOCSETAF = _IOW('t', 22, "termios"), TIOCGETD = _IOR('t', 26, "int"), TIOCSETD = _IOW('t', 27, "int"), TIOCPTMASTER = _IO('t', 28), TIOCGDRAINWAIT = _IOR('t', 86, "int"), TIOCSDRAINWAIT = _IOW('t', 87, "int"), TIOCTIMESTAMP = _IOR('t', 89, "timeval"), TIOCMGDTRWAIT = _IOR('t', 90, "int"), TIOCMSDTRWAIT = _IOW('t', 91, "int"), TIOCDRAIN = _IO('t', 94), TIOCSIG = _IOWINT('t', 95), TIOCEXT = _IOW('t', 96, "int"), TIOCSCTTY = _IO('t', 97), TIOCCONS = _IOW('t', 98, "int"), TIOCGSID = _IOR('t', 99, "int"), TIOCSTAT = _IO('t', 101), TIOCUCNTL = _IOW('t', 102, "int"), TIOCSWINSZ = _IOW('t', 103, "winsize"), TIOCGWINSZ = _IOR('t', 104, "winsize"), TIOCMGET = _IOR('t', 106, "int"), TIOCMBIC = _IOW('t', 107, "int"), TIOCMBIS = _IOW('t', 108, "int"), TIOCMSET = _IOW('t', 109, "int"), TIOCSTART = _IO('t', 110), TIOCSTOP = _IO('t', 111), TIOCPKT = _IOW('t', 112, "int"), TIOCNOTTY = _IO('t', 113), TIOCSTI = _IOW('t', 114, "char"), TIOCOUTQ = _IOR('t', 115, "int"), TIOCSPGRP = _IOW('t', 118, "int"), TIOCGPGRP = _IOR('t', 119, "int"), TIOCCDTR = _IO('t', 120), TIOCSDTR = _IO('t', 121), TIOCCBRK = _IO('t', 122), TIOCSBRK = _IO('t', 123), -- file descriptor ioctls FIOCLEX = _IO('f', 1), FIONCLEX = _IO('f', 2), FIONREAD = _IOR('f', 127, "int"), FIONBIO = _IOW('f', 126, "int"), FIOASYNC = _IOW('f', 125, "int"), FIOSETOWN = _IOW('f', 124, "int"), FIOGETOWN = _IOR('f', 123, "int"), FIODTYPE = _IOR('f', 122, "int"), FIOGETLBA = _IOR('f', 121, "int"), FIODGNAME = _IOW('f', 120, "fiodgname_arg"), FIONWRITE = _IOR('f', 119, "int"), FIONSPACE = _IOR('f', 118, "int"), FIOSEEKDATA = _IOWR('f', 97, "off"), FIOSEEKHOLE = _IOWR('f', 98, "off"), -- allow user defined ioctls _IO = _IO, _IOR = _IOR, _IOW = _IOW, _IOWR = _IOWR, _IOWINT = _IOWINT, } return ioctl end return {init = init}
apache-2.0
soundsrc/premake-core
modules/xcode/_preload.lua
6
1666
--- -- xcode/_preload.lua -- Define the Apple XCode actions and new APIs. -- Copyright (c) 2009-2015 Jason Perkins and the Premake project --- local p = premake -- -- Register new Xcode-specific project fields. -- p.api.register { name = "xcodebuildsettings", scope = "config", kind = "key-array", } p.api.register { name = "xcodebuildresources", scope = "config", kind = "list", } p.api.register { name = "xcodecodesigningidentity", scope = "config", kind = "string", } p.api.register { name = "xcodesystemcapabilities", scope = "project", kind = "key-boolean", } p.api.register { name = "iosfamily", scope = "config", kind = "string", allowed = { "iPhone/iPod touch", "iPad", "Universal", } } -- -- Register the Xcode exporters. -- newaction { trigger = "xcode4", shortname = "Apple Xcode 4", description = "Generate Apple Xcode 4 project files", -- Xcode always uses Mac OS X path and naming conventions toolset = "clang", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "SharedLib", "StaticLib", "Makefile", "Utility", "None" }, valid_languages = { "C", "C++" }, valid_tools = { cc = { "gcc", "clang" }, }, -- Workspace and project generation logic onWorkspace = function(wks) p.generate(wks, ".xcworkspace/contents.xcworkspacedata", p.modules.xcode.generateWorkspace) end, onProject = function(prj) p.generate(prj, ".xcodeproj/project.pbxproj", p.modules.xcode.generateProject) end, } -- -- Decide when the full module should be loaded. -- return function(cfg) return (_ACTION == "xcode4") end
bsd-3-clause
darya7476/Dimon
plugins/sticker2photo.lua
15
1070
local function tosticker(msg, success, result) local receiver = get_receiver(msg) if success then local file = '/root/robot/data/stickers/'..msg.from.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) send_photo(get_receiver(msg), file, ok_cb, false) redis:del("sticker:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id if msg.media then if msg.media.type == 'document' and is_momod(msg) and redis:get("sticker:photo") then if redis:get("sticker:photo") == 'waiting' then load_document(msg.id, tosticker, msg) end end end if matches[1] == "tophoto" and is_momod(msg) then redis:set("sticker:photo", "waiting") return 'Please send your sticker now' end end return { patterns = { "^[!/](tophoto)$", "%[(document)%]", }, run = run, }
gpl-2.0
ArianWatch/SportTG
plugins/webshot.lua
110
1424
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Website Screen Shot", usage = { "/web (url) : screen shot of website" }, patterns = { "^[!/]web (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
MustaphaTR/OpenRA
mods/ra/maps/top-o-the-world/top-o-the-world.lua
7
14024
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] --All timers have been reduced by 40% because time was flying 40% faster than reality in the original game. --That's why instead of having an hour to complete the mission you only have 36 minutes. --Unit Groups Setup USSRDie01 = { USSRGrenadier01, USSRGrenadier02, USSRGrenadier03, USSRFlame01, USSRFlame03 } USSRDie02 = { USSRGrenadier04, USSRGrenadier05, USSRFlame02, USSRFlame04 } USSRDie03 = { USSRHTank01, USSRHTank02 } USSRDie04 = { USSRDog01, USSRDog03 } USSRDie05 = { USSRDog02, USSRDog04 } USSRDie06 = { USSRV202, USSRV203 } AlliedSquad01 = { AlliedSquad01RocketInf01, AlliedSquad01RocketInf02, AlliedSquad01RocketInf03, AlliedSquad01RocketInf04, AlliedSquad01RocketInf05 } AlliedSquad02 = { AlliedSquad02RifleInf01, AlliedSquad02RifleInf02, AlliedSquad02RifleInf03, AlliedSquad02RifleInf04, AlliedSquad02RifleInf05, AlliedSquad02RifleInf06, AlliedSquad02RifleInf07, AlliedSquad02RifleInf08, AlliedSquad02RifleInf09 } AlliedSquad03 = { AlliedSquad03LTank01, AlliedSquad03RocketInf01, AlliedSquad03RocketInf02, AlliedSquad03RocketInf03 } AlliedSquad04 = { AlliedSquad04MGG01, AlliedSquad04MTank01, AlliedSquad04MTank02, AlliedSquad04MTank03, AlliedSquad04MTank04, AlliedSquad04MTank05, AlliedSquad04Arty01, AlliedSquad04Arty02, AlliedSquad04Arty03 } AlliedTanksReinforcement = { "2tnk", "2tnk" } if Difficulty == "easy" then AlliedHuntingParty = { "1tnk" } elseif Difficulty == "normal" then AlliedHuntingParty = { "1tnk", "1tnk" } elseif Difficulty == "hard" then AlliedHuntingParty = { "1tnk", "1tnk", "1tnk" } end --Building Group Setup AlliedAAGuns = { AAGun01, AAGun02, AAGun03, AAGun04, AAGun05, AAGun06 } --Area Triggers Setup WaystationTrigger = { CPos.New(61, 37), CPos.New(62, 37), CPos.New(63, 37), CPos.New(64, 37), CPos.New(65, 37), CPos.New(66, 37), CPos.New(67, 37), CPos.New(68, 37), CPos.New(69, 37), CPos.New(70, 37), CPos.New(71, 37), CPos.New(72, 37), CPos.New(73, 37), CPos.New(74, 37), CPos.New(75, 37), CPos.New(61, 38), CPos.New(62, 38), CPos.New(63, 38), CPos.New(64, 38), CPos.New(65, 38), CPos.New(66, 38), CPos.New(67, 38), CPos.New(68, 38), CPos.New(69, 38), CPos.New(70, 38), CPos.New(71, 38), CPos.New(72, 38), CPos.New(73, 38), CPos.New(74, 38), CPos.New(75, 38), CPos.New(61, 39), CPos.New(62, 39), CPos.New(63, 39), CPos.New(64, 39), CPos.New(65, 39), CPos.New(66, 39), CPos.New(67, 39), CPos.New(68, 39), CPos.New(69, 39), CPos.New(70, 39), CPos.New(71, 39), CPos.New(72, 39), CPos.New(73, 39), CPos.New(74, 39), CPos.New(75, 39) } Inf01Trigger = { CPos.New(81, 90), CPos.New(81, 91), CPos.New(81, 92), CPos.New(81, 93), CPos.New(81, 94), CPos.New(81, 95), CPos.New(82, 90), CPos.New(82, 91), CPos.New(82, 92), CPos.New(82, 93), CPos.New(82, 94), CPos.New(82, 95) } Inf02Trigger = { CPos.New(85, 90), CPos.New(85, 91), CPos.New(85, 92), CPos.New(85, 93), CPos.New(85, 94), CPos.New(85, 95), CPos.New(86, 90), CPos.New(86, 91), CPos.New(86, 92), CPos.New(86, 93), CPos.New(86, 94), CPos.New(86, 95) } RevealBridgeTrigger = { CPos.New(74, 52), CPos.New(75, 52), CPos.New(76, 52), CPos.New(77, 52), CPos.New(78, 52), CPos.New(79, 52), CPos.New(80, 52), CPos.New(81, 52), CPos.New(82, 52), CPos.New(83, 52), CPos.New(84, 52), CPos.New(85, 52), CPos.New(86, 52), CPos.New(87, 52), CPos.New(88, 52), CPos.New(76, 53), CPos.New(77, 53), CPos.New(78, 53), CPos.New(79, 53), CPos.New(80, 53), CPos.New(81, 53), CPos.New(82, 53), CPos.New(83, 53), CPos.New(84, 53), CPos.New(85, 53), CPos.New(86, 53), CPos.New(87, 53) } --Mission Variables Setup DateTime.TimeLimit = DateTime.Minutes(36) BridgeIsIntact = true --Mission Functions Setup HuntObjectiveTruck = function(a) if a.HasProperty("Hunt") then if a.Owner == greece or a.Owner == goodguy then Trigger.OnIdle(a, function(a) if a.IsInWorld and not ObjectiveTruck01.IsDead then a.AttackMove(ObjectiveTruck01.Location, 2) elseif a.IsInWorld then a.Hunt() end end) end end end HuntEnemyUnits = function(a) if a.HasProperty("Hunt") then Trigger.OnIdle(a, function(a) if a.IsInWorld then a.Hunt() end end) end end AlliedGroundPatrols = function(a) if a.HasProperty("Hunt") then if a.IsInWorld then a.Patrol({ AlliedHuntingPartyWP02.Location, AlliedHuntingPartyWP03.Location, AlliedHuntingPartyWP04.Location, AlliedHuntingPartyWP05.Location, AlliedHuntingPartyWP06.Location, AlliedHuntingPartyWP07.Location }, false, 50) end end end SpawnAlliedHuntingParty = function() Trigger.AfterDelay(DateTime.Minutes(3), function() if BridgeIsIntact then local tanks = Reinforcements.Reinforce(greece, AlliedHuntingParty, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location,AlliedHuntingPartyWP03.Location, AlliedHuntingPartyWP05.Location }, 0) Utils.Do(tanks, function(units) HuntObjectiveTruck(units) end) SpawnAlliedHuntingParty() end end) end WorldLoaded = function() --Players Setup player = Player.GetPlayer("USSR") greece = Player.GetPlayer("Greece") goodguy = Player.GetPlayer("GoodGuy") badguy = Player.GetPlayer("BadGuy") neutral = Player.GetPlayer("Neutral") creeps = Player.GetPlayer("Creeps") Camera.Position = DefaultCameraPosition.CenterPosition --Objectives Setup InitObjectives(player) BringSupplyTruck = player.AddObjective("Bring the supply truck to the waystation.") ProtectWaystation = player.AddObjective("The waystation must not be destroyed.") DestroyAAGuns = player.AddObjective("Destroy all the AA Guns to enable air support.", "Secondary", false) PreventAlliedIncursions = player.AddObjective("Find and destroy the bridge the allies are using\nto bring their reinforcements in the area.", "Secondary", false) Trigger.OnKilled(USSRTechCenter01, function() player.MarkFailedObjective(ProtectWaystation) end) Trigger.OnKilled(ObjectiveTruck01, function() player.MarkFailedObjective(BringSupplyTruck) end) Trigger.OnEnteredFootprint(WaystationTrigger, function(unit, id) if unit == ObjectiveTruck01 then Trigger.RemoveFootprintTrigger(id) player.MarkCompletedObjective(BringSupplyTruck) player.MarkCompletedObjective(ProtectWaystation) end end) Trigger.OnAllKilled(AlliedAAGuns, function() player.MarkCompletedObjective(DestroyAAGuns) Media.PlaySpeechNotification(player, "ObjectiveMet") Trigger.AfterDelay(DateTime.Seconds(2), function() Actor.Create("powerproxy.spyplane", true, { Owner = player }) Actor.Create("powerproxy.parabombs", true, { Owner = player }) Media.DisplayMessage("Very good comrade general! Our air units just took off\nand should be in your area in approximately three minutes.") end) end) --Triggers Setup SpawnAlliedHuntingParty() Trigger.AfterDelay(0, function() local playerrevealcam = Actor.Create("camera", true, { Owner = player, Location = PlayerStartLocation.Location }) Trigger.AfterDelay(1, function() if playerrevealcam.IsInWorld then playerrevealcam.Destroy() end end) end) Trigger.OnEnteredFootprint(Inf01Trigger, function(unit, id) if unit.Owner == player then if not AlliedGNRLHouse.IsDead then Reinforcements.Reinforce(greece, { "gnrl" }, { AlliedGNRLSpawn.Location, AlliedGNRLDestination.Location }, 0, function(unit) HuntEnemyUnits(unit) end) end Utils.Do(AlliedSquad01, HuntEnemyUnits) local alliedgnrlcamera = Actor.Create("scamera", true, { Owner = player, Location = AlliedGNRLSpawn.Location }) Trigger.AfterDelay(DateTime.Seconds(6), function() if alliedgnrlcamera.IsInWorld then alliedgnrlcamera.Destroy() end end) Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnEnteredFootprint(Inf02Trigger, function(unit, id) if unit.Owner == player then Utils.Do(AlliedSquad02, HuntEnemyUnits) Trigger.RemoveFootprintTrigger(id) end end) Utils.Do(AlliedSquad03, function(actor) Trigger.OnDamaged(actor, function(unit, attacker) if attacker.Owner == player then Utils.Do(AlliedSquad03, HuntEnemyUnits) end end) end) Trigger.OnEnteredFootprint(RevealBridgeTrigger, function(unit, id) if unit.Owner == player then local bridgecamera01 = Actor.Create("camera", true, { Owner = player, Location = AlliedHuntingPartySpawn.Location }) local bridgecamera02 = Actor.Create("camera", true, { Owner = player, Location = AlliedHuntingPartyWP01.Location }) Trigger.AfterDelay(DateTime.Seconds(6), function() if bridgecamera01.IsInWorld then bridgecamera01.Destroy() end if bridgecamera02.IsInWorld then bridgecamera02.Destroy() end end) if Difficulty == "normal" then Reinforcements.Reinforce(goodguy, { "dd" }, { AlliedDestroyer01Spawn.Location, AlliedDestroyer01WP01.Location, AlliedDestroyer01WP02.Location }, 0, function(unit) unit.Stance = "Defend" end) end if Difficulty == "hard" then Reinforcements.Reinforce(goodguy, { "dd" }, { AlliedDestroyer01Spawn.Location, AlliedDestroyer01WP01.Location, AlliedDestroyer01WP02.Location }, 0, function(unit) unit.Stance = "Defend" end) Reinforcements.Reinforce(goodguy, { "dd" }, { AlliedDestroyer02Spawn.Location, AlliedDestroyer02WP01.Location, AlliedDestroyer02WP02.Location }, 0, function(unit) unit.Stance = "Defend" end) end Trigger.RemoveFootprintTrigger(id) end end) Trigger.AfterDelay(DateTime.Minutes(9), function() local powerproxy01 = Actor.Create("powerproxy.paratroopers", true, { Owner = greece }) local aircraft01 = powerproxy01.TargetParatroopers(AlliedParadropLZ01.CenterPosition, Angle.SouthWest) Utils.Do(aircraft01, function(a) Trigger.OnPassengerExited(a, function(t, p) HuntObjectiveTruck(p) end) end) local powerproxy02 = Actor.Create("powerproxy.paratroopers", true, { Owner = goodguy }) local aircraft02 = powerproxy02.TargetParatroopers(AlliedParadropLZ02.CenterPosition, Angle.SouthWest) Utils.Do(aircraft02, function(a) Trigger.OnPassengerExited(a, function(t, p) HuntObjectiveTruck(p) end) end) end) Trigger.AfterDelay(0, function() BridgeEnd = Map.ActorsInBox(AlliedHuntingPartySpawn.CenterPosition, AlliedHuntingPartyWP01.CenterPosition, function(self) return self.Type == "br2" end)[1] Trigger.OnKilled(BridgeEnd, function() BridgeIsIntact = false if not BridgeBarrel01.IsDead then BridgeBarrel01.Kill() end if not BridgeBarrel03.IsDead then BridgeBarrel03.Kill() end player.MarkCompletedObjective(PreventAlliedIncursions) Media.PlaySpeechNotification(player, "ObjectiveMet") Trigger.AfterDelay(DateTime.Seconds(2), function() Media.DisplayMessage("This should stop the allied forces from getting their ground based reinforcements.") end) end) end) Trigger.OnAnyKilled({ BridgeBarrel01, BridgeBarrel03 }, function() if not BridgeEnd.IsDead then BridgeEnd.Kill() end end) Trigger.OnAnyKilled(AlliedSquad04, function() if BridgeIsIntact then local tanks = Reinforcements.Reinforce(greece, AlliedTanksReinforcement, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location }, 0, function(units) AlliedGroundPatrols(units) end) Trigger.OnAllKilled(tanks, function() if BridgeIsIntact then Reinforcements.Reinforce(greece, AlliedTanksReinforcement, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location }, 0, function(units) AlliedGroundPatrols(units) end) end end) end end) Trigger.OnAllKilled(AlliedSquad04, function() if BridgeIsIntact then local tanks = Reinforcements.Reinforce(greece, AlliedTanksReinforcement, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location }, 0, function(units) AlliedGroundPatrols(units) end) Trigger.OnAllKilled(tanks, function() if BridgeIsIntact then Reinforcements.Reinforce(greece, AlliedTanksReinforcement, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location }, 0, function(units) AlliedGroundPatrols(units) end) end end) end end) --Units Death Setup Trigger.AfterDelay(DateTime.Seconds(660), function() Utils.Do(USSRDie01, function(actor) if not actor.IsDead then actor.Kill("DefaultDeath") end end) end) Trigger.AfterDelay(DateTime.Seconds(744), function() Utils.Do(USSRDie02, function(actor) if not actor.IsDead then actor.Kill("DefaultDeath") end end) end) Trigger.AfterDelay(DateTime.Seconds(1122), function() if not USSRHTank03.IsDead then USSRHTank03.Kill("DefaultDeath") end end) Trigger.AfterDelay(DateTime.Seconds(1230), function() Utils.Do(USSRDie03, function(actor) if not actor.IsDead then actor.Kill("DefaultDeath") end end) end) Trigger.AfterDelay(DateTime.Seconds(1338), function() Utils.Do(USSRDie04, function(actor) if not actor.IsDead then actor.Kill("DefaultDeath") end end) end) Trigger.AfterDelay(DateTime.Seconds(1416), function() Utils.Do(USSRDie05, function(actor) if not actor.IsDead then actor.Kill("DefaultDeath") end end) end) Trigger.AfterDelay(DateTime.Seconds(1668), function() if not USSRV201.IsDead then USSRV201.Kill("DefaultDeath") end end) Trigger.AfterDelay(DateTime.Seconds(1746), function() Utils.Do(USSRDie06, function(actor) if not actor.IsDead then actor.Kill("DefaultDeath") end end) end) Trigger.AfterDelay(DateTime.Seconds(2034), function() if not USSRMTank02.IsDead then USSRMTank02.Kill("DefaultDeath") end end) Trigger.AfterDelay(DateTime.Seconds(2142), function() if not USSRMTank01.IsDead then USSRMTank01.Kill("DefaultDeath") end end) Trigger.OnTimerExpired(function() if not ObjectiveTruck01.IsDead then ObjectiveTruck01.Kill("DefaultDeath") -- Set the limit to one so that the timer displays 0 and never ends -- (which would display the game time instead of 0) DateTime.TimeLimit = 1 end end) end
gpl-3.0
Noltari/luci
protocols/luci-proto-ipip/luasrc/model/cbi/admin_network/proto_ipip.lua
18
1684
-- Copyright 2016 Roger Pueyo Centelles <roger.pueyo@guifi.net> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local peeraddr, ipaddr, ttl, tos, df, mtu, tunlink peeraddr = section:taboption("general", Value, "peeraddr", translate("Remote IPv4 address or FQDN"), translate("The IPv4 address or the fully-qualified domain name of the remote tunnel end.")) peeraddr.optional = false peeraddr.datatype = "or(hostname,ip4addr)" ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("The local IPv4 address over which the tunnel is created (optional).")) ipaddr.optional = true ipaddr.datatype = "ip4addr" tunlink = section:taboption("general", Value, "tunlink", translate("Bind interface"), translate("Bind the tunnel to this interface (optional).")) ipaddr.optional = true mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"), translate("Specify an MTU (Maximum Transmission Unit) other than the default (1280 bytes).")) mtu.optional = true mtu.placeholder = 1280 mtu.datatype = "range(68, 9200)" ttl = section:taboption("advanced", Value, "ttl", translate("Override TTL"), translate("Specify a TTL (Time to Live) for the encapsulating packet other than the default (64).")) ttl.optional = true ttl.placeholder = 64 ttl.datatype = "min(1)" tos = section:taboption("advanced", Value, "tos", translate("Override TOS"), translate("Specify a TOS (Type of Service).")) tos.optional = true tos.datatype = "range(0, 255)" df = section:taboption("advanced", Flag, "df", translate("Don't Fragment"), translate("Enable the DF (Don't Fragment) flag of the encapsulating packets."))
apache-2.0
Noltari/luci
applications/luci-app-openvpn/luasrc/model/cbi/openvpn.lua
4
5538
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local testfullps = sys.exec("ps --help 2>&1 | grep BusyBox") --check which ps do we have local psstring = (string.len(testfullps)>0) and "ps w" or "ps axfw" --set command we use to get pid local m = Map("openvpn", translate("OpenVPN")) local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") ) s.template = "cbi/tblsection" s.template_addremove = "openvpn/cbi-select-input-add" s.addremove = true s.add_select_options = { } local cfg = s:option(DummyValue, "config") function cfg.cfgvalue(self, section) local file_cfg = self.map:get(section, "config") if file_cfg then s.extedit = luci.dispatcher.build_url("admin", "vpn", "openvpn", "file", "%s") else s.extedit = luci.dispatcher.build_url("admin", "vpn", "openvpn", "basic", "%s") end end uci:load("openvpn_recipes") uci:foreach( "openvpn_recipes", "openvpn_recipe", function(section) s.add_select_options[section['.name']] = section['_description'] or section['.name'] end ) function s.getPID(section) -- Universal function which returns valid pid # or nil local pid = sys.exec("%s | grep -w '[o]penvpn(%s)'" % { psstring, section }) if pid and #pid > 0 then return tonumber(pid:match("^%s*(%d+)")) else return nil end end function s.parse(self, section) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) if recipe and not s.add_select_options[recipe] then self.invalid_cts = true else TypedSection.parse( self, section ) end end function s.create(self, name) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) local name = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".text" ) if #name > 3 and not name:match("[^a-zA-Z0-9_]") then local s = uci:section("openvpn", "openvpn", name) if s then local options = uci:get_all("openvpn_recipes", recipe) for k, v in pairs(options) do if k ~= "_role" and k ~= "_description" then if type(v) == "boolean" then v = v and "1" or "0" end uci:set("openvpn", name, k, v) end end uci:save("openvpn") uci:commit("openvpn") if extedit then luci.http.redirect( self.extedit:format(name) ) end end elseif #name > 0 then self.invalid_cts = true end return 0 end function s.remove(self, name) local cfg_file = "/etc/openvpn/" ..name.. ".ovpn" local auth_file = "/etc/openvpn/" ..name.. ".auth" if fs.access(cfg_file) then fs.unlink(cfg_file) end if fs.access(auth_file) then fs.unlink(auth_file) end uci:delete("openvpn", name) uci:save("openvpn") uci:commit("openvpn") end s:option( Flag, "enabled", translate("Enabled") ) local active = s:option( DummyValue, "_active", translate("Started") ) function active.cfgvalue(self, section) local pid = s.getPID(section) if pid ~= nil then return (sys.process.signal(pid, 0)) and translatef("yes (%i)", pid) or translate("no") end return translate("no") end local updown = s:option( Button, "_updown", translate("Start/Stop") ) updown._state = false updown.redirect = luci.dispatcher.build_url( "admin", "vpn", "openvpn" ) function updown.cbid(self, section) local pid = s.getPID(section) self._state = pid ~= nil and sys.process.signal(pid, 0) self.option = self._state and "stop" or "start" return AbstractValue.cbid(self, section) end function updown.cfgvalue(self, section) self.title = self._state and "stop" or "start" self.inputstyle = self._state and "reset" or "reload" end function updown.write(self, section, value) if self.option == "stop" then sys.call("/etc/init.d/openvpn stop %s" % section) else sys.call("/etc/init.d/openvpn start %s" % section) end luci.http.redirect( self.redirect ) end local port = s:option( DummyValue, "port", translate("Port") ) function port.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) if not val then local file_cfg = self.map:get(section, "config") if file_cfg and fs.access(file_cfg) then val = sys.exec("awk '{if(match(tolower($1),/^port$/)&&match($2,/[0-9]+/)){cnt++;printf $2;exit}}END{if(cnt==0)printf \"-\"}' " ..file_cfg) if val == "-" then val = sys.exec("awk '{if(match(tolower($1),/^remote$/)&&match($3,/[0-9]+/)){cnt++;printf $3;exit}}END{if(cnt==0)printf \"-\"}' " ..file_cfg) end end end return val or "-" end local proto = s:option( DummyValue, "proto", translate("Protocol") ) function proto.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) if not val then local file_cfg = self.map:get(section, "config") if file_cfg and fs.access(file_cfg) then val = sys.exec("awk '{if(match(tolower($1),/^proto$/)&&match(tolower($2),/^udp[46]*$|^tcp[46]*-server$|^tcp[46]*-client$/)){cnt++;printf tolower($2);exit}}END{if(cnt==0)printf \"-\"}' " ..file_cfg) if val == "-" then val = sys.exec("awk '{if(match(tolower($1),/^remote$/)&&match(tolower($4),/^udp[46]*$|^tcp[46]*-server$|^tcp[46]*-client$/)){cnt++;printf $4;exit}}END{if(cnt==0)printf \"-\"}' " ..file_cfg) end end end return val or "-" end function m.on_after_apply(self,map) sys.call('/etc/init.d/openvpn reload') end return m
apache-2.0
snabbnfv-goodies/snabbswitch
lib/luajit/src/jit/v.lua
78
5755
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1 loop] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..oex..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then out:write(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else out:write(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local info = traceinfo(tr) local link, ltype = info.link, info.linktype if ltype == "interpreter" then out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif ltype == "stitch" then out:write(format("[TRACE %3s %s%s %s %s]\n", tr, startex, startloc, ltype, fmtfunc(func, pc))) elseif link == tr or link == 0 then out:write(format("[TRACE %3s %s%s %s]\n", tr, startex, startloc, ltype)) elseif ltype == "root" then out:write(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) else out:write(format("[TRACE %3s %s%s -> %d %s]\n", tr, startex, startloc, link, ltype)) end else out:write(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. return { on = dumpon, off = dumpoff, start = dumpon -- For -j command line option. }
apache-2.0
Inorizushi/DDR-X3
Graphics/MusicWheelItem SectionCollapsed NormalPart/2nd.lua
1
2977
local group; local t = Def.ActorFrame{ InitCommand=cmd(zoom,0.7); LoadActor("cd_mask")..{ InitCommand=cmd(blend,Blend.NoEffect;zwrite,1;clearzbuffer,true;); }; Def.Sprite { SetMessageCommand=function(self,params) self:ztest(1) group = params.Text; local so = GAMESTATE:GetSortOrder(); if group then if so == "SortOrder_Group" then if group_name[group] ~= nil then local filePath = THEME:GetPathG("","_jackets/group/"..group_name[group]..".png"); self:Load(filePath) self:diffusealpha(1); else self:Load( THEME:GetPathG("","_No banner") ); self:diffusealpha(0); end; end; end; end; }; Def.Banner { Name="SongBanner"; InitCommand=cmd(scaletoclipped,256,256;diffusealpha,0;); SetMessageCommand=function(self,params) self:ztest(1) local pt_text = params.Text; local group = params.Text; if group then if params.HasFocus then setenv("getgroupname",pt_text); end; if group_name[group] ~= nil then self:Load( THEME:GetPathG("","_No banner") ); self:diffusealpha(0); else self:LoadFromSongGroup(group); self:diffusealpha(1); end; else -- call fallback self:Load( THEME:GetPathG("","_No banner") ); self:diffusealpha(1); end; end; }; Def.ActorFrame{ Name="CdOver"; InitCommand=cmd(); LoadActor("overlay"); }; }; t[#t+1] = Def.Sprite { InitCommand=cmd(y,40); SetMessageCommand=function(self,params) group = params.Text; local so = GAMESTATE:GetSortOrder(); if group then if so == "SortOrder_Group" then if group_name[group] ~= nil then local filePath = THEME:GetPathG("","_jackets/group/"..group_name[group]..".png"); self:Load(filePath) self:diffusealpha(1); else self:Load( THEME:GetPathG("","_No banner") ); self:diffusealpha(0); end; end; end; end; }; t[#t+1] = Def.ActorFrame{ Def.Banner { Name="SongBanner"; InitCommand=cmd(scaletoclipped,256,256;diffusealpha,0;y,40); SetMessageCommand=function(self,params) local pt_text = params.Text; local group = params.Text; if group then if params.HasFocus then setenv("getgroupname",pt_text); end; if group_name[group] ~= nil then self:Load( THEME:GetPathG("","_No banner") ); self:diffusealpha(0); else self:LoadFromSongGroup(group); self:diffusealpha(1); end; else -- call fallback self:Load( THEME:GetPathG("","_No banner") ); self:diffusealpha(1); end; end; }; LoadFont("_helvetica Bold 24px")..{ InitCommand=cmd(y,-44;maxwidth,256); SetMessageCommand=function(self, params) local song = params.Song; group = params.Text; local so = GAMESTATE:GetSortOrder(); if group_name[group] ~= nil then self:settext(""); else if so == "SortOrder_Group" then self:settext(group); self:strokecolor(color("#000000")) self:diffuse(color("#FFFFFF")); else self:settext(""); end; end; end; }; }; return t;
mit
vladimir-kotikov/clink-completions
completions/adb.lua
1
9130
--- adb.lua, Android ADB completion for Clink. -- @compatible Android SDK Platform-tools v31.0.3 (ADB v1.0.41) -- @author Goldie Lin -- @date 2021-08-27 -- @see [Clink](https://github.com/chrisant996/clink) -- @usage -- Place it in "%LocalAppData%\clink\" if installed globally, -- or "ConEmu/ConEmu/clink/" if you used portable ConEmu & Clink. -- -- luacheck: no unused args -- luacheck: ignore clink rl_state local function dump(o) -- luacheck: ignore if type(o) == 'table' then local s = '{ ' local prefix = "" for k, v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s..prefix..'['..k..']="'..dump(v)..'"' prefix = ', ' end return s..' }' else return tostring(o) end end local function generate_matches(command, pattern) local f = io.popen('2>nul '..command) if f then local matches = {} for line in f:lines() do if line ~= 'List of devices attached' then table.insert(matches, line:match(pattern)) end end f:close() return matches end end local function serialno_matches() return generate_matches('adb devices', '^(%w+)%s+.*$') end local function transportid_matches() return generate_matches('adb devices -l', '^.*%s+transport_id:(%d+)%s*.*$') end local serialno_parser = clink.argmatcher():addarg({serialno_matches}) local transportid_parser = clink.argmatcher():addarg({transportid_matches}) local null_parser = clink.argmatcher():nofiles() local devices_parser = clink.argmatcher() :nofiles() :addflags( "-l" ) local reconnect_parser = clink.argmatcher() :nofiles() :addarg({ "device", "offline" }) local networking_options_parser = clink.argmatcher() :addflags( "--list", "--no-rebind", "--remove", "--remove-all" ) local mdns_parser = clink.argmatcher() :nofiles() :addarg({ "check", "services" }) local push_parser = clink.argmatcher() :addflags( "--sync", "-n", "-z", "-Z" ) local pull_parser = clink.argmatcher() :addflags( "-a", "-z", "-Z" ) local sync_parser = clink.argmatcher() :addflags( "-n", "-l", "-z", "-Z" ) :addarg({ "all", "data", "odm", "oem", "product_services", "product", "system", "system_ext", "vendor" }) local shell_bu_backup_parser = clink.argmatcher() :addflags( "-f", "-all", "-apk", "-noapk", "-obb", "-noobb", "-shared", "-noshared", "-system", "-nosystem", "-keyvalue", "-nokeyvalue" ) local backup_parser = shell_bu_backup_parser local shell_bu_parser = clink.argmatcher() :addarg({ "backup" .. shell_bu_backup_parser, "restore" }) local shell_parser = clink.argmatcher() :addflags( "-e", "-n", "-T", "-t", "-x" ) :addarg({ "bu" .. shell_bu_parser }) local install_parser = clink.argmatcher() :addflags( "-l", "-r", "-t", "-s", "-d", "-g", "--abi", "--instant", "--no-streaming", "--streaming", "--fastdeploy", "--no-fastdeploy", "--force-agent", "--date-check-agent", "--version-check-agent", "--local-agent" ) local install_multiple_parser = clink.argmatcher() :addflags( "-l", "-r", "-t", "-s", "-d", "-p", "-g", "--abi", "--instant", "--no-streaming", "--streaming", "--fastdeploy", "--no-fastdeploy", "--force-agent", "--date-check-agent", "--version-check-agent", "--local-agent" ) local install_multi_package_parser = clink.argmatcher() :addflags( "-l", "-r", "-t", "-s", "-d", "-p", "-g", "--abi", "--instant", "--no-streaming", "--streaming", "--fastdeploy", "--no-fastdeploy", "--force-agent", "--date-check-agent", "--version-check-agent", "--local-agent" ) local uninstall_parser = clink.argmatcher() :addflags( "-k" ) local logcat_format_parser = clink.argmatcher() :nofiles() :addarg({ "brief", "help", "long", "process", "raw", "tag", "thread", "threadtime", "time", "color", "descriptive", "epoch", "monotonic", "printable", "uid", "usec", "UTC", "year", "zone" }) local logcat_buffer_parser = clink.argmatcher() :nofiles() :addarg({ "default", -- default = main,system,crash "all", "main", "radio", "events", "system", "crash", "security", "kernel" }) local logcat_parser = clink.argmatcher() :nofiles() :addflags( "-s", "-f", "--file", "-r", "--rotate-kbytes", "-n", "--rotate-count", "--id", "-v" .. logcat_format_parser, "--format" .. logcat_format_parser, "-D", "--dividers", "-c", "--clear", "-d", "-e", "--regex", "-m", "--max-count", "--print", "-t", "-T", "-g", "--buffer-size", "-G", "--buffer-size=", "-L", "--last", "-b" .. logcat_buffer_parser, "--buffer" .. logcat_buffer_parser, "-B", "--binary", "-S", "--statistics", "-p", "--prune", "-P", "--prune=", "--pid", "--wrap" ) :addarg({ "*:V", "*:D", "*:I", "*:W", "*:E", "*:F", "*:S", }) local remount_parser = clink.argmatcher() :nofiles() :addflags( "-R" ) local reboot_parser = clink.argmatcher() :nofiles() :addarg({ "bootloader", "recovery", "sideload", "sideload-auto-reboot", "edl" }) clink.argmatcher("adb") :addflags( "-a", "-d", "-e", "-s" .. serialno_parser, "-p", "-t" .. transportid_parser, "-H", "-P", "-L" ) :addarg({ "help" .. null_parser, "version" .. null_parser, "devices" .. devices_parser, "connect" .. null_parser, "disconnect" .. null_parser, "pair" .. null_parser, "reconnect" .. reconnect_parser, "ppp", "forward" .. networking_options_parser, "reverse" .. networking_options_parser, "mdns" .. mdns_parser, "push" .. push_parser, "pull" .. pull_parser, "sync" .. sync_parser, "shell" .. shell_parser, "emu", "install" .. install_parser, "install-multiple" .. install_multiple_parser, "install-multi-package" .. install_multi_package_parser, "uninstall" .. uninstall_parser, "backup" .. backup_parser, "restore", "bugreport", "jdwp" .. null_parser, "logcat" .. logcat_parser, "disable-verity" .. null_parser, "enable-verity" .. null_parser, "keygen", "wait-for-device" .. null_parser, "wait-for-recovery" .. null_parser, "wait-for-rescue" .. null_parser, "wait-for-sideload" .. null_parser, "wait-for-bootloader" .. null_parser, "wait-for-disconnect" .. null_parser, "wait-for-any-device" .. null_parser, "wait-for-any-recovery" .. null_parser, "wait-for-any-rescue" .. null_parser, "wait-for-any-sideload" .. null_parser, "wait-for-any-bootloader" .. null_parser, "wait-for-any-disconnect" .. null_parser, "wait-for-usb-device" .. null_parser, "wait-for-usb-recovery" .. null_parser, "wait-for-usb-rescue" .. null_parser, "wait-for-usb-sideload" .. null_parser, "wait-for-usb-bootloader" .. null_parser, "wait-for-usb-disconnect" .. null_parser, "wait-for-local-device" .. null_parser, "wait-for-local-recovery" .. null_parser, "wait-for-local-rescue" .. null_parser, "wait-for-local-sideload" .. null_parser, "wait-for-local-bootloader" .. null_parser, "wait-for-local-disconnect" .. null_parser, "get-state" .. null_parser, "get-serialno" .. null_parser, "get-devpath" .. null_parser, "remount" .. remount_parser, "reboot-bootloader" .. null_parser, "reboot" .. reboot_parser, "sideload", "root" .. null_parser, "unroot" .. null_parser, "usb" .. null_parser, "tcpip", "start-server" .. null_parser, "kill-server" .. null_parser, "attach" .. null_parser, "detach" .. null_parser })
mit
LaFamiglia/Illarion-Content
quest/akaltuts_chamber_526_dungeon.lua
1
8305
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (526, 'quest.Akaltuts_Chamber_526_dungeon'); local common = require("base.common") local monsterQuests = require("monster.base.quests") local M = {} local GERMAN = Player.german local ENGLISH = Player.english -- Insert the quest title here, in both languages local Title = {} Title[GERMAN] = "Die Kammer von Akaltut II" Title[ENGLISH] = "Akaltut's Chamber II" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do local Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Sammle sechs Elbenschwert und bringe sie zum Defensor Sancio." Description[ENGLISH][1] = "Collect six elven swords for Defensor Sancio." Description[GERMAN][2] = "Der Defensor Mando hat vielleicht eine Aufgabe für dich." Description[ENGLISH][2] = "The Defensor Mando may have a task for you." Description[GERMAN][3] = "Töte Drow für den Defensor Mando Du benötigst noch zehn." Description[ENGLISH][3] = "Kill drow for Defensor Mando. You still need ten." Description[GERMAN][4] = "Töte Drow für den Defensor Mando. Du benötigst noch neun." Description[ENGLISH][4] = "Kill drow for Defensor Mando. You still need nine." Description[GERMAN][5] = "Töte Drow für den Defensor Mando. Du benötigst noch acht." Description[ENGLISH][5] = "Kill drow for Defensor Mando. You still need eight." Description[GERMAN][6] = "Töte Drow für den Defensor Mando. Du benötigst noch sieben." Description[ENGLISH][6] = "Kill drow for Defensor Mando. You still need seven." Description[GERMAN][7] = "Töte Drow für den Defensor Mando. Du benötigst noch sechs." Description[ENGLISH][7] = "Kill drow for Defensor Mando. You still need six." Description[GERMAN][8] = "Töte Drow für den Defensor Mando. Du benötigst noch fünf." Description[ENGLISH][8] = "Kill drow for Defensor Mando. You still need five." Description[GERMAN][9] = "Töte Drow für den Defensor Mando. Du benötigst noch vier." Description[ENGLISH][9] = "Kill drow for Defensor Mando. You still need four." Description[GERMAN][10] = "Töte Drow für den Defensor Mando. Du benötigst noch drei." Description[ENGLISH][10] = "Kill drow for Defensor Mando. You still need three." Description[GERMAN][11] = "Töte Drow für den Defensor Mando. Du benötigst noch zwei." Description[ENGLISH][11] = "Kill drow for Defensor Mando. You still need two." Description[GERMAN][12] = "Töte Drow für den Defensor Mando. Du benötigst noch ein." Description[ENGLISH][12] = "Kill drow for Defensor Mando. You still need one." Description[GERMAN][13] = "Kehre zurück zum Defensor Mando. Du hast seinen Test bestanden." Description[ENGLISH][13] = "Report back to Defensor Mando, you have finished his test." Description[GERMAN][14] = "Der Defensor Confirmo hat vielleicht eine Aufgabe für dich." Description[ENGLISH][14] = "The Defensor Confirmo may have a task for you." Description[GERMAN][15] = "Finde 'Die Herrschaft Akaltuts' in der Bibliothek und lies es für Defensor Confirmo." Description[ENGLISH][15] = "Find the copy of 'The Reign of Akaltut' in the library and read it for Defensor Confirmo." Description[GERMAN][16] = "Kehre zu Defensor Confirmo zurück um deine Belohnung zu erhalten." Description[ENGLISH][16] = "Return to Defensor Confirmo for your reward." Description[GERMAN][17] = "Der Defensor Prohibeo hat vielleicht eine Aufgabe für dich." Description[ENGLISH][17] = "The Defensor Prohibeo may have a task for you." Description[GERMAN][18] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch zehn." Description[ENGLISH][18] = "Kill drow warrior for Defensor Prohibeo. You still need ten." Description[GERMAN][19] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch neun." Description[ENGLISH][19] = "Kill drow warrior for Defensor Prohibeo. You still need nine." Description[GERMAN][20] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch acht." Description[ENGLISH][20] = "Kill drow warrior for Defensor Prohibeo. You still need eight." Description[GERMAN][21] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch sieben." Description[ENGLISH][21] = "Kill drow warrior for Defensor Prohibeo. You still need seven." Description[GERMAN][22] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch sech." Description[ENGLISH][22] = "Kill drow warrior for Defensor Prohibeo. You still need six." Description[GERMAN][23] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch fünf." Description[ENGLISH][23] = "Kill drow warrior for Defensor Prohibeo. You still need five." Description[GERMAN][24] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch vier." Description[ENGLISH][24] = "Kill drow warrior for Defensor Prohibeo. You still need four." Description[GERMAN][25] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch drei." Description[ENGLISH][25] = "Kill drow warrior for Defensor Prohibeo. You still need three." Description[GERMAN][26] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch zwei." Description[ENGLISH][26] = "Kill drow warrior for Defensor Prohibeo You still need two." Description[GERMAN][27] = "Töte zehn Drow Krieger für den Defensor Prohibeo. Du benötigst noch einen." Description[ENGLISH][27] = "Kill drow warrior for Defensor Prohibeo. You still need one." Description[GERMAN][28] = "Kehre zurück zum Defensor Prohibeo. Du hast seinen Test bestanden." Description[ENGLISH][28] = "Report back to Defensor Prohibeo, you have finished his test." Description[GERMAN][29] = "Der Defensor Affligo hat vielleicht eine Aufgabe für dich." Description[ENGLISH][29] = "The Defensor Affligo may have a task for you." Description[GERMAN][30] = "Du hast den zweiten Teil der Prüfung bestanden." Description[ENGLISH][30] = "You have finished part two of the testing." -- Insert the position of the quest start here (probably the position of an NPC or item) local Start = {} -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there local QuestTarget = {} -- Insert the quest status which is reached at the end of the quest local FINAL_QUEST_STATUS = 30 -- Register the monster kill parts of the quest. monsterQuests.addQuest{ questId = 526, location = {position = position(470, 802, -9), radius = 100}, queststatus = {from = 3, to = 13}, questTitle = {german = Title[GERMAN], english = Title[ENGLISH]}, monsterName = {german = "Dunkelelfen", english = "drows"}, npcName = "Defensor Mando", monsterGroupIds = {6} -- all drows } monsterQuests.addQuest{ questId = 526, location = {position = position(470, 802, -9), radius = 100}, queststatus = {from = 18, to = 28}, questTitle = {german = Title[GERMAN], english = Title[ENGLISH]}, monsterName = {german = "Dunkelelfkrieger", english = "drow warriors"}, npcName = "Defensor Prohibeo", monsterIds = {62} -- drow warrior } function M.QuestTitle(user) return common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function M.QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return common.GetNLS(user, german, english) end function M.QuestStart() return Start end function M.QuestTargets(user, status) return QuestTarget[status] end function M.QuestFinalStatus() return FINAL_QUEST_STATUS end function M.QuestAvailability(user, status) return Player.questAvailable end return M
agpl-3.0
MustaphaTR/OpenRA
mods/ra/maps/soviet-08b/soviet08b-AI.lua
7
4471
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] IdlingUnits = { } DDPatrol = { "dd", "dd" } DDPatrol1Path = { DDPatrol1Point1.Location, DDPatrol1Point2.Location, DDPatrol1Point3.Location, DDPatrol1Point4.Location } DDPatrol2Path = { DDPatrol2Point1.Location, DDPatrol2Point2.Location, DDPatrol2Point3.Location, DDPatrol2Point4.Location } ShipArrivePath = { DDEntry.Location, DDEntryStop.Location } WTransWays = { { WaterUnloadEntry1.Location, WaterUnload1.Location }, { WaterUnloadEntry2.Location, WaterUnload2.Location }, { WaterUnloadEntry3.Location, WaterUnload3.Location }, { WaterUnloadEntry4.Location, WaterUnload4.Location }, { WaterUnloadEntry5.Location, WaterUnload5.Location }, { WaterUnloadEntry6.Location, WaterUnload6.Location } } WTransUnits = { hard = { { "2tnk", "1tnk", "e1", "e3", "e3" }, { "2tnk", "2tnk", "2tnk" } }, normal = { { "1tnk", "1tnk", "e3", "e3", "jeep" }, { "2tnk", "e3", "e3", "jeep" } }, easy = { { "1tnk", "e1", "e1", "e3", "e3" }, { "e3", "e3", "jeep", "jeep" } } } WTransDelays = { easy = DateTime.Minutes(4), normal = DateTime.Minutes(2), hard = DateTime.Minutes(1) } AttackGroup = { } AttackGroupSize = 10 ProductionInterval = { easy = DateTime.Seconds(30), normal = DateTime.Seconds(20), hard = DateTime.Seconds(10) } AlliedInfantry = { "e1", "e3" } AlliedVehiclesUpgradeDelay = DateTime.Minutes(15) AlliedVehicleType = "Normal" AlliedVehicles = { Normal = { "jeep", "1tnk", "1tnk" }, Upgraded = { "2tnk", "arty" } } WTransWaves = function() local way = Utils.Random(WTransWays) local units = Utils.Random(WTransUnits) local attackUnits = Reinforcements.ReinforceWithTransport(Greece, "lst", units , way, { way[2], way[1] })[2] Utils.Do(attackUnits, function(a) Trigger.OnAddedToWorld(a, function() a.AttackMove(SovietBase.Location) IdleHunt(a) end) end) Trigger.AfterDelay(WTransDelays, WTransWaves) end SendAttackGroup = function() if #AttackGroup < AttackGroupSize then return end Utils.Do(AttackGroup, function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end) AttackGroup = { } end ProduceInfantry = function() if (GreeceTent1.IsDead or GreeceTent1.Owner ~= Greece) and (GreeceTent2.IsDead or GreeceTent2.Owner ~= Greece) then return end Greece.Build({ Utils.Random(AlliedInfantry) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceInfantry) end) end ProduceVehicles = function() if GreeceWarFactory.IsDead or GreeceWarFactory.Owner ~= Greece then return end Greece.Build({ Utils.Random(AlliedVehicles[AlliedVehicleType]) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceVehicles) end) end BringDDPatrol = function(patrolPath) local units = Reinforcements.Reinforce(Greece, DDPatrol, ShipArrivePath) Utils.Do(units, function(unit) Trigger.OnIdle(unit, function(patrols) patrols.Patrol(patrolPath, true, 200) end) end) Trigger.OnAllKilled(units, function() if GreeceNavalYard.IsDead then return else if Difficulty == "easy" then Trigger.AfterDelay(DateTime.Minutes(7), function() BringDDPatrol(patrolPath) end) else Trigger.AfterDelay(DateTime.Minutes(4), function() BringDDPatrol(patrolPath) end) end end end) end ActivateAI = function() WTransUnits = WTransUnits[Difficulty] WTransDelays = WTransDelays[Difficulty] local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == Greece and self.HasProperty("StartBuildingRepairs") end) Utils.Do(buildings, function(actor) Trigger.OnDamaged(actor, function(building) if building.Owner == Greece and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) end) Trigger.AfterDelay(DateTime.Minutes(3), WTransWaves) Trigger.AfterDelay(AlliedVehiclesUpgradeDelay, function() AlliedVehicleType = "Upgraded" end) ProduceInfantry() ProduceVehicles() BringDDPatrol(DDPatrol1Path) Trigger.AfterDelay(DateTime.Minutes(1), function() BringDDPatrol(DDPatrol2Path) end) end
gpl-3.0
luiseduardohdbackup/WarriorQuest
WarriorQuest/runtime/ios/PrebuiltRuntimeLua.app/OpenglConstants.lua
78
27074
--Encapsulate opengl constants. gl = gl or {} gl.GCCSO_SHADER_BINARY_FJ = 0x9260 gl._3DC_XY_AMD = 0x87fa gl._3DC_X_AMD = 0x87f9 gl.ACTIVE_ATTRIBUTES = 0x8b89 gl.ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8b8a gl.ACTIVE_PROGRAM_EXT = 0x8259 gl.ACTIVE_TEXTURE = 0x84e0 gl.ACTIVE_UNIFORMS = 0x8b86 gl.ACTIVE_UNIFORM_MAX_LENGTH = 0x8b87 gl.ALIASED_LINE_WIDTH_RANGE = 0x846e gl.ALIASED_POINT_SIZE_RANGE = 0x846d gl.ALL_COMPLETED_NV = 0x84f2 gl.ALL_SHADER_BITS_EXT = 0xffffffff gl.ALPHA = 0x1906 gl.ALPHA16F_EXT = 0x881c gl.ALPHA32F_EXT = 0x8816 gl.ALPHA8_EXT = 0x803c gl.ALPHA8_OES = 0x803c gl.ALPHA_BITS = 0xd55 gl.ALPHA_TEST_FUNC_QCOM = 0xbc1 gl.ALPHA_TEST_QCOM = 0xbc0 gl.ALPHA_TEST_REF_QCOM = 0xbc2 gl.ALREADY_SIGNALED_APPLE = 0x911a gl.ALWAYS = 0x207 gl.AMD_compressed_3DC_texture = 0x1 gl.AMD_compressed_ATC_texture = 0x1 gl.AMD_performance_monitor = 0x1 gl.AMD_program_binary_Z400 = 0x1 gl.ANGLE_depth_texture = 0x1 gl.ANGLE_framebuffer_blit = 0x1 gl.ANGLE_framebuffer_multisample = 0x1 gl.ANGLE_instanced_arrays = 0x1 gl.ANGLE_pack_reverse_row_order = 0x1 gl.ANGLE_program_binary = 0x1 gl.ANGLE_texture_compression_dxt3 = 0x1 gl.ANGLE_texture_compression_dxt5 = 0x1 gl.ANGLE_texture_usage = 0x1 gl.ANGLE_translated_shader_source = 0x1 gl.ANY_SAMPLES_PASSED_CONSERVATIVE_EXT = 0x8d6a gl.ANY_SAMPLES_PASSED_EXT = 0x8c2f gl.APPLE_copy_texture_levels = 0x1 gl.APPLE_framebuffer_multisample = 0x1 gl.APPLE_rgb_422 = 0x1 gl.APPLE_sync = 0x1 gl.APPLE_texture_format_BGRA8888 = 0x1 gl.APPLE_texture_max_level = 0x1 gl.ARM_mali_program_binary = 0x1 gl.ARM_mali_shader_binary = 0x1 gl.ARM_rgba8 = 0x1 gl.ARRAY_BUFFER = 0x8892 gl.ARRAY_BUFFER_BINDING = 0x8894 gl.ATC_RGBA_EXPLICIT_ALPHA_AMD = 0x8c93 gl.ATC_RGBA_INTERPOLATED_ALPHA_AMD = 0x87ee gl.ATC_RGB_AMD = 0x8c92 gl.ATTACHED_SHADERS = 0x8b85 gl.BACK = 0x405 gl.BGRA8_EXT = 0x93a1 gl.BGRA_EXT = 0x80e1 gl.BGRA_IMG = 0x80e1 gl.BINNING_CONTROL_HINT_QCOM = 0x8fb0 gl.BLEND = 0xbe2 gl.BLEND_COLOR = 0x8005 gl.BLEND_DST_ALPHA = 0x80ca gl.BLEND_DST_RGB = 0x80c8 gl.BLEND_EQUATION = 0x8009 gl.BLEND_EQUATION_ALPHA = 0x883d gl.BLEND_EQUATION_RGB = 0x8009 gl.BLEND_SRC_ALPHA = 0x80cb gl.BLEND_SRC_RGB = 0x80c9 gl.BLUE_BITS = 0xd54 gl.BOOL = 0x8b56 gl.BOOL_VEC2 = 0x8b57 gl.BOOL_VEC3 = 0x8b58 gl.BOOL_VEC4 = 0x8b59 gl.BUFFER = 0x82e0 gl.BUFFER_ACCESS_OES = 0x88bb gl.BUFFER_MAPPED_OES = 0x88bc gl.BUFFER_MAP_POINTER_OES = 0x88bd gl.BUFFER_OBJECT_EXT = 0x9151 gl.BUFFER_SIZE = 0x8764 gl.BUFFER_USAGE = 0x8765 gl.BYTE = 0x1400 gl.CCW = 0x901 gl.CLAMP_TO_BORDER_NV = 0x812d gl.CLAMP_TO_EDGE = 0x812f gl.COLOR_ATTACHMENT0 = 0x8ce0 gl.COLOR_ATTACHMENT0_NV = 0x8ce0 gl.COLOR_ATTACHMENT10_NV = 0x8cea gl.COLOR_ATTACHMENT11_NV = 0x8ceb gl.COLOR_ATTACHMENT12_NV = 0x8cec gl.COLOR_ATTACHMENT13_NV = 0x8ced gl.COLOR_ATTACHMENT14_NV = 0x8cee gl.COLOR_ATTACHMENT15_NV = 0x8cef gl.COLOR_ATTACHMENT1_NV = 0x8ce1 gl.COLOR_ATTACHMENT2_NV = 0x8ce2 gl.COLOR_ATTACHMENT3_NV = 0x8ce3 gl.COLOR_ATTACHMENT4_NV = 0x8ce4 gl.COLOR_ATTACHMENT5_NV = 0x8ce5 gl.COLOR_ATTACHMENT6_NV = 0x8ce6 gl.COLOR_ATTACHMENT7_NV = 0x8ce7 gl.COLOR_ATTACHMENT8_NV = 0x8ce8 gl.COLOR_ATTACHMENT9_NV = 0x8ce9 gl.COLOR_ATTACHMENT_EXT = 0x90f0 gl.COLOR_BUFFER_BIT = 0x4000 gl.COLOR_BUFFER_BIT0_QCOM = 0x1 gl.COLOR_BUFFER_BIT1_QCOM = 0x2 gl.COLOR_BUFFER_BIT2_QCOM = 0x4 gl.COLOR_BUFFER_BIT3_QCOM = 0x8 gl.COLOR_BUFFER_BIT4_QCOM = 0x10 gl.COLOR_BUFFER_BIT5_QCOM = 0x20 gl.COLOR_BUFFER_BIT6_QCOM = 0x40 gl.COLOR_BUFFER_BIT7_QCOM = 0x80 gl.COLOR_CLEAR_VALUE = 0xc22 gl.COLOR_EXT = 0x1800 gl.COLOR_WRITEMASK = 0xc23 gl.COMPARE_REF_TO_TEXTURE_EXT = 0x884e gl.COMPILE_STATUS = 0x8b81 gl.COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb gl.COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8 gl.COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9 gl.COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba gl.COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc gl.COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd gl.COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0 gl.COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1 gl.COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2 gl.COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3 gl.COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4 gl.COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5 gl.COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6 gl.COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7 gl.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03 gl.COMPRESSED_RGBA_PVRTC_2BPPV2_IMG = 0x9137 gl.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02 gl.COMPRESSED_RGBA_PVRTC_4BPPV2_IMG = 0x9138 gl.COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1 gl.COMPRESSED_RGBA_S3TC_DXT3_ANGLE = 0x83f2 gl.COMPRESSED_RGBA_S3TC_DXT5_ANGLE = 0x83f3 gl.COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01 gl.COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00 gl.COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7 gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV = 0x8c4d gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV = 0x8c4e gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV = 0x8c4f gl.COMPRESSED_SRGB_S3TC_DXT1_NV = 0x8c4c gl.COMPRESSED_TEXTURE_FORMATS = 0x86a3 gl.CONDITION_SATISFIED_APPLE = 0x911c gl.CONSTANT_ALPHA = 0x8003 gl.CONSTANT_COLOR = 0x8001 gl.CONTEXT_FLAG_DEBUG_BIT = 0x2 gl.CONTEXT_ROBUST_ACCESS_EXT = 0x90f3 gl.COUNTER_RANGE_AMD = 0x8bc1 gl.COUNTER_TYPE_AMD = 0x8bc0 gl.COVERAGE_ALL_FRAGMENTS_NV = 0x8ed5 gl.COVERAGE_ATTACHMENT_NV = 0x8ed2 gl.COVERAGE_AUTOMATIC_NV = 0x8ed7 gl.COVERAGE_BUFFERS_NV = 0x8ed3 gl.COVERAGE_BUFFER_BIT_NV = 0x8000 gl.COVERAGE_COMPONENT4_NV = 0x8ed1 gl.COVERAGE_COMPONENT_NV = 0x8ed0 gl.COVERAGE_EDGE_FRAGMENTS_NV = 0x8ed6 gl.COVERAGE_SAMPLES_NV = 0x8ed4 gl.CPU_OPTIMIZED_QCOM = 0x8fb1 gl.CULL_FACE = 0xb44 gl.CULL_FACE_MODE = 0xb45 gl.CURRENT_PROGRAM = 0x8b8d gl.CURRENT_QUERY_EXT = 0x8865 gl.CURRENT_VERTEX_ATTRIB = 0x8626 gl.CW = 0x900 gl.DEBUG_CALLBACK_FUNCTION = 0x8244 gl.DEBUG_CALLBACK_USER_PARAM = 0x8245 gl.DEBUG_GROUP_STACK_DEPTH = 0x826d gl.DEBUG_LOGGED_MESSAGES = 0x9145 gl.DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243 gl.DEBUG_OUTPUT = 0x92e0 gl.DEBUG_OUTPUT_SYNCHRONOUS = 0x8242 gl.DEBUG_SEVERITY_HIGH = 0x9146 gl.DEBUG_SEVERITY_LOW = 0x9148 gl.DEBUG_SEVERITY_MEDIUM = 0x9147 gl.DEBUG_SEVERITY_NOTIFICATION = 0x826b gl.DEBUG_SOURCE_API = 0x8246 gl.DEBUG_SOURCE_APPLICATION = 0x824a gl.DEBUG_SOURCE_OTHER = 0x824b gl.DEBUG_SOURCE_SHADER_COMPILER = 0x8248 gl.DEBUG_SOURCE_THIRD_PARTY = 0x8249 gl.DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247 gl.DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824d gl.DEBUG_TYPE_ERROR = 0x824c gl.DEBUG_TYPE_MARKER = 0x8268 gl.DEBUG_TYPE_OTHER = 0x8251 gl.DEBUG_TYPE_PERFORMANCE = 0x8250 gl.DEBUG_TYPE_POP_GROUP = 0x826a gl.DEBUG_TYPE_PORTABILITY = 0x824f gl.DEBUG_TYPE_PUSH_GROUP = 0x8269 gl.DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824e gl.DECR = 0x1e03 gl.DECR_WRAP = 0x8508 gl.DELETE_STATUS = 0x8b80 gl.DEPTH24_STENCIL8_OES = 0x88f0 gl.DEPTH_ATTACHMENT = 0x8d00 gl.DEPTH_BITS = 0xd56 gl.DEPTH_BUFFER_BIT = 0x100 gl.DEPTH_BUFFER_BIT0_QCOM = 0x100 gl.DEPTH_BUFFER_BIT1_QCOM = 0x200 gl.DEPTH_BUFFER_BIT2_QCOM = 0x400 gl.DEPTH_BUFFER_BIT3_QCOM = 0x800 gl.DEPTH_BUFFER_BIT4_QCOM = 0x1000 gl.DEPTH_BUFFER_BIT5_QCOM = 0x2000 gl.DEPTH_BUFFER_BIT6_QCOM = 0x4000 gl.DEPTH_BUFFER_BIT7_QCOM = 0x8000 gl.DEPTH_CLEAR_VALUE = 0xb73 gl.DEPTH_COMPONENT = 0x1902 gl.DEPTH_COMPONENT16 = 0x81a5 gl.DEPTH_COMPONENT16_NONLINEAR_NV = 0x8e2c gl.DEPTH_COMPONENT16_OES = 0x81a5 gl.DEPTH_COMPONENT24_OES = 0x81a6 gl.DEPTH_COMPONENT32_OES = 0x81a7 gl.DEPTH_EXT = 0x1801 gl.DEPTH_FUNC = 0xb74 gl.DEPTH_RANGE = 0xb70 gl.DEPTH_STENCIL_OES = 0x84f9 gl.DEPTH_TEST = 0xb71 gl.DEPTH_WRITEMASK = 0xb72 gl.DITHER = 0xbd0 gl.DMP_shader_binary = 0x1 gl.DONT_CARE = 0x1100 gl.DRAW_BUFFER0_NV = 0x8825 gl.DRAW_BUFFER10_NV = 0x882f gl.DRAW_BUFFER11_NV = 0x8830 gl.DRAW_BUFFER12_NV = 0x8831 gl.DRAW_BUFFER13_NV = 0x8832 gl.DRAW_BUFFER14_NV = 0x8833 gl.DRAW_BUFFER15_NV = 0x8834 gl.DRAW_BUFFER1_NV = 0x8826 gl.DRAW_BUFFER2_NV = 0x8827 gl.DRAW_BUFFER3_NV = 0x8828 gl.DRAW_BUFFER4_NV = 0x8829 gl.DRAW_BUFFER5_NV = 0x882a gl.DRAW_BUFFER6_NV = 0x882b gl.DRAW_BUFFER7_NV = 0x882c gl.DRAW_BUFFER8_NV = 0x882d gl.DRAW_BUFFER9_NV = 0x882e gl.DRAW_BUFFER_EXT = 0xc01 gl.DRAW_FRAMEBUFFER_ANGLE = 0x8ca9 gl.DRAW_FRAMEBUFFER_APPLE = 0x8ca9 gl.DRAW_FRAMEBUFFER_BINDING_ANGLE = 0x8ca6 gl.DRAW_FRAMEBUFFER_BINDING_APPLE = 0x8ca6 gl.DRAW_FRAMEBUFFER_BINDING_NV = 0x8ca6 gl.DRAW_FRAMEBUFFER_NV = 0x8ca9 gl.DST_ALPHA = 0x304 gl.DST_COLOR = 0x306 gl.DYNAMIC_DRAW = 0x88e8 gl.ELEMENT_ARRAY_BUFFER = 0x8893 gl.ELEMENT_ARRAY_BUFFER_BINDING = 0x8895 gl.EQUAL = 0x202 gl.ES_VERSION_2_0 = 0x1 gl.ETC1_RGB8_OES = 0x8d64 gl.ETC1_SRGB8_NV = 0x88ee gl.EXTENSIONS = 0x1f03 gl.EXT_blend_minmax = 0x1 gl.EXT_color_buffer_half_float = 0x1 gl.EXT_debug_label = 0x1 gl.EXT_debug_marker = 0x1 gl.EXT_discard_framebuffer = 0x1 gl.EXT_map_buffer_range = 0x1 gl.EXT_multi_draw_arrays = 0x1 gl.EXT_multisampled_render_to_texture = 0x1 gl.EXT_multiview_draw_buffers = 0x1 gl.EXT_occlusion_query_boolean = 0x1 gl.EXT_read_format_bgra = 0x1 gl.EXT_robustness = 0x1 gl.EXT_sRGB = 0x1 gl.EXT_separate_shader_objects = 0x1 gl.EXT_shader_framebuffer_fetch = 0x1 gl.EXT_shader_texture_lod = 0x1 gl.EXT_shadow_samplers = 0x1 gl.EXT_texture_compression_dxt1 = 0x1 gl.EXT_texture_filter_anisotropic = 0x1 gl.EXT_texture_format_BGRA8888 = 0x1 gl.EXT_texture_rg = 0x1 gl.EXT_texture_storage = 0x1 gl.EXT_texture_type_2_10_10_10_REV = 0x1 gl.EXT_unpack_subimage = 0x1 gl.FALSE = 0x0 gl.FASTEST = 0x1101 gl.FENCE_CONDITION_NV = 0x84f4 gl.FENCE_STATUS_NV = 0x84f3 gl.FIXED = 0x140c gl.FJ_shader_binary_GCCSO = 0x1 gl.FLOAT = 0x1406 gl.FLOAT_MAT2 = 0x8b5a gl.FLOAT_MAT3 = 0x8b5b gl.FLOAT_MAT4 = 0x8b5c gl.FLOAT_VEC2 = 0x8b50 gl.FLOAT_VEC3 = 0x8b51 gl.FLOAT_VEC4 = 0x8b52 gl.FRAGMENT_SHADER = 0x8b30 gl.FRAGMENT_SHADER_BIT_EXT = 0x2 gl.FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8b8b gl.FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT = 0x8a52 gl.FRAMEBUFFER = 0x8d40 gl.FRAMEBUFFER_ATTACHMENT_ANGLE = 0x93a3 gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 0x8210 gl.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211 gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1 gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0 gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES = 0x8cd4 gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3 gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2 gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT = 0x8d6c gl.FRAMEBUFFER_BINDING = 0x8ca6 gl.FRAMEBUFFER_COMPLETE = 0x8cd5 gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6 gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9 gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE = 0x8d56 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE = 0x8d56 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT = 0x8d56 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG = 0x9134 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV = 0x8d56 gl.FRAMEBUFFER_UNDEFINED_OES = 0x8219 gl.FRAMEBUFFER_UNSUPPORTED = 0x8cdd gl.FRONT = 0x404 gl.FRONT_AND_BACK = 0x408 gl.FRONT_FACE = 0xb46 gl.FUNC_ADD = 0x8006 gl.FUNC_REVERSE_SUBTRACT = 0x800b gl.FUNC_SUBTRACT = 0x800a gl.GENERATE_MIPMAP_HINT = 0x8192 gl.GEQUAL = 0x206 gl.GPU_OPTIMIZED_QCOM = 0x8fb2 gl.GREATER = 0x204 gl.GREEN_BITS = 0xd53 gl.GUILTY_CONTEXT_RESET_EXT = 0x8253 gl.HALF_FLOAT_OES = 0x8d61 gl.HIGH_FLOAT = 0x8df2 gl.HIGH_INT = 0x8df5 gl.IMG_multisampled_render_to_texture = 0x1 gl.IMG_program_binary = 0x1 gl.IMG_read_format = 0x1 gl.IMG_shader_binary = 0x1 gl.IMG_texture_compression_pvrtc = 0x1 gl.IMG_texture_compression_pvrtc2 = 0x1 gl.IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b gl.IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a gl.INCR = 0x1e02 gl.INCR_WRAP = 0x8507 gl.INFO_LOG_LENGTH = 0x8b84 gl.INNOCENT_CONTEXT_RESET_EXT = 0x8254 gl.INT = 0x1404 gl.INT_10_10_10_2_OES = 0x8df7 gl.INT_VEC2 = 0x8b53 gl.INT_VEC3 = 0x8b54 gl.INT_VEC4 = 0x8b55 gl.INVALID_ENUM = 0x500 gl.INVALID_FRAMEBUFFER_OPERATION = 0x506 gl.INVALID_OPERATION = 0x502 gl.INVALID_VALUE = 0x501 gl.INVERT = 0x150a gl.KEEP = 0x1e00 gl.KHR_debug = 0x1 gl.KHR_texture_compression_astc_ldr = 0x1 gl.LEQUAL = 0x203 gl.LESS = 0x201 gl.LINEAR = 0x2601 gl.LINEAR_MIPMAP_LINEAR = 0x2703 gl.LINEAR_MIPMAP_NEAREST = 0x2701 gl.LINES = 0x1 gl.LINE_LOOP = 0x2 gl.LINE_STRIP = 0x3 gl.LINE_WIDTH = 0xb21 gl.LINK_STATUS = 0x8b82 gl.LOSE_CONTEXT_ON_RESET_EXT = 0x8252 gl.LOW_FLOAT = 0x8df0 gl.LOW_INT = 0x8df3 gl.LUMINANCE = 0x1909 gl.LUMINANCE16F_EXT = 0x881e gl.LUMINANCE32F_EXT = 0x8818 gl.LUMINANCE4_ALPHA4_OES = 0x8043 gl.LUMINANCE8_ALPHA8_EXT = 0x8045 gl.LUMINANCE8_ALPHA8_OES = 0x8045 gl.LUMINANCE8_EXT = 0x8040 gl.LUMINANCE8_OES = 0x8040 gl.LUMINANCE_ALPHA = 0x190a gl.LUMINANCE_ALPHA16F_EXT = 0x881f gl.LUMINANCE_ALPHA32F_EXT = 0x8819 gl.MALI_PROGRAM_BINARY_ARM = 0x8f61 gl.MALI_SHADER_BINARY_ARM = 0x8f60 gl.MAP_FLUSH_EXPLICIT_BIT_EXT = 0x10 gl.MAP_INVALIDATE_BUFFER_BIT_EXT = 0x8 gl.MAP_INVALIDATE_RANGE_BIT_EXT = 0x4 gl.MAP_READ_BIT_EXT = 0x1 gl.MAP_UNSYNCHRONIZED_BIT_EXT = 0x20 gl.MAP_WRITE_BIT_EXT = 0x2 gl.MAX_3D_TEXTURE_SIZE_OES = 0x8073 gl.MAX_COLOR_ATTACHMENTS_NV = 0x8cdf gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d gl.MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c gl.MAX_DEBUG_GROUP_STACK_DEPTH = 0x826c gl.MAX_DEBUG_LOGGED_MESSAGES = 0x9144 gl.MAX_DEBUG_MESSAGE_LENGTH = 0x9143 gl.MAX_DRAW_BUFFERS_NV = 0x8824 gl.MAX_EXT = 0x8008 gl.MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd gl.MAX_LABEL_LENGTH = 0x82e8 gl.MAX_MULTIVIEW_BUFFERS_EXT = 0x90f2 gl.MAX_RENDERBUFFER_SIZE = 0x84e8 gl.MAX_SAMPLES_ANGLE = 0x8d57 gl.MAX_SAMPLES_APPLE = 0x8d57 gl.MAX_SAMPLES_EXT = 0x8d57 gl.MAX_SAMPLES_IMG = 0x9135 gl.MAX_SAMPLES_NV = 0x8d57 gl.MAX_SERVER_WAIT_TIMEOUT_APPLE = 0x9111 gl.MAX_TEXTURE_IMAGE_UNITS = 0x8872 gl.MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff gl.MAX_TEXTURE_SIZE = 0xd33 gl.MAX_VARYING_VECTORS = 0x8dfc gl.MAX_VERTEX_ATTRIBS = 0x8869 gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c gl.MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb gl.MAX_VIEWPORT_DIMS = 0xd3a gl.MEDIUM_FLOAT = 0x8df1 gl.MEDIUM_INT = 0x8df4 gl.MIN_EXT = 0x8007 gl.MIRRORED_REPEAT = 0x8370 gl.MULTISAMPLE_BUFFER_BIT0_QCOM = 0x1000000 gl.MULTISAMPLE_BUFFER_BIT1_QCOM = 0x2000000 gl.MULTISAMPLE_BUFFER_BIT2_QCOM = 0x4000000 gl.MULTISAMPLE_BUFFER_BIT3_QCOM = 0x8000000 gl.MULTISAMPLE_BUFFER_BIT4_QCOM = 0x10000000 gl.MULTISAMPLE_BUFFER_BIT5_QCOM = 0x20000000 gl.MULTISAMPLE_BUFFER_BIT6_QCOM = 0x40000000 gl.MULTISAMPLE_BUFFER_BIT7_QCOM = 0x80000000 gl.MULTIVIEW_EXT = 0x90f1 gl.NEAREST = 0x2600 gl.NEAREST_MIPMAP_LINEAR = 0x2702 gl.NEAREST_MIPMAP_NEAREST = 0x2700 gl.NEVER = 0x200 gl.NICEST = 0x1102 gl.NONE = 0x0 gl.NOTEQUAL = 0x205 gl.NO_ERROR = 0x0 gl.NO_RESET_NOTIFICATION_EXT = 0x8261 gl.NUM_COMPRESSED_TEXTURE_FORMATS = 0x86a2 gl.NUM_PROGRAM_BINARY_FORMATS_OES = 0x87fe gl.NUM_SHADER_BINARY_FORMATS = 0x8df9 gl.NV_coverage_sample = 0x1 gl.NV_depth_nonlinear = 0x1 gl.NV_draw_buffers = 0x1 gl.NV_draw_instanced = 0x1 gl.NV_fbo_color_attachments = 0x1 gl.NV_fence = 0x1 gl.NV_framebuffer_blit = 0x1 gl.NV_framebuffer_multisample = 0x1 gl.NV_generate_mipmap_sRGB = 0x1 gl.NV_instanced_arrays = 0x1 gl.NV_read_buffer = 0x1 gl.NV_read_buffer_front = 0x1 gl.NV_read_depth = 0x1 gl.NV_read_depth_stencil = 0x1 gl.NV_read_stencil = 0x1 gl.NV_sRGB_formats = 0x1 gl.NV_shadow_samplers_array = 0x1 gl.NV_shadow_samplers_cube = 0x1 gl.NV_texture_border_clamp = 0x1 gl.NV_texture_compression_s3tc_update = 0x1 gl.NV_texture_npot_2D_mipmap = 0x1 gl.OBJECT_TYPE_APPLE = 0x9112 gl.OES_EGL_image = 0x1 gl.OES_EGL_image_external = 0x1 gl.OES_compressed_ETC1_RGB8_texture = 0x1 gl.OES_compressed_paletted_texture = 0x1 gl.OES_depth24 = 0x1 gl.OES_depth32 = 0x1 gl.OES_depth_texture = 0x1 gl.OES_element_index_uint = 0x1 gl.OES_fbo_render_mipmap = 0x1 gl.OES_fragment_precision_high = 0x1 gl.OES_get_program_binary = 0x1 gl.OES_mapbuffer = 0x1 gl.OES_packed_depth_stencil = 0x1 gl.OES_required_internalformat = 0x1 gl.OES_rgb8_rgba8 = 0x1 gl.OES_standard_derivatives = 0x1 gl.OES_stencil1 = 0x1 gl.OES_stencil4 = 0x1 gl.OES_surfaceless_context = 0x1 gl.OES_texture_3D = 0x1 gl.OES_texture_float = 0x1 gl.OES_texture_float_linear = 0x1 gl.OES_texture_half_float = 0x1 gl.OES_texture_half_float_linear = 0x1 gl.OES_texture_npot = 0x1 gl.OES_vertex_array_object = 0x1 gl.OES_vertex_half_float = 0x1 gl.OES_vertex_type_10_10_10_2 = 0x1 gl.ONE = 0x1 gl.ONE_MINUS_CONSTANT_ALPHA = 0x8004 gl.ONE_MINUS_CONSTANT_COLOR = 0x8002 gl.ONE_MINUS_DST_ALPHA = 0x305 gl.ONE_MINUS_DST_COLOR = 0x307 gl.ONE_MINUS_SRC_ALPHA = 0x303 gl.ONE_MINUS_SRC_COLOR = 0x301 gl.OUT_OF_MEMORY = 0x505 gl.PACK_ALIGNMENT = 0xd05 gl.PACK_REVERSE_ROW_ORDER_ANGLE = 0x93a4 gl.PALETTE4_R5_G6_B5_OES = 0x8b92 gl.PALETTE4_RGB5_A1_OES = 0x8b94 gl.PALETTE4_RGB8_OES = 0x8b90 gl.PALETTE4_RGBA4_OES = 0x8b93 gl.PALETTE4_RGBA8_OES = 0x8b91 gl.PALETTE8_R5_G6_B5_OES = 0x8b97 gl.PALETTE8_RGB5_A1_OES = 0x8b99 gl.PALETTE8_RGB8_OES = 0x8b95 gl.PALETTE8_RGBA4_OES = 0x8b98 gl.PALETTE8_RGBA8_OES = 0x8b96 gl.PERCENTAGE_AMD = 0x8bc3 gl.PERFMON_GLOBAL_MODE_QCOM = 0x8fa0 gl.PERFMON_RESULT_AMD = 0x8bc6 gl.PERFMON_RESULT_AVAILABLE_AMD = 0x8bc4 gl.PERFMON_RESULT_SIZE_AMD = 0x8bc5 gl.POINTS = 0x0 gl.POLYGON_OFFSET_FACTOR = 0x8038 gl.POLYGON_OFFSET_FILL = 0x8037 gl.POLYGON_OFFSET_UNITS = 0x2a00 gl.PROGRAM = 0x82e2 gl.PROGRAM_BINARY_ANGLE = 0x93a6 gl.PROGRAM_BINARY_FORMATS_OES = 0x87ff gl.PROGRAM_BINARY_LENGTH_OES = 0x8741 gl.PROGRAM_OBJECT_EXT = 0x8b40 gl.PROGRAM_PIPELINE_BINDING_EXT = 0x825a gl.PROGRAM_PIPELINE_OBJECT_EXT = 0x8a4f gl.PROGRAM_SEPARABLE_EXT = 0x8258 gl.QCOM_alpha_test = 0x1 gl.QCOM_binning_control = 0x1 gl.QCOM_driver_control = 0x1 gl.QCOM_extended_get = 0x1 gl.QCOM_extended_get2 = 0x1 gl.QCOM_perfmon_global_mode = 0x1 gl.QCOM_tiled_rendering = 0x1 gl.QCOM_writeonly_rendering = 0x1 gl.QUERY = 0x82e3 gl.QUERY_OBJECT_EXT = 0x9153 gl.QUERY_RESULT_AVAILABLE_EXT = 0x8867 gl.QUERY_RESULT_EXT = 0x8866 gl.R16F_EXT = 0x822d gl.R32F_EXT = 0x822e gl.R8_EXT = 0x8229 gl.READ_BUFFER_EXT = 0xc02 gl.READ_BUFFER_NV = 0xc02 gl.READ_FRAMEBUFFER_ANGLE = 0x8ca8 gl.READ_FRAMEBUFFER_APPLE = 0x8ca8 gl.READ_FRAMEBUFFER_BINDING_ANGLE = 0x8caa gl.READ_FRAMEBUFFER_BINDING_APPLE = 0x8caa gl.READ_FRAMEBUFFER_BINDING_NV = 0x8caa gl.READ_FRAMEBUFFER_NV = 0x8ca8 gl.RED_BITS = 0xd52 gl.RED_EXT = 0x1903 gl.RENDERBUFFER = 0x8d41 gl.RENDERBUFFER_ALPHA_SIZE = 0x8d53 gl.RENDERBUFFER_BINDING = 0x8ca7 gl.RENDERBUFFER_BLUE_SIZE = 0x8d52 gl.RENDERBUFFER_DEPTH_SIZE = 0x8d54 gl.RENDERBUFFER_GREEN_SIZE = 0x8d51 gl.RENDERBUFFER_HEIGHT = 0x8d43 gl.RENDERBUFFER_INTERNAL_FORMAT = 0x8d44 gl.RENDERBUFFER_RED_SIZE = 0x8d50 gl.RENDERBUFFER_SAMPLES_ANGLE = 0x8cab gl.RENDERBUFFER_SAMPLES_APPLE = 0x8cab gl.RENDERBUFFER_SAMPLES_EXT = 0x8cab gl.RENDERBUFFER_SAMPLES_IMG = 0x9133 gl.RENDERBUFFER_SAMPLES_NV = 0x8cab gl.RENDERBUFFER_STENCIL_SIZE = 0x8d55 gl.RENDERBUFFER_WIDTH = 0x8d42 gl.RENDERER = 0x1f01 gl.RENDER_DIRECT_TO_FRAMEBUFFER_QCOM = 0x8fb3 gl.REPEAT = 0x2901 gl.REPLACE = 0x1e01 gl.REQUIRED_TEXTURE_IMAGE_UNITS_OES = 0x8d68 gl.RESET_NOTIFICATION_STRATEGY_EXT = 0x8256 gl.RG16F_EXT = 0x822f gl.RG32F_EXT = 0x8230 gl.RG8_EXT = 0x822b gl.RGB = 0x1907 gl.RGB10_A2_EXT = 0x8059 gl.RGB10_EXT = 0x8052 gl.RGB16F_EXT = 0x881b gl.RGB32F_EXT = 0x8815 gl.RGB565 = 0x8d62 gl.RGB565_OES = 0x8d62 gl.RGB5_A1 = 0x8057 gl.RGB5_A1_OES = 0x8057 gl.RGB8_OES = 0x8051 gl.RGBA = 0x1908 gl.RGBA16F_EXT = 0x881a gl.RGBA32F_EXT = 0x8814 gl.RGBA4 = 0x8056 gl.RGBA4_OES = 0x8056 gl.RGBA8_OES = 0x8058 gl.RGB_422_APPLE = 0x8a1f gl.RG_EXT = 0x8227 gl.SAMPLER = 0x82e6 gl.SAMPLER_2D = 0x8b5e gl.SAMPLER_2D_ARRAY_SHADOW_NV = 0x8dc4 gl.SAMPLER_2D_SHADOW_EXT = 0x8b62 gl.SAMPLER_3D_OES = 0x8b5f gl.SAMPLER_CUBE = 0x8b60 gl.SAMPLER_CUBE_SHADOW_NV = 0x8dc5 gl.SAMPLER_EXTERNAL_OES = 0x8d66 gl.SAMPLES = 0x80a9 gl.SAMPLE_ALPHA_TO_COVERAGE = 0x809e gl.SAMPLE_BUFFERS = 0x80a8 gl.SAMPLE_COVERAGE = 0x80a0 gl.SAMPLE_COVERAGE_INVERT = 0x80ab gl.SAMPLE_COVERAGE_VALUE = 0x80aa gl.SCISSOR_BOX = 0xc10 gl.SCISSOR_TEST = 0xc11 gl.SGX_BINARY_IMG = 0x8c0a gl.SGX_PROGRAM_BINARY_IMG = 0x9130 gl.SHADER = 0x82e1 gl.SHADER_BINARY_DMP = 0x9250 gl.SHADER_BINARY_FORMATS = 0x8df8 gl.SHADER_BINARY_VIV = 0x8fc4 gl.SHADER_COMPILER = 0x8dfa gl.SHADER_OBJECT_EXT = 0x8b48 gl.SHADER_SOURCE_LENGTH = 0x8b88 gl.SHADER_TYPE = 0x8b4f gl.SHADING_LANGUAGE_VERSION = 0x8b8c gl.SHORT = 0x1402 gl.SIGNALED_APPLE = 0x9119 gl.SLUMINANCE8_ALPHA8_NV = 0x8c45 gl.SLUMINANCE8_NV = 0x8c47 gl.SLUMINANCE_ALPHA_NV = 0x8c44 gl.SLUMINANCE_NV = 0x8c46 gl.SRC_ALPHA = 0x302 gl.SRC_ALPHA_SATURATE = 0x308 gl.SRC_COLOR = 0x300 gl.SRGB8_ALPHA8_EXT = 0x8c43 gl.SRGB8_NV = 0x8c41 gl.SRGB_ALPHA_EXT = 0x8c42 gl.SRGB_EXT = 0x8c40 gl.STACK_OVERFLOW = 0x503 gl.STACK_UNDERFLOW = 0x504 gl.STATE_RESTORE = 0x8bdc gl.STATIC_DRAW = 0x88e4 gl.STENCIL_ATTACHMENT = 0x8d20 gl.STENCIL_BACK_FAIL = 0x8801 gl.STENCIL_BACK_FUNC = 0x8800 gl.STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802 gl.STENCIL_BACK_PASS_DEPTH_PASS = 0x8803 gl.STENCIL_BACK_REF = 0x8ca3 gl.STENCIL_BACK_VALUE_MASK = 0x8ca4 gl.STENCIL_BACK_WRITEMASK = 0x8ca5 gl.STENCIL_BITS = 0xd57 gl.STENCIL_BUFFER_BIT = 0x400 gl.STENCIL_BUFFER_BIT0_QCOM = 0x10000 gl.STENCIL_BUFFER_BIT1_QCOM = 0x20000 gl.STENCIL_BUFFER_BIT2_QCOM = 0x40000 gl.STENCIL_BUFFER_BIT3_QCOM = 0x80000 gl.STENCIL_BUFFER_BIT4_QCOM = 0x100000 gl.STENCIL_BUFFER_BIT5_QCOM = 0x200000 gl.STENCIL_BUFFER_BIT6_QCOM = 0x400000 gl.STENCIL_BUFFER_BIT7_QCOM = 0x800000 gl.STENCIL_CLEAR_VALUE = 0xb91 gl.STENCIL_EXT = 0x1802 gl.STENCIL_FAIL = 0xb94 gl.STENCIL_FUNC = 0xb92 gl.STENCIL_INDEX1_OES = 0x8d46 gl.STENCIL_INDEX4_OES = 0x8d47 gl.STENCIL_INDEX8 = 0x8d48 gl.STENCIL_PASS_DEPTH_FAIL = 0xb95 gl.STENCIL_PASS_DEPTH_PASS = 0xb96 gl.STENCIL_REF = 0xb97 gl.STENCIL_TEST = 0xb90 gl.STENCIL_VALUE_MASK = 0xb93 gl.STENCIL_WRITEMASK = 0xb98 gl.STREAM_DRAW = 0x88e0 gl.SUBPIXEL_BITS = 0xd50 gl.SYNC_CONDITION_APPLE = 0x9113 gl.SYNC_FENCE_APPLE = 0x9116 gl.SYNC_FLAGS_APPLE = 0x9115 gl.SYNC_FLUSH_COMMANDS_BIT_APPLE = 0x1 gl.SYNC_GPU_COMMANDS_COMPLETE_APPLE = 0x9117 gl.SYNC_OBJECT_APPLE = 0x8a53 gl.SYNC_STATUS_APPLE = 0x9114 gl.TEXTURE = 0x1702 gl.TEXTURE0 = 0x84c0 gl.TEXTURE1 = 0x84c1 gl.TEXTURE10 = 0x84ca gl.TEXTURE11 = 0x84cb gl.TEXTURE12 = 0x84cc gl.TEXTURE13 = 0x84cd gl.TEXTURE14 = 0x84ce gl.TEXTURE15 = 0x84cf gl.TEXTURE16 = 0x84d0 gl.TEXTURE17 = 0x84d1 gl.TEXTURE18 = 0x84d2 gl.TEXTURE19 = 0x84d3 gl.TEXTURE2 = 0x84c2 gl.TEXTURE20 = 0x84d4 gl.TEXTURE21 = 0x84d5 gl.TEXTURE22 = 0x84d6 gl.TEXTURE23 = 0x84d7 gl.TEXTURE24 = 0x84d8 gl.TEXTURE25 = 0x84d9 gl.TEXTURE26 = 0x84da gl.TEXTURE27 = 0x84db gl.TEXTURE28 = 0x84dc gl.TEXTURE29 = 0x84dd gl.TEXTURE3 = 0x84c3 gl.TEXTURE30 = 0x84de gl.TEXTURE31 = 0x84df gl.TEXTURE4 = 0x84c4 gl.TEXTURE5 = 0x84c5 gl.TEXTURE6 = 0x84c6 gl.TEXTURE7 = 0x84c7 gl.TEXTURE8 = 0x84c8 gl.TEXTURE9 = 0x84c9 gl.TEXTURE_2D = 0xde1 gl.TEXTURE_3D_OES = 0x806f gl.TEXTURE_BINDING_2D = 0x8069 gl.TEXTURE_BINDING_3D_OES = 0x806a gl.TEXTURE_BINDING_CUBE_MAP = 0x8514 gl.TEXTURE_BINDING_EXTERNAL_OES = 0x8d67 gl.TEXTURE_BORDER_COLOR_NV = 0x1004 gl.TEXTURE_COMPARE_FUNC_EXT = 0x884d gl.TEXTURE_COMPARE_MODE_EXT = 0x884c gl.TEXTURE_CUBE_MAP = 0x8513 gl.TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516 gl.TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518 gl.TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a gl.TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515 gl.TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517 gl.TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519 gl.TEXTURE_DEPTH_QCOM = 0x8bd4 gl.TEXTURE_EXTERNAL_OES = 0x8d65 gl.TEXTURE_FORMAT_QCOM = 0x8bd6 gl.TEXTURE_HEIGHT_QCOM = 0x8bd3 gl.TEXTURE_IMAGE_VALID_QCOM = 0x8bd8 gl.TEXTURE_IMMUTABLE_FORMAT_EXT = 0x912f gl.TEXTURE_INTERNAL_FORMAT_QCOM = 0x8bd5 gl.TEXTURE_MAG_FILTER = 0x2800 gl.TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe gl.TEXTURE_MAX_LEVEL_APPLE = 0x813d gl.TEXTURE_MIN_FILTER = 0x2801 gl.TEXTURE_NUM_LEVELS_QCOM = 0x8bd9 gl.TEXTURE_OBJECT_VALID_QCOM = 0x8bdb gl.TEXTURE_SAMPLES_IMG = 0x9136 gl.TEXTURE_TARGET_QCOM = 0x8bda gl.TEXTURE_TYPE_QCOM = 0x8bd7 gl.TEXTURE_USAGE_ANGLE = 0x93a2 gl.TEXTURE_WIDTH_QCOM = 0x8bd2 gl.TEXTURE_WRAP_R_OES = 0x8072 gl.TEXTURE_WRAP_S = 0x2802 gl.TEXTURE_WRAP_T = 0x2803 gl.TIMEOUT_EXPIRED_APPLE = 0x911b gl.TIMEOUT_IGNORED_APPLE = 0xffffffffffffffff gl.TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE = 0x93a0 gl.TRIANGLES = 0x4 gl.TRIANGLE_FAN = 0x6 gl.TRIANGLE_STRIP = 0x5 gl.TRUE = 0x1 gl.UNKNOWN_CONTEXT_RESET_EXT = 0x8255 gl.UNPACK_ALIGNMENT = 0xcf5 gl.UNPACK_ROW_LENGTH = 0xcf2 gl.UNPACK_SKIP_PIXELS = 0xcf4 gl.UNPACK_SKIP_ROWS = 0xcf3 gl.UNSIGNALED_APPLE = 0x9118 gl.UNSIGNED_BYTE = 0x1401 gl.UNSIGNED_INT = 0x1405 gl.UNSIGNED_INT64_AMD = 0x8bc2 gl.UNSIGNED_INT_10_10_10_2_OES = 0x8df6 gl.UNSIGNED_INT_24_8_OES = 0x84fa gl.UNSIGNED_INT_2_10_10_10_REV_EXT = 0x8368 gl.UNSIGNED_NORMALIZED_EXT = 0x8c17 gl.UNSIGNED_SHORT = 0x1403 gl.UNSIGNED_SHORT_1_5_5_5_REV_EXT = 0x8366 gl.UNSIGNED_SHORT_4_4_4_4 = 0x8033 gl.UNSIGNED_SHORT_4_4_4_4_REV_EXT = 0x8365 gl.UNSIGNED_SHORT_4_4_4_4_REV_IMG = 0x8365 gl.UNSIGNED_SHORT_5_5_5_1 = 0x8034 gl.UNSIGNED_SHORT_5_6_5 = 0x8363 gl.UNSIGNED_SHORT_8_8_APPLE = 0x85ba gl.UNSIGNED_SHORT_8_8_REV_APPLE = 0x85bb gl.VALIDATE_STATUS = 0x8b83 gl.VENDOR = 0x1f00 gl.VERSION = 0x1f02 gl.VERTEX_ARRAY_BINDING_OES = 0x85b5 gl.VERTEX_ARRAY_OBJECT_EXT = 0x9154 gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f gl.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88fe gl.VERTEX_ATTRIB_ARRAY_DIVISOR_NV = 0x88fe gl.VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622 gl.VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a gl.VERTEX_ATTRIB_ARRAY_POINTER = 0x8645 gl.VERTEX_ATTRIB_ARRAY_SIZE = 0x8623 gl.VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624 gl.VERTEX_ATTRIB_ARRAY_TYPE = 0x8625 gl.VERTEX_SHADER = 0x8b31 gl.VERTEX_SHADER_BIT_EXT = 0x1 gl.VIEWPORT = 0xba2 gl.VIV_shader_binary = 0x1 gl.WAIT_FAILED_APPLE = 0x911d gl.WRITEONLY_RENDERING_QCOM = 0x8823 gl.WRITE_ONLY_OES = 0x88b9 gl.Z400_BINARY_AMD = 0x8740 gl.ZERO = 0x0
mit
MustaphaTR/OpenRA
mods/d2k/maps/atreides-02a/atreides02a.lua
7
2649
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] HarkonnenBase = { HConyard, HPower1, HPower2, HBarracks } HarkonnenReinforcements = { easy = { { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" } }, normal = { { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" } }, hard = { { "trike", "trike" }, { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf" }, { "trike", "trike" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" }, { "trike", "trike" } } } HarkonnenAttackPaths = { { HarkonnenEntry1.Location, HarkonnenRally1.Location }, { HarkonnenEntry1.Location, HarkonnenRally3.Location }, { HarkonnenEntry2.Location, HarkonnenRally2.Location }, { HarkonnenEntry2.Location, HarkonnenRally4.Location } } HarkonnenAttackDelay = { easy = DateTime.Minutes(5), normal = DateTime.Minutes(2) + DateTime.Seconds(40), hard = DateTime.Minutes(1) + DateTime.Seconds(20) } HarkonnenAttackWaves = { easy = 3, normal = 6, hard = 9 } Tick = function() if player.HasNoRequiredUnits() then harkonnen.MarkCompletedObjective(KillAtreides) end if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat") player.MarkCompletedObjective(KillHarkonnen) end end WorldLoaded = function() harkonnen = Player.GetPlayer("Harkonnen") player = Player.GetPlayer("Atreides") InitObjectives(player) KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.") KillHarkonnen = player.AddPrimaryObjective("Destroy all Harkonnen forces.") Camera.Position = AConyard.CenterPosition Trigger.OnAllKilled(HarkonnenBase, function() Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt) end) local path = function() return Utils.Random(HarkonnenAttackPaths) end SendCarryallReinforcements(harkonnen, 0, HarkonnenAttackWaves[Difficulty], HarkonnenAttackDelay[Difficulty], path, HarkonnenReinforcements[Difficulty]) Trigger.AfterDelay(0, ActivateAI) end
gpl-3.0
shahabsaf1/copy-infernal
plugins/meme.lua
637
5791
local helpers = require "OAuth.helpers" local _file_memes = './data/memes.lua' local _cache = {} local function post_petition(url, arguments) local response_body = {} local request_constructor = { url = url, method = "POST", sink = ltn12.sink.table(response_body), headers = {}, redirect = false } local source = arguments if type(arguments) == "table" then local source = helpers.url_encode_arguments(arguments) end request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded" request_constructor.headers["Content-Length"] = tostring(#source) request_constructor.source = ltn12.source.string(source) local ok, response_code, response_headers, response_status_line = http.request(request_constructor) if not ok then return nil end response_body = json:decode(table.concat(response_body)) return response_body end local function upload_memes(memes) local base = "http://hastebin.com/" local pet = post_petition(base .. "documents", memes) if pet == nil then return '', '' end local key = pet.key return base .. key, base .. 'raw/' .. key end local function analyze_meme_list() local function get_m(res, n) local r = "<option.*>(.*)</option>.*" local start = string.find(res, "<option.*>", n) if start == nil then return nil, nil end local final = string.find(res, "</option>", n) + #"</option>" local sub = string.sub(res, start, final) local f = string.match(sub, r) return f, final end local res, code = http.request('http://apimeme.com/') local r = "<option.*>(.*)</option>.*" local n = 0 local f, n = get_m(res, n) local ult = {} while f ~= nil do print(f) table.insert(ult, f) f, n = get_m(res, n) end return ult end local function get_memes() local memes = analyze_meme_list() return { last_time = os.time(), memes = memes } end local function load_data() local data = load_from_file(_file_memes) if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then data = get_memes() -- Upload only if changed? link, rawlink = upload_memes(table.concat(data.memes, '\n')) data.link = link data.rawlink = rawlink serialize_to_file(data, _file_memes) end return data end local function match_n_word(list1, list2) local n = 0 for k,v in pairs(list1) do for k2, v2 in pairs(list2) do if v2:find(v) then n = n + 1 end end end return n end local function match_meme(name) local _memes = load_data() local name = name:lower():split(' ') local max = 0 local id = nil for k,v in pairs(_memes.memes) do local n = match_n_word(name, v:lower():split(' ')) if n > 0 and n > max then max = n id = v end end return id end local function generate_meme(id, textup, textdown) local base = "http://apimeme.com/meme" local arguments = { meme=id, top=textup, bottom=textdown } return base .. "?" .. helpers.url_encode_arguments(arguments) end local function get_all_memes_names() local _memes = load_data() local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n' for k, v in pairs(_memes.memes) do text = text .. '- ' .. v .. '\n' end text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/' return text end local function callback_send(cb_extra, success, data) if success == 0 then send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false) end end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == 'list' then local _memes = load_data() return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link elseif matches[1] == 'listall' then if not is_sudo(msg) then return "You can't list this way, use \"!meme list\"" else return get_all_memes_names() end elseif matches[1] == "search" then local meme_id = match_meme(matches[2]) if meme_id == nil then return "I can't match that search with any meme." end return "With that search your meme is " .. meme_id end local searchterm = string.gsub(matches[1]:lower(), ' ', '') local meme_id = _cache[searchterm] or match_meme(matches[1]) if not meme_id then return 'I don\'t understand the meme name "' .. matches[1] .. '"' end _cache[searchterm] = meme_id print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3]) local url_gen = generate_meme(meme_id, matches[2], matches[3]) send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen}) return nil end return { description = "Generate a meme image with up and bottom texts.", usage = { "!meme search (name): Return the name of the meme that match.", "!meme list: Return the link where you can see the memes.", "!meme listall: Return the list of all memes. Only admin can call it.", '!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.', '!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.', }, patterns = { "^!meme (search) (.+)$", '^!meme (list)$', '^!meme (listall)$', '^!meme (.+) "(.*)" "(.*)"$', '^!meme "(.+)" "(.*)" "(.*)"$', "^!meme (.+) %- (.*) %- (.*)$" }, run = run }
gpl-2.0
Ali-2h/wwefucker
plugins/search_youtube.lua
674
1270
do local google_config = load_from_file('data/google.lua') local function httpsRequest(url) print(url) local res,code = https.request(url) if code ~= 200 then return nil end return json:decode(res) end local function searchYoutubeVideos(text) local url = 'https://www.googleapis.com/youtube/v3/search?' url = url..'part=snippet'..'&maxResults=4'..'&type=video' url = url..'&q='..URL.escape(text) if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local data = httpsRequest(url) if not data then print("HTTP Error") return nil elseif not data.items then return nil end return data.items end local function run(msg, matches) local text = '' local items = searchYoutubeVideos(matches[1]) if not items then return "Error!" end for k,item in pairs(items) do text = text..'http://youtu.be/'..item.id.videoId..' '.. item.snippet.title..'\n\n' end return text end return { description = "Search video on youtube and send it.", usage = "!youtube [term]: Search for a youtube video and send it.", patterns = { "^!youtube (.*)" }, run = run } end
gpl-2.0
ArianWatch/SportTG
plugins/tophoto.lua
24
1059
local function tosticker(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/stickers/'..msg.from.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) send_photo(get_receiver(msg), file, ok_cb, false) redis:del("sticker:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id if msg.media then if msg.media.type == 'document' and is_momod(msg) and redis:get("sticker:photo") then if redis:get("sticker:photo") == 'waiting' then load_document(msg.id, tosticker, msg) end end end if matches[1] == "tophoto" and is_momod(msg) then redis:set("sticker:photo", "waiting") return 'Please send your sticker now' end end return { patterns = { "^[!/](tophoto)$", "%[(document)%]", }, run = run, }
gpl-2.0
rafaeu749/ProjectPorcupine
Assets/StreamingAssets/LUA/Furniture.lua
2
24728
------------------------------------------------------- -- Project Porcupine Copyright(C) 2016 Team Porcupine -- This program comes with ABSOLUTELY NO WARRANTY; This is free software, -- and you are welcome to redistribute it under certain conditions; See -- file LICENSE, which is part of this source code package, for details. ------------------------------------------------------- -- TODO: Figure out the nicest way to have unified defines/enums -- between C# and Lua so we don't have to duplicate anything. ENTERABILITY_YES = 0 ENTERABILITY_NO = 1 ENTERABILITY_SOON = 2 -- HOWTO Log: -- ModUtils.ULog("Testing ModUtils.ULogChannel") -- ModUtils.ULogWarning("Testing ModUtils.ULogWarningChannel") -- ModUtils.ULogError("Testing ModUtils.ULogErrorChannel") -- Note: pauses the game -------------------------------- Furniture Actions -------------------------------- function OnUpdate_GasGenerator( furniture, deltaTime ) if ( furniture.Tile.Room == nil ) then return "Furniture's room was null." end local keys = furniture.Parameters["gas_gen"].Keys() for discard, key in pairs(keys) do if ( furniture.Tile.Room.GetGasPressure(key) < furniture.Parameters["gas_gen"][key]["gas_limit"].ToFloat()) then furniture.Tile.Room.ChangeGas(key, furniture.Parameters["gas_per_second"].ToFloat() * deltaTime * furniture.Parameters["gas_gen"][key]["gas_limit"].ToFloat()) else -- Do we go into a standby mode to save power? end end return end function OnUpdate_Door( furniture, deltaTime ) if (furniture.Parameters["is_opening"].ToFloat() >= 1.0) then furniture.Parameters["openness"].ChangeFloatValue(deltaTime * 4) -- FIXME: Maybe a door open speed parameter? if (furniture.Parameters["openness"].ToFloat() >= 1) then furniture.Parameters["is_opening"].SetValue(0) end else furniture.Parameters["openness"].ChangeFloatValue(deltaTime * -4) end furniture.Parameters["openness"].SetValue( ModUtils.Clamp01(furniture.Parameters["openness"].ToFloat()) ) furniture.UpdateOnChanged(furniture); end function OnUpdate_AirlockDoor( furniture, deltaTime ) if (furniture.Parameters["pressure_locked"].ToFloat() >= 1.0) then local neighbors = furniture.Tile.GetNeighbours(false) local adjacentRooms = {} local pressureEqual = true; local count = 0 for k, tile in pairs(neighbors) do if (tile.Room != nil) then count = count + 1 adjacentRooms[count] = tile.Room end end if(ModUtils.Round(adjacentRooms[1].GetTotalGasPressure(),3) == ModUtils.Round(adjacentRooms[2].GetTotalGasPressure(),3)) then OnUpdate_Door(furniture, deltaTime) end else OnUpdate_Door(furniture, deltaTime) end end function AirlockDoor_Toggle_Pressure_Lock(furniture, character) ModUtils.ULog("Toggling Pressure Lock") if (furniture.Parameters["pressure_locked"].ToFloat() == 1) then furniture.Parameters["pressure_locked"].SetValue(0) else furniture.Parameters["pressure_locked"].SetValue(1) end ModUtils.ULog(furniture.Parameters["pressure_locked"].ToFloat()) end function OnUpdate_Leak_Door( furniture, deltaTime ) furniture.Tile.EqualiseGas(deltaTime * 10.0 * (furniture.Parameters["openness"].ToFloat() + 0.1)) end function OnUpdate_Leak_Airlock( furniture, deltaTime ) furniture.Tile.EqualiseGas(deltaTime * 10.0 * (furniture.Parameters["openness"].ToFloat())) end function IsEnterable_Door( furniture ) furniture.Parameters["is_opening"].SetValue(1) if (furniture.Parameters["openness"].ToFloat() >= 1) then return ENTERABILITY_YES --ENTERABILITY.Yes end return ENTERABILITY_SOON --ENTERABILITY.Soon end function GetSpriteName_Door( furniture ) local openness = furniture.Parameters["openness"].ToFloat() if (furniture.verticalDoor == true) then -- Door is closed if (openness < 0.1) then return "DoorVertical_0" end if (openness < 0.25) then return "DoorVertical_1" end if (openness < 0.5) then return "DoorVertical_2" end if (openness < 0.75) then return "DoorVertical_3" end if (openness < 0.9) then return "DoorVertical_4" end -- Door is a fully open return "DoorVertical_5" end -- Door is closed if (openness < 0.1) then return "DoorHorizontal_0" end if (openness < 0.25) then return "DoorHorizontal_1" end if (openness < 0.5) then return "DoorHorizontal_2" end if (openness < 0.75) then return "DoorHorizontal_3" end if (openness < 0.9) then return "DoorHorizontal_4" end -- Door is a fully open return "DoorHorizontal_5" end function GetSpriteName_Airlock( furniture ) local openness = furniture.Parameters["openness"].ToFloat() -- Door is closed if (openness < 0.1) then return "Airlock" end -- Door is a bit open if (openness < 0.5) then return "Airlock_openness_1" end -- Door is a lot open if (openness < 0.9) then return "Airlock_openness_2" end -- Door is a fully open return "Airlock_openness_3" end function Stockpile_GetItemsFromFilter( furniture ) -- TODO: This should be reading from some kind of UI for this -- particular stockpile -- Probably, this doesn't belong in Lua at all and instead we should -- just be calling a C# function to give us the list. -- Since jobs copy arrays automatically, we could already have -- an Inventory[] prepared and just return that (as a sort of example filter) --return { Inventory.__new("Steel Plate", 50, 0) } return furniture.AcceptsForStorage() end function Stockpile_UpdateAction( furniture, deltaTime ) -- We need to ensure that we have a job on the queue -- asking for either: -- (if we are empty): That ANY loose inventory be brought to us. -- (if we have something): Then IF we are still below the max stack size, -- that more of the same should be brought to us. -- TODO: This function doesn't need to run each update. Once we get a lot -- of furniture in a running game, this will run a LOT more than required. -- Instead, it only really needs to run whenever: -- -- It gets created -- -- A good gets delivered (at which point we reset the job) -- -- A good gets picked up (at which point we reset the job) -- -- The UI's filter of allowed items gets changed if( furniture.Tile.Inventory != nil and furniture.Tile.Inventory.StackSize >= furniture.Tile.Inventory.MaxStackSize ) then -- We are full! furniture.CancelJobs() return end -- Maybe we already have a job queued up? if( furniture.JobCount() > 0 ) then -- Cool, all done. return end -- We Currently are NOT full, but we don't have a job either. -- Two possibilities: Either we have SOME inventory, or we have NO inventory. -- Third possibility: Something is WHACK if( furniture.Tile.Inventory != nil and furniture.Tile.Inventory.StackSize == 0 ) then furniture.CancelJobs() return "Stockpile has a zero-size stack. This is clearly WRONG!" end -- TODO: In the future, stockpiles -- rather than being a bunch of individual -- 1x1 tiles -- should manifest themselves as single, large objects. This -- would respresent our first and probably only VARIABLE sized "furniture" -- -- at what happenes if there's a "hole" in our stockpile because we have an -- actual piece of furniture (like a cooking stating) installed in the middle -- of our stockpile? -- In any case, once we implement "mega stockpiles", then the job-creation system -- could be a lot smarter, in that even if the stockpile has some stuff in it, it -- can also still be requestion different object types in its job creation. local itemsDesired = {} if( furniture.Tile.Inventory == nil ) then --ModUtils.ULog("Creating job for new stack.") itemsDesired = Stockpile_GetItemsFromFilter( furniture ) else --ModUtils.ULog("Creating job for existing stack.") desInv = furniture.Tile.Inventory.Clone() desInv.MaxStackSize = desInv.MaxStackSize - desInv.StackSize desInv.StackSize = 0 itemsDesired = { desInv } end local j = Job.__new( furniture.Tile, nil, nil, 0, itemsDesired, Job.JobPriority.Low, false ) j.JobDescription = "job_stockpile_moving_desc" j.acceptsAny = true -- TODO: Later on, add stockpile priorities, so that we can take from a lower -- priority stockpile for a higher priority one. j.canTakeFromStockpile = false j.RegisterJobWorkedCallback("Stockpile_JobWorked") furniture.AddJob( j ) end function Stockpile_JobWorked(j) j.CancelJob() -- TODO: Change this when we figure out what we're doing for the all/any pickup job. --values = j.GetInventoryRequirementValues(); for k, inv in pairs(j.inventoryRequirements) do if(inv.StackSize > 0) then World.Current.inventoryManager.PlaceInventory(j.tile, inv) return -- There should be no way that we ever end up with more than on inventory requirement with StackSize > 0 end end end function MiningDroneStation_UpdateAction( furniture, deltaTime ) local spawnSpot = furniture.GetSpawnSpotTile() if( furniture.JobCount() > 0 ) then -- Check to see if the Metal Plate destination tile is full. if( spawnSpot.Inventory != nil and spawnSpot.Inventory.StackSize >= spawnSpot.Inventory.MaxStackSize ) then -- We should stop this job, because it's impossible to make any more items. furniture.CancelJobs() end return end -- If we get here, then we have no Current job. Check to see if our destination is full. if( spawnSpot.Inventory != nil and spawnSpot.Inventory.StackSize >= spawnSpot.Inventory.MaxStackSize ) then -- We are full! Don't make a job! return end if(furniture.GetSpawnSpotTile().Inventory != nil and furniture.GetSpawnSpotTile().Inventory.Type != furniture.Parameters["mine_type"].ToString()) then return end -- If we get here, we need to CREATE a new job. local jobSpot = furniture.GetJobSpotTile() local j = Job.__new( jobSpot, nil, nil, 1, nil, Job.JobPriority.Medium, true -- This job repeats until the destination tile is full. ) j.RegisterJobCompletedCallback("MiningDroneStation_JobComplete") j.JobDescription = "job_mining_drone_station_mining_desc" furniture.AddJob( j ) end function MiningDroneStation_JobComplete(j) if (j.furniture.GetSpawnSpotTile().Inventory == nil or j.furniture.GetSpawnSpotTile().Inventory.Type == j.furniture.Parameters["mine_type"].ToString()) then World.Current.inventoryManager.PlaceInventory( j.furniture.GetSpawnSpotTile(), Inventory.__new(j.furniture.Parameters["mine_type"].ToString() , 2) ) else j.CancelJob() end end function MiningDroneStation_Change_to_Raw_Iron(furniture, character) furniture.Parameters["mine_type"].SetValue("Raw Iron") end function MiningDroneStation_Change_to_Raw_Copper(furniture, character) furniture.Parameters["mine_type"].SetValue("raw_copper") end function MetalSmelter_UpdateAction(furniture, deltaTime) local spawnSpot = furniture.GetSpawnSpotTile() if(spawnSpot.Inventory ~= nil and spawnSpot.Inventory.StackSize >= 5) then furniture.Parameters["smelttime"].ChangeFloatValue(deltaTime) if(furniture.Parameters["smelttime"].ToFloat() >= furniture.Parameters["smelttime_required"].ToFloat()) then furniture.Parameters["smelttime"].SetValue(0) local outputSpot = World.Current.GetTileAt(spawnSpot.X+2, spawnSpot.Y, spawnSpot.Z) if(outputSpot.Inventory == nil) then World.Current.inventoryManager.PlaceInventory(outputSpot, Inventory.__new("Steel Plate", 5)) spawnSpot.Inventory.StackSize = spawnSpot.Inventory.StackSize - 5 else if(outputSpot.Inventory.StackSize <= 45) then outputSpot.Inventory.StackSize = outputSpot.Inventory.StackSize + 5 spawnSpot.Inventory.StackSize = spawnSpot.Inventory.StackSize - 5 end end if(spawnSpot.Inventory.StackSize <= 0) then spawnSpot.Inventory = nil end end end if(spawnSpot.Inventory ~= nil and spawnSpot.Inventory.StackSize == spawnSpot.Inventory.MaxStackSize) then -- We have the max amount of resources, cancel the job. -- This check exists mainly, because the job completed callback doesn't -- seem to be reliable. furniture.CancelJobs() return end if(furniture.JobCount() > 0) then return end -- Create job depending on the already available stack size. local desiredStackSize = 50 local itemsDesired = { Inventory.__new("Raw Iron", 0, desiredStackSize) } if(spawnSpot.Inventory ~= nil and spawnSpot.Inventory.StackSize < spawnSpot.Inventory.MaxStackSize) then desiredStackSize = spawnSpot.Inventory.MaxStackSize - spawnSpot.Inventory.StackSize itemsDesired[1].MaxStackSize = desiredStackSize end ModUtils.ULog("MetalSmelter: Creating job for " .. desiredStackSize .. " raw iron.") local jobSpot = furniture.GetJobSpotTile() local j = Job.__new( jobSpot, nil, nil, 0.4, itemsDesired, Job.JobPriority.Medium, false ) j.RegisterJobWorkedCallback("MetalSmelter_JobWorked") furniture.AddJob(j) return end function MetalSmelter_JobWorked(j) j.CancelJob() local spawnSpot = j.tile.Furniture.GetSpawnSpotTile() for k, inv in pairs(j.inventoryRequirements) do if(inv ~= nil and inv.StackSize > 0) then World.Current.inventoryManager.PlaceInventory(spawnSpot, inv) spawnSpot.Inventory.Locked = true return end end end function CloningPod_UpdateAction(furniture, deltaTime) if( furniture.JobCount() > 0 ) then return end local j = Job.__new( furniture.GetJobSpotTile(), nil, nil, 10, nil, Job.JobPriority.Medium, false ) furniture.SetAnimationState("idle") j.RegisterJobWorkedCallback("CloningPod_JobRunning") j.RegisterJobCompletedCallback("CloningPod_JobComplete") j.JobDescription = "job_cloning_pod_cloning_desc" furniture.AddJob(j) end function CloningPod_JobRunning(j) j.furniture.SetAnimationState("running") end function CloningPod_JobComplete(j) World.Current.CreateCharacter(j.furniture.GetSpawnSpotTile()) j.furniture.Deconstruct() end function PowerGenerator_UpdateAction(furniture, deltatime) if (furniture.JobCount() < 1 and furniture.Parameters["burnTime"].ToFloat() == 0) then furniture.PowerConnection.OutputRate = 0 local itemsDesired = {Inventory.__new("Uranium", 0, 5)} local j = Job.__new( furniture.GetJobSpotTile(), nil, nil, 0.5, itemsDesired, Job.JobPriority.High, false ) j.RegisterJobCompletedCallback("PowerGenerator_JobComplete") j.JobDescription = "job_power_generator_fulling_desc" furniture.AddJob( j ) else furniture.Parameters["burnTime"].ChangeFloatValue(-deltatime) if ( furniture.Parameters["burnTime"].ToFloat() < 0 ) then furniture.Parameters["burnTime"].SetValue(0) end end if (furniture.Parameters["burnTime"].ToFloat() == 0) then furniture.SetAnimationState("idle") else furniture.SetAnimationState("running") end end function PowerGenerator_JobComplete( j ) j.furniture.Parameters["burnTime"].SetValue(j.furniture.Parameters["burnTimeRequired"].ToFloat()) j.furniture.PowerConnection.OutputRate = 5 end function LandingPad_Test_CallTradeShip(furniture, character) WorldController.Instance.TradeController.CallTradeShipTest(furniture) end -- This function gets called once, when the furniture is installed function Heater_InstallAction( furniture, deltaTime) -- TODO: find elegant way to register heat source and sinks to Temperature furniture.EventActions.Register("OnUpdateTemperature", "Heater_UpdateTemperature") World.Current.temperature.RegisterSinkOrSource(furniture) end -- This function gets called once, when the furniture is uninstalled function Heater_UninstallAction( furniture, deltaTime) furniture.EventActions.Deregister("OnUpdateTemperature", "Heater_UpdateTemperature") World.Current.temperature.DeregisterSinkOrSource(furniture) -- TODO: find elegant way to unregister previous register end function Heater_UpdateTemperature( furniture, deltaTime) if (furniture.tile.Room.IsOutsideRoom() == true) then return end tile = furniture.tile pressure = tile.Room.GetGasPressure() / tile.Room.GetSize() efficiency = ModUtils.Clamp01(pressure / furniture.Parameters["pressure_threshold"].ToFloat()) temperatureChangePerSecond = furniture.Parameters["base_heating"].ToFloat() * efficiency temperatureChange = temperatureChangePerSecond * deltaTime World.Current.temperature.ChangeTemperature(tile.X, tile.Y, temperatureChange) --ModUtils.ULogChannel("Temperature", "Heat change: " .. temperatureChangePerSecond .. " => " .. World.current.temperature.GetTemperature(tile.X, tile.Y)) end -- Should maybe later be integrated with GasGenerator function by -- someone who knows how that would work in this case function OxygenCompressor_OnUpdate(furniture, deltaTime) local room = furniture.Tile.Room local pressure = room.GetGasPressure("O2") local gasAmount = furniture.Parameters["flow_rate"].ToFloat() * deltaTime if (pressure < furniture.Parameters["give_threshold"].ToFloat()) then -- Expel gas if available if (furniture.Parameters["gas_content"].ToFloat() > 0) then furniture.Parameters["gas_content"].ChangeFloatValue(-gasAmount) room.ChangeGas("O2", gasAmount / room.GetSize()) furniture.UpdateOnChanged(furniture) end elseif (pressure > furniture.Parameters["take_threshold"].ToFloat()) then -- Suck in gas if not full if (furniture.Parameters["gas_content"].ToFloat() < furniture.Parameters["max_gas_content"].ToFloat()) then furniture.Parameters["gas_content"].ChangeFloatValue(gasAmount) room.ChangeGas("O2", -gasAmount / room.GetSize()) furniture.UpdateOnChanged(furniture) end end end function OxygenCompressor_GetSpriteName(furniture) local baseName = furniture.Type local suffix = 0 if (furniture.Parameters["gas_content"].ToFloat() > 0) then idxAsFloat = 8 * (furniture.Parameters["gas_content"].ToFloat() / furniture.Parameters["max_gas_content"].ToFloat()) suffix = ModUtils.FloorToInt(idxAsFloat) end return baseName .. "_" .. suffix end function SolarPanel_OnUpdate(furniture, deltaTime) local baseOutput = furniture.Parameters["base_output"].ToFloat() local efficiency = furniture.Parameters["efficiency"].ToFloat() local powerPerSecond = baseOutput * efficiency furniture.PowerConnection.OutputRate = powerPerSecond end function AirPump_OnUpdate(furniture, deltaTime) if (furniture.HasPower() == false) then return end local t = furniture.Tile local north = World.Current.GetTileAt(t.X, t.Y + 1, t.Z) local south = World.Current.GetTileAt(t.X, t.Y - 1, t.Z) local west = World.Current.GetTileAt(t.X - 1, t.Y, t.Z) local east = World.Current.GetTileAt(t.X + 1, t.Y, t.Z) -- Find the correct rooms for source and target -- Maybe in future this could be cached. it only changes when the direction changes local sourceRoom = nil local targetRoom = nil if (north.Room != nil and south.Room != nil) then if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then sourceRoom = south.Room targetRoom = north.Room else sourceRoom = north.Room targetRoom = south.Room end elseif (west.Room != nil and east.Room != nil) then if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then sourceRoom = west.Room targetRoom = east.Room else sourceRoom = east.Room targetRoom = west.Room end else ModUtils.UChannelLogWarning("Furniture", "Air Pump blocked. Direction unclear") return end local sourcePressureLimit = furniture.Parameters["source_pressure_limit"].ToFloat() local targetPressureLimit = furniture.Parameters["target_pressure_limit"].ToFloat() local flow = furniture.Parameters["gas_throughput"].ToFloat() * deltaTime -- Only transfer gas if the pressures are within the defined bounds if (sourceRoom.GetTotalGasPressure() > sourcePressureLimit and targetRoom.GetTotalGasPressure() < targetPressureLimit) then sourceRoom.MoveGasTo(targetRoom, flow) end end function AirPump_GetSpriteName(furniture) local t = furniture.Tile if (furniture.Tile == nil) then return furniture.Type end local north = World.Current.GetTileAt(t.X, t.Y + 1, t.Z) local south = World.Current.GetTileAt(t.X, t.Y - 1, t.Z) local west = World.Current.GetTileAt(t.X - 1, t.Y, t.Z) local east = World.Current.GetTileAt(t.X + 1, t.Y, t.Z) suffix = "" if (north.Room != nil and south.Room != nil) then if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then suffix = "_SN" else suffix = "_NS" end elseif (west.Room != nil and east.Room != nil) then if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then suffix = "_WE" else suffix = "_EW" end end return furniture.Type .. suffix end function AirPump_FlipDirection(furniture, character) if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then furniture.Parameters["flow_direction_up"].SetValue(0) else furniture.Parameters["flow_direction_up"].SetValue(1) end furniture.UpdateOnChanged(furniture) end function Accumulator_GetSpriteName(furniture) local baseName = furniture.Type local suffix = furniture.PowerConnection.CurrentThreshold return baseName .. "_" .. suffix end function OreMine_CreateMiningJob(furniture, character) -- Creates job for a character to go and "mine" the Ore local j = Job.__new( furniture.Tile, nil, nil, 0, nil, Job.JobPriority.High, false ) j.RegisterJobWorkedCallback("OreMine_OreMined") furniture.AddJob(j) ModUtils.ULog("Ore Mine - Mining Job Created") end function OreMine_OreMined(job) -- Defines the ore to be spawned by the mine local inventory = Inventory.__new(job.furniture.Parameters["ore_type"], 10) -- Place the "mined" ore on the tile World.Current.inventoryManager.PlaceInventory(job.tile, inventory) -- Deconstruct the ore mine job.furniture.Deconstruct() job.CancelJob() end function OreMine_GetSpriteName(furniture) return "mine_" .. furniture.Parameters["ore_type"].ToString() end -- This function gets called once, when the furniture is installed function Rtg_InstallAction( furniture, deltaTime) -- TODO: find elegant way to register heat source and sinks to Temperature furniture.EventActions.Register("OnUpdateTemperature", "Rtg_UpdateTemperature") World.Current.temperature.RegisterSinkOrSource(furniture) end -- This function gets called once, when the furniture is uninstalled function Rtg_UninstallAction( furniture, deltaTime) furniture.EventActions.Deregister("OnUpdateTemperature", "Rtg_UpdateTemperature") World.Current.temperature.DeregisterSinkOrSource(furniture) -- TODO: find elegant way to unregister previous register end function Rtg_UpdateTemperature( furniture, deltaTime) if (furniture.tile.Room.IsOutsideRoom() == true) then return end tile = furniture.tile pressure = tile.Room.GetGasPressure() / tile.Room.GetSize() efficiency = ModUtils.Clamp01(pressure / furniture.Parameters["pressure_threshold"].ToFloat()) temperatureChangePerSecond = furniture.Parameters["base_heating"].ToFloat() * efficiency temperatureChange = temperatureChangePerSecond * deltaTime World.Current.temperature.ChangeTemperature(tile.X, tile.Y, temperatureChange) --ModUtils.ULogChannel("Temperature", "Heat change: " .. temperatureChangePerSecond .. " => " .. World.current.temperature.GetTemperature(tile.X, tile.Y)) end ModUtils.ULog("Furniture.lua loaded") return "LUA Script Parsed!"
gpl-3.0
ArchiveTeam/imdb-grab
table_show.lua
1
3331
--[[ Author: Julio Manuel Fernandez-Diaz Date: January 12, 2007 (For Lua 5.1) Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount() Formats tables with cycles recursively to any depth. The output is returned as a string. References to other tables are shown as values. Self references are indicated. The string returned is "Lua code", which can be procesed (in the case in which indent is composed by spaces or "--"). Userdata and function keys and values are shown as strings, which logically are exactly not equivalent to the original code. This routine can serve for pretty formating tables with proper indentations, apart from printing them: print(table.show(t, "t")) -- a typical use Heavily based on "Saving tables with cycles", PIL2, p. 113. Arguments: t is the table. name is the name of the table (optional) indent is a first indentation (optional). --]] function table.show(t, name, indent) local cart -- a container local autoref -- for self references --[[ counts the number of elements in a table local function tablecount(t) local n = 0 for _, _ in pairs(t) do n = n+1 end return n end ]] -- (RiciLake) returns true if the table is empty local function isemptytable(t) return next(t) == nil end local function basicSerialize (o) local so = tostring(o) if type(o) == "function" then local info = debug.getinfo(o, "S") -- info.name is nil because o is not a calling level if info.what == "C" then return string.format("%q", so .. ", C function") else -- the information is defined through lines return string.format("%q", so .. ", defined in (" .. info.linedefined .. "-" .. info.lastlinedefined .. ")" .. info.source) end elseif type(o) == "number" or type(o) == "boolean" then return so else return string.format("%q", so) end end local function addtocart (value, name, indent, saved, field) indent = indent or "" saved = saved or {} field = field or name cart = cart .. indent .. field if type(value) ~= "table" then cart = cart .. " = " .. basicSerialize(value) .. ";\n" else if saved[value] then cart = cart .. " = {}; -- " .. saved[value] .. " (self reference)\n" autoref = autoref .. name .. " = " .. saved[value] .. ";\n" else saved[value] = name --if tablecount(value) == 0 then if isemptytable(value) then cart = cart .. " = {};\n" else cart = cart .. " = {\n" for k, v in pairs(value) do k = basicSerialize(k) local fname = string.format("%s[%s]", name, k) field = string.format("[%s]", k) -- three spaces between levels addtocart(v, fname, indent .. " ", saved, field) end cart = cart .. indent .. "};\n" end end end end name = name or "__unnamed__" if type(t) ~= "table" then return name .. " = " .. basicSerialize(t) end cart, autoref = "", "" addtocart(t, name, indent) return cart .. autoref end
unlicense
bkaradzic/SwiftShader
third_party/SPIRV-Headers/include/spirv/1.2/spirv.lua
59
26887
-- Copyright (c) 2014-2018 The Khronos Group Inc. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and/or associated documentation files (the "Materials"), -- to deal in the Materials without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Materials, and to permit persons to whom the -- Materials are furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Materials. -- -- MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS -- STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND -- HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ -- -- THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS -- IN THE MATERIALS. -- This header is automatically generated by the same tool that creates -- the Binary Section of the SPIR-V specification. -- Enumeration tokens for SPIR-V, in various styles: -- C, C++, C++11, JSON, Lua, Python -- -- - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL -- - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL -- - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL -- - Lua will use tables, e.g.: spv.SourceLanguage.GLSL -- - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] -- -- Some tokens act like mask values, which can be OR'd together, -- while others are mutually exclusive. The mask-like ones have -- "Mask" in their name, and a parallel enum that has the shift -- amount (1 << x) for each corresponding enumerant. spv = { MagicNumber = 0x07230203, Version = 0x00010200, Revision = 2, OpCodeMask = 0xffff, WordCountShift = 16, SourceLanguage = { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, }, ExecutionModel = { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, }, AddressingModel = { Logical = 0, Physical32 = 1, Physical64 = 2, }, MemoryModel = { Simple = 0, GLSL450 = 1, OpenCL = 2, }, ExecutionMode = { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, Initializer = 33, Finalizer = 34, SubgroupSize = 35, SubgroupsPerWorkgroup = 36, SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, PostDepthCoverage = 4446, StencilRefReplacingEXT = 5027, }, StorageClass = { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, }, Dim = { Dim1D = 0, Dim2D = 1, Dim3D = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, }, SamplerAddressingMode = { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, }, SamplerFilterMode = { Nearest = 0, Linear = 1, }, ImageFormat = { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, }, ImageChannelOrder = { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, }, ImageChannelDataType = { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, }, ImageOperandsShift = { Bias = 0, Lod = 1, Grad = 2, ConstOffset = 3, Offset = 4, ConstOffsets = 5, Sample = 6, MinLod = 7, }, ImageOperandsMask = { MaskNone = 0, Bias = 0x00000001, Lod = 0x00000002, Grad = 0x00000004, ConstOffset = 0x00000008, Offset = 0x00000010, ConstOffsets = 0x00000020, Sample = 0x00000040, MinLod = 0x00000080, }, FPFastMathModeShift = { NotNaN = 0, NotInf = 1, NSZ = 2, AllowRecip = 3, Fast = 4, }, FPFastMathModeMask = { MaskNone = 0, NotNaN = 0x00000001, NotInf = 0x00000002, NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, }, FPRoundingMode = { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, }, LinkageType = { Export = 0, Import = 1, }, AccessQualifier = { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, }, FunctionParameterAttribute = { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, }, Decoration = { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, MaxByteOffset = 45, AlignmentId = 46, MaxByteOffsetId = 47, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, }, BuiltIn = { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, SubgroupEqMaskKHR = 4416, SubgroupGeMaskKHR = 4417, SubgroupGtMaskKHR = 4418, SubgroupLeMaskKHR = 4419, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, DeviceIndex = 4438, ViewIndex = 4440, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, }, SelectionControlShift = { Flatten = 0, DontFlatten = 1, }, SelectionControlMask = { MaskNone = 0, Flatten = 0x00000001, DontFlatten = 0x00000002, }, LoopControlShift = { Unroll = 0, DontUnroll = 1, DependencyInfinite = 2, DependencyLength = 3, }, LoopControlMask = { MaskNone = 0, Unroll = 0x00000001, DontUnroll = 0x00000002, DependencyInfinite = 0x00000004, DependencyLength = 0x00000008, }, FunctionControlShift = { Inline = 0, DontInline = 1, Pure = 2, Const = 3, }, FunctionControlMask = { MaskNone = 0, Inline = 0x00000001, DontInline = 0x00000002, Pure = 0x00000004, Const = 0x00000008, }, MemorySemanticsShift = { Acquire = 1, Release = 2, AcquireRelease = 3, SequentiallyConsistent = 4, UniformMemory = 6, SubgroupMemory = 7, WorkgroupMemory = 8, CrossWorkgroupMemory = 9, AtomicCounterMemory = 10, ImageMemory = 11, }, MemorySemanticsMask = { MaskNone = 0, Acquire = 0x00000002, Release = 0x00000004, AcquireRelease = 0x00000008, SequentiallyConsistent = 0x00000010, UniformMemory = 0x00000040, SubgroupMemory = 0x00000080, WorkgroupMemory = 0x00000100, CrossWorkgroupMemory = 0x00000200, AtomicCounterMemory = 0x00000400, ImageMemory = 0x00000800, }, MemoryAccessShift = { Volatile = 0, Aligned = 1, Nontemporal = 2, }, MemoryAccessMask = { MaskNone = 0, Volatile = 0x00000001, Aligned = 0x00000002, Nontemporal = 0x00000004, }, Scope = { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, }, GroupOperation = { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, }, KernelEnqueueFlags = { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, }, KernelProfilingInfoShift = { CmdExecTime = 0, }, KernelProfilingInfoMask = { MaskNone = 0, CmdExecTime = 0x00000001, }, Capability = { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupDispatch = 58, NamedBarrier = 59, PipeStorage = 60, SubgroupBallotKHR = 4423, DrawParameters = 4427, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, StorageUniform16 = 4434, UniformAndStorageBuffer16BitAccess = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, }, Op = { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpSizeOf = 321, OpTypePipeStorage = 322, OpConstantPipeStorage = 323, OpCreatePipeFromPipeStorage = 324, OpGetKernelLocalSizeForSubgroupCount = 325, OpGetKernelMaxNumSubgroups = 326, OpTypeNamedBarrier = 327, OpNamedBarrierInitialize = 328, OpMemoryNamedBarrier = 329, OpModuleProcessed = 330, OpExecutionModeId = 331, OpDecorateId = 332, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpDecorateStringGOOGLE = 5632, OpMemberDecorateStringGOOGLE = 5633, }, }
apache-2.0
MemoryPenguin/CodeSync
Plugin/Modules/UI.module.lua
1
1826
local CoreGui = game:GetService("CoreGui") local Accessor = require(script.Parent.Accessor) local Object = script.CodeSyncUI local EnabledColor = Color3.new(34 / 255, 162 / 255, 147 / 255) local DisabledColor = Color3.new(162 / 255, 162 / 255, 162 / 255) local UI = {} UI.PortBox = Object.Container.Contents.PortBox.Input UI.ToggleButton = Object.Container.Contents.Toggle UI.Info = Object.Container.Contents.Info function UI.Show() Object.Parent = CoreGui end function UI.Hide() Object.Parent = script end function UI.IsVisible() return Object.Parent == CoreGui end function UI.SetInfoText(text) Object.Container.Contents.Info.Text = text end function UI.GetInfoText() return Object.Container.Contents.Info.Text end function UI.GetPort() return tonumber(Object.Container.Contents.PortBox.Input.Text) end function UI.FreezeButton() UI.ToggleButton.Active = false UI.ToggleButton.AutoButtonColor = false UI.ToggleButton.BackgroundColor3 = DisabledColor end function UI.ThawButton() UI.ToggleButton.Active = true UI.ToggleButton.AutoButtonColor = true UI.ToggleButton.BackgroundColor3 = EnabledColor end function UI.FreezePortBox() UI.PortBox.Active = false UI.PortBox.BackgroundColor3 = DisabledColor UI.PortBox:ReleaseFocus() end function UI.ThawPortBox() UI.PortBox.Active = true UI.PortBox.BackgroundColor3 = Color3.new(240 / 255, 240 / 255, 240 / 255) end function UI.CheckPort() local port = tonumber(UI.PortBox.Text) UI.FreezeButton() if UI.PortBox.Text == "" then UI.SetInfoText("Enter a port to get started.") elseif not port or port > 65535 then UI.SetInfoText("This port doesn't work! It should be a number between 1 and 65535.") else UI.ThawButton() UI.SetInfoText("Ready to start sync.") end end UI.PortBox.FocusLost:connect(UI.CheckPort) UI.CheckPort() return UI
mit
jackkkk21/jackkbot
plugins/owners.lua
284
12473
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
chelog/brawl
addons/brawl-weapons/lua/weapons/cw_base/sh_general.lua
1
22538
-- various convenience functions related to the weapon local reg = debug.getregistry() local GetVelocity = reg.Entity.GetVelocity local Length = reg.Vector.Length local GetAimVector = reg.Player.GetAimVector -- no reason to get it over and over again, since if it's singleplayer, it's singleplayer local SP = game.SinglePlayer() --[[attachment inter-dependency logic: requires a table, ie SWEP.AttachmentPosDependency first index a string containing attachments that it depends on second index is a string which contains the vector position ]]-- function LerpCW20(val, min, max) -- basically a wrapper that limits 'val' (aka progress) to a max of 1 val = val > 1 and 1 or val return Lerp(val, min, max) end function SWEP:canCustomize() if not self.CanCustomize then return false end if self.ReloadDelay then return false end if self.NoCustomizeStates[self.dt.State] then return false end if not self.Owner:OnGround() then return false end return true end function SWEP:isLowOnMagAmmo() if self:Clip1() <= self.Primary.ClipSize * 0.25 or self:getReloadProgress() then return true end end function SWEP:isLowOnAmmo() if self.Owner:GetAmmoCount(self.Primary.Ammo) <= self.Primary.ClipSize then return true end return false end function SWEP:isLowOnTotalAmmo() if self.Owner:GetAmmoCount(self.Primary.Ammo) + self:Clip1() <= self.Primary.ClipSize * 2 then return true end return false end function SWEP:setM203Chamber(state) self.M203Chamber = state self:networkM203Chamber() end function SWEP:networkM203Chamber() umsg.Start("CW20_M203CHAMBER", self.Owner) umsg.Entity(self) umsg.Bool(self.M203Chamber) umsg.End() end function SWEP:resetAimBreathingState() self.AimBreathingEnabled = self.AimBreathingEnabled_Orig end function SWEP:maxOutWeaponAmmo(desiredAmmo) self:SetClip1(desiredAmmo + (self.Chamberable and 1 or 0)) end function SWEP:isAiming() return self.dt.State == CW_AIMING end function SWEP:setupSuppressorPositions() self.SuppressorPositions = self.SuppressorPositions or {} if self.AttachmentModelsVM then for k, v in pairs(self.AttachmentModelsVM) do -- easy way to find all suppressor attachments, 'silencer' is there in case someone is gun-illiterate enough and calls them incorrectly if k:find("suppress") or k:find("silencer") then self.SuppressorPositions[k] = v.pos v.origPos = v.pos end end end end function SWEP:updateAttachmentPositions() if not self.AttachmentPosDependency and not self.AttachmentAngDependency then return end if not self.AttachmentModelsVM then return end -- loop through the VM attachment table for k, v in pairs(self.AttachmentModelsVM) do -- iterate through active attachments only if v.active then -- check for inter-dependencies of this attachment if self.AttachmentPosDependency then local inter = self.AttachmentPosDependency[k] if inter then -- loop through the attachment table, find active attachments local found = false for k2, v2 in pairs(inter) do if self.ActiveAttachments[k2] then v.pos = inter[k2] found = true end end -- reset the position in case none are active if not found then v.pos = v.origPos end end end if self.AttachmentAngDependency then local inter = self.AttachmentAngDependency[k] if inter then -- loop through the attachment table, find active attachments local found = false for k2, v2 in pairs(inter) do if self.ActiveAttachments[k2] then v.angle = inter[k2] found = true end end -- reset the position in case none are active if not found then v.angle = v.origAng end end end end end end function SWEP:updateSuppressorPosition(suppressor) if not self.SuppressorPositions then return end if not self.AttachmentModelsVM then return end local found = false -- loop through the table for k, v in pairs(self.Attachments) do if v.last then -- check active attachments -- if there is one and it is in the SuppressorPositions table local suppressorPos = self.SuppressorPositions[v.atts[v.last]] if suppressorPos then --find every single VM element with part of the name "suppress" or "silencer" and update it's pos to what it is for k2, v2 in pairs(self.AttachmentModelsVM) do if CustomizableWeaponry.suppressors[k2] then --if k2:find("suppress") or k2:find("silencer") then v2.pos = suppressorPos found = true break end end end end end -- if nothing is found, revert the position back to origPos if not found then for k, v in pairs(self.AttachmentModelsVM) do if CustomizableWeaponry.suppressors[k] then v.pos = v.origPos end end end end function SWEP:canSeeThroughTelescopics(aimPosName) if self.dt.State == CW_AIMING and not self.Peeking and self.AimPos == self[aimPosName] then local canUseSights = CustomizableWeaponry.grenadeTypes:canUseProperSights(self.Grenade40MM) if self.dt.M203Active then if self.M203Chamber then if canUseSights then return true end else return true end else return true end end return false end function SWEP:hasExcludedAttachment(tbl, targetTable) targetTable = targetTable or self.ActiveAttachments for k, v in pairs(tbl) do if targetTable[v] then return true, targetTable[v] end end return false end function SWEP:isCategoryEligible(depend, exclude, activeAttachments) local state = false activeAttachments = activeAttachments or self.ActiveAttachments -- if there are dependencies, make sure we have at least one of them for this category if depend then for k, v in pairs(depend) do if activeAttachments[k] then return true end end else state = true -- if there are none, assume no exclusions end -- if there are exclusions, loop through, if there are any attachments that exclude the current category, don't allow us to attach it if exclude then for k, v in pairs(exclude) do if activeAttachments[k] then return false, -1, k -- active attachment that excludes this category end end end -- otherwise, return the final verdict return state, -2, depend -- either true or false, in case of false - attachment(s) we depend on is (are) not active end -- this function checks whether a certain attachment can be attached -- it's different from the 'dependencies' and 'exclusions' tables in the Attachments table in the way that it checks eligibility on a per-attachment basis -- keep in mind that the 'dependencies' and 'exclusions' you specify in the Attachments table are on a category basis function SWEP:isAttachmentEligible(name, activeAttachments) local found = nil activeAttachments = activeAttachments or self.ActiveAttachments if self.AttachmentDependencies then local depend = self.AttachmentDependencies[name] -- loop through the active attachments, see if any of them are active if depend then found = false for k, v in pairs(depend) do -- if they are, that means we can proceed if activeAttachments[v] then found = true break end end end end if self.AttachmentExclusions then -- loop through the exclusions for this particular attachment, if there are any, let us know that we can't proceed local excl = self.AttachmentExclusions[name] if excl then for k, v in pairs(excl) do if activeAttachments[v] then return false, self.AttachmentEligibilityEnum.ACTIVE_ATTACHMENT_EXCLUSION, activeAttachments[v] -- active attachment excludes end end end end -- nil indicates that we can attach if found == nil then return true end -- or just return the result return found, self.AttachmentEligibilityEnum.NEED_ATTACHMENTS, self.AttachmentDependencies[name] -- in case of false - attachment we depend on is not attached end -- this function is ran every time an attachment is detached (or swapped, which is basically the same thing) -- what it does is it checks every attachment for dependencies, and detaches everything that can't be on the weapon without a 'parent' attachment function SWEP:checkAttachmentDependency() for k, v in ipairs(self.Attachments) do if v.last then local curAtt = v.atts[v.last] local foundAtt = CustomizableWeaponry.registeredAttachmentsSKey[curAtt] -- we've found an attachment that's currently on the weapon, check if it depends on anything if foundAtt then -- check if the category and the attachment are eligible if not self:isAttachmentEligible(foundAtt.name) or not self:isCategoryEligible(v.dependencies, v.exclusions) then -- they aren't eligible, time to detach them self:_detach(k, v.last) end end end end end -- restores the current firing sounds back to their original variants function SWEP:restoreSound() self.FireSound = self.FireSound_Orig self.FireSoundSuppressed = self.FireSoundSuppressed_Orig end function SWEP:updateSoundTo(snd, var) if not snd then return end var = var or 0 -- var 0 is the unsuppressed fire sound, var 1 is the suppressed if var == 0 then self.FireSound = Sound(snd) return self.FireSound elseif var == 1 then self.FireSoundSuppressed = Sound(snd) return self.FireSoundSuppressed end end function SWEP:setupCurrentIronsights(pos, ang) if SERVER then return end self.CurIronsightPos = pos self.CurIronsightAng = ang end function SWEP:resetSuppressorStatus() if self.SuppressedOnEquip ~= nil then self.dt.Suppressed = self.SuppressedOnEquip else -- default to false self.dt.Suppressed = false end end function SWEP:resetAimToIronsights() if SERVER then return end self.AimPos = self.CurIronsightPos self.AimAng = self.CurIronsightAng self.ActualSightPos = nil self.ActualSightAng = nil self.SightBackUpPos = nil self.SightBackUpAng = nil end function SWEP:revertToOriginalIronsights() if SERVER then return end self.CurIronsightPos = self.AimPos_Orig self.CurIronsightAng = self.AimAng_Orig if not self:isAttachmentActive("sights") then self.AimPos = self.CurIronsightPos self.AimAng = self.CurIronsightAng end end function SWEP:updateIronsights(index) if SERVER then return end self.AimPos = self[index .. "Pos"] self.AimAng = self[index .. "Ang"] end function SWEP:isAttachmentActive(category) if not category then return false end if not CustomizableWeaponry[category] then return false end for k, v in ipairs(self.Attachments) do if v.last then local curAtt = v.atts[v.last] if CustomizableWeaponry[category][curAtt] then return true end end end return false end local mins, maxs = Vector(-8, -8, -1), Vector(8, 8, 1) local td = {} td.mins = mins td.maxs = maxs function SWEP:CanRestWeapon(height) height = height or -1 local vel = Length(GetVelocity(self.Owner)) local pitch = self.Owner:EyeAngles().p if vel == 0 and pitch <= 60 and pitch >= -20 then local sp = self.Owner:GetShootPos() local aim = self.Owner:GetAimVector() td.start = sp td.endpos = td.start + aim * 35 td.filter = self.Owner local tr = util.TraceHull(td) -- fire first trace to check whether there is anything IN FRONT OF US if tr.Hit then -- if there is, don't allow us to deploy return false end aim.z = height td.start = sp td.endpos = td.start + aim * 25 td.filter = self.Owner tr = util.TraceHull(td) if tr.Hit then local ent = tr.Entity -- if the second trace passes, we can deploy if not ent:IsPlayer() and not ent:IsNPC() then return true end end return false end return false end function SWEP:getSpreadModifiers() local mul = 1 local mulMax = 1 -- decrease spread increase when aiming if self.Owner:Crouching() then mul = mul * 0.75 end -- and when a bipod is deployed if self.dt.BipodDeployed then mul = mul * 0.5 mulMax = 0.5 -- decrease maximum spread increase end return mul, mulMax end function SWEP:getFinalSpread(vel, maxMultiplier) maxMultiplier = maxMultiplier or 1 local final = self.BaseCone local aiming = self.dt.State == CW_AIMING -- take the continuous fire spread into account final = final + self.AddSpread -- and the player's velocity * mobility factor if aiming then -- irl the accuracy of your weapon goes to shit when you start moving even if you aim down the sights, so when aiming, player movement will impact the spread even more than it does during hip fire -- but we're gonna clamp it to a maximum of the weapon's hip fire spread, so that even if you aim down the sights and move, your accuracy won't be worse than your hip fire spread final = math.min(final + (vel / 10000 * self.VelocitySensitivity) * self.AimMobilitySpreadMod, self.HipSpread) else final = final + (vel / 10000 * self.VelocitySensitivity) end if self.ShootWhileProne and self:isPlayerProne() then final = final + vel / 1000 end -- as well as the spread caused by rapid mouse movement final = final + self.Owner.ViewAff -- lastly, return the final clamped value return math.Clamp(final, 0, 0.09 + self:getMaxSpreadIncrease(maxMultiplier)) end function SWEP:isNearWall() if not self.NearWallEnabled then return false end td.start = self.Owner:GetShootPos() td.endpos = td.start + self.Owner:EyeAngles():Forward() * 30 td.filter = self.Owner local tr = util.TraceLine(td) if tr.Hit or (IsValid(tr.Entity) and not tr.Entity:IsPlayer()) then return true end return false end function SWEP:performBipodDelay(time) time = time or self.BipodDeployTime local CT = CurTime() self.BipodDelay = CT + time self:SetNextPrimaryFire(CT + time) self:SetNextSecondaryFire(CT + time) self.ReloadWait = CT + time end function SWEP:delayEverything(time) time = time or 0.15 local CT = CurTime() self.BipodDelay = CT + time self:SetNextPrimaryFire(CT + time) self:SetNextSecondaryFire(CT + time) self.ReloadWait = CT + time self.HolsterWait = CT + time end function SWEP:isBipodIdle() if self.dt.BipodDeployed and self.DeployAngle and self.dt.State == CW_IDLE then return true end return false end function SWEP:isBipodDeployed() if self.dt.BipodDeployed then return true end return false end function SWEP:isReloading() if self.ReloadDelay then return true end if (SP and CLIENT) then if self.IsReloading then if self.Cycle < 0.98 then return true end end end return false end function SWEP:canOpenInteractionMenu() if self.dt.State == CW_CUSTOMIZE then return true end if CustomizableWeaponry.callbacks.processCategory(self, "disableInteractionMenu") then return false end if table.Count(self.Attachments) == 0 then return false end if self.ReloadDelay then return false end local CT = CurTime() if CT < self.ReloadWait or CT < self.BipodDelay or self.dt.BipodDeployed then return false end if Length(GetVelocity(self.Owner)) >= self.Owner:GetWalkSpeed() * self.RunStateVelocity then return false end if not self.Owner:OnGround() then return false end return true end function SWEP:setupBipodVars() -- network/predict bipod angles if SP and SERVER then umsg.Start("CW20_DEPLOYANGLE", self.Owner) umsg.Angle(self.Owner:EyeAngles()) umsg.End() else self.DeployAngle = self.Owner:EyeAngles() end -- delay all actions self:performBipodDelay() end function SWEP:canUseComplexTelescopics() if SERVER then return true end if CustomizableWeaponry.callbacks.processCategory(self, "forceComplexTelescopics") then return true end return GetConVarNumber("cw_simple_telescopics") <= 0 end function SWEP:canUseSimpleTelescopics() if not self:canUseComplexTelescopics() and self.SimpleTelescopicsFOV then return true end return false end function SWEP:setGlobalDelay(delay, forceNetwork, forceState, forceTime) if SERVER then if (SP or forceNetwork) then umsg.Start("CW20_GLOBALDELAY", self.Owner) umsg.Float(delay) umsg.End() end if forceState and forceTime then self:forceState(forceState, forceTime, true) end end self.GlobalDelay = CurTime() + delay end function SWEP:forceState(state, time, network) self.forcedState = state self.ForcedStateTime = CurTime() + time if SERVER and network then umsg.Start("CW20_FORCESTATE", self.Owner) umsg.Short(state) umsg.Float(time) umsg.End() end end function SWEP:setupBallisticsInformation() local info = CustomizableWeaponry.ammoTypes[self.Primary.Ammo] if not info then return end self.BulletDiameter = info.bulletDiameter self.CaseLength = info.caseLength end function SWEP:seekPresetPosition(offset) offset = offset or 0 local count = #self.PresetResults if offset > 0 and self.PresetPosition + 10 > count then return end self.PresetPosition = math.Clamp(self.PresetPosition + offset, 1, count) end function SWEP:setPresetPosition(offset, force) offset = offset or 0 if force then self.PresetPosition = math.max(self.PresetPosition, 1) return end local count = #self.PresetResults -- clamp the maximum and minimum position self.PresetPosition = math.Clamp(offset, 1, count) end function SWEP:getDesiredPreset(bind) local desired = bind == "slot0" and 10 or tonumber(string.Right(bind, 1)) local pos = self.PresetPosition + desired return pos end function SWEP:attemptPresetLoad(entry) if not self.PresetResults then return false end entry = entry - 1 local result = self.PresetResults[entry] if not result then return false end CustomizableWeaponry.preset.load(self, result.displayName) return true end function SWEP:getActiveAttachmentInCategory(cat) local category = self.Attachments[cat] if category then if category.last then return category.atts[category.last] end end return nil end function SWEP:getSightColor(data) -- why are you passing nil :( if not data then -- assume it's a sight we're trying to get the color for return CustomizableWeaponry.defaultColors[CustomizableWeaponry.COLOR_TYPE_SIGHT] end local found = self.SightColors[data] if found then return found.color end end -- this function sets up reticle and laser beam colors for all sights/laser sights function SWEP:setupReticleColors() self.SightColors = {} for k, v in ipairs(self.Attachments) do for k2, v2 in ipairs(v.atts) do local foundAtt = CustomizableWeaponry.registeredAttachmentsSKey[v2] if foundAtt then -- if the found attachment has a color type enum, that means it is colorable (wow!) -- therefore, we need to add it to the color table if foundAtt.colorType then local def = CustomizableWeaponry.colorableParts.defaultColors[foundAtt.colorType] self.SightColors[foundAtt.name] = {type = foundAtt.colorType, color = def.color, last = 1, display = CustomizableWeaponry.colorableParts:makeColorDisplayText(def.display)} end end end end end function SWEP:isReloadingM203() if not self.AttachmentModelsVM then return false end local m203 = self.AttachmentModelsVM.md_m203 if m203 and m203.active then if self.curM203Anim == self.M203Anims.reload then if m203.ent:GetCycle() <= 0.9 then return true end end end return false end function SWEP:filterPrediction() if (SP and SERVER) or not SP then return true end return false end function SWEP:getMagCapacity() local mag = self:Clip1() if mag > self.Primary.ClipSize_Orig then return self.Primary.ClipSize_Orig .. " + " .. mag - self.Primary.ClipSize_Orig end return mag end function SWEP:getReloadProgress() if self.IsReloading and self.Cycle <= 0.98 then if self.ShotgunReload then return math.Clamp(math.ceil(self:getAnimSeek() / self.InsertShellTime * 100), 0, 100) else if self.wasEmpty then return math.Clamp(math.ceil(self:getAnimSeek() / self.ReloadHalt_Empty * 100), 0, 100) else return math.Clamp(math.ceil(self:getAnimSeek() / self.ReloadHalt * 100), 0, 100) end end end return nil end function SWEP:isReticleActive() if self.reticleInactivity and UnPredictedCurTime() < self.reticleInactivity then return false end return true end if CLIENT then function SWEP:getReticleAngles() if self.freeAimOn then local ang = self.CW_VM:GetAngles() ang.p = ang.p + self.AimAng.x ang.y = ang.y - self.AimAng.y ang.r = ang.r - self.AimAng.z return ang end return self.Owner:EyeAngles() + self.Owner:GetPunchAngle() end function SWEP:getTelescopeAngles() if self.freeAimOn then return self.Owner:EyeAngles() end return self:getMuzzlePosition().Ang end function SWEP:getLaserAngles(model) --if self.freeAimOn then -- return self.Owner:EyeAngles() --end return model:GetAngles() end end local trans = {["MOUSE1"] = "LEFT MOUSE BUTTON", ["MOUSE2"] = "RIGHT MOUSE BUTTON"} local b, e function SWEP:getKeyBind(bind) b = input.LookupBinding(bind) e = trans[b] return b and ("[" .. (e and e or string.upper(b)) .. "]") or "[NOT BOUND, " .. bind .. "]" end -- GENERAL MATH FUNCS function math.ApproachVector(startValue, endValue, amount) startValue.x = math.Approach(startValue.x, endValue.x, amount) startValue.y = math.Approach(startValue.y, endValue.y, amount) startValue.z = math.Approach(startValue.z, endValue.z, amount) return startValue end function math.NormalizeAngles(ang) ang.p = math.NormalizeAngle(ang.p) ang.y = math.NormalizeAngle(ang.y) ang.r = math.NormalizeAngle(ang.r) return ang end
gpl-3.0
aruanruan/Atlas
lib/proxy/tokenizer.lua
41
6215
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] require("mysql.tokenizer") module("proxy.tokenizer", package.seeall) --- -- normalize a query -- -- * remove comments -- * quote literals -- * turn constants into ? -- * turn tokens into uppercase -- -- @param tokens a array of tokens -- @return normalized SQL query -- -- @see tokenize function normalize(tokens) -- we use a string-stack here and join them at the end -- see http://www.lua.org/pil/11.6.html for more -- local stack = {} -- literals that are SQL commands if they appear at the start -- (all uppercase) local literal_keywords = { ["COMMIT"] = { }, ["ROLLBACK"] = { }, ["BEGIN"] = { }, ["START"] = { "TRANSACTION" }, } for i = 1, #tokens do local token = tokens[i] -- normalize the query if token["token_name"] == "TK_COMMENT" then elseif token["token_name"] == "TK_COMMENT_MYSQL" then -- a /*!... */ comment -- -- we can't look into the comment as we don't know which server-version -- we will talk to, pass it on verbatimly table.insert(stack, "/*!" ..token.text .. "*/ ") elseif token["token_name"] == "TK_LITERAL" then if token.text:sub(1, 1) == "@" then -- append session variables as is table.insert(stack, token.text .. " ") elseif #stack == 0 then -- nothing is on the stack yet local u_text = token.text:upper() if literal_keywords[u_text] then table.insert(stack, u_text .. " ") else table.insert(stack, "`" .. token.text .. "` ") end elseif #stack == 1 then local u_text = token.text:upper() local starting_keyword = stack[1]:sub(1, -2) if literal_keywords[starting_keyword] and literal_keywords[starting_keyword][1] == u_text then table.insert(stack, u_text .. " ") else table.insert(stack, "`" .. token.text .. "` ") end else table.insert(stack, "`" .. token.text .. "` ") end elseif token["token_name"] == "TK_STRING" or token["token_name"] == "TK_INTEGER" or token["token_name"] == "TK_FLOAT" then table.insert(stack, "? ") elseif token["token_name"] == "TK_FUNCTION" then table.insert(stack, token.text:upper()) else table.insert(stack, token.text:upper() .. " ") end end return table.concat(stack) end --- -- call the included tokenizer -- -- this function is only a wrapper and exists mostly -- for constancy and documentation reasons function tokenize(packet) local tokens = tokenizer.tokenize(packet) local attr = 0 if tokens[1].token_name == "TK_COMMENT" or tokens[1].token_name == "TK_COMMENT_MYSQL" then if string.match(tokens[1].text:upper(), "^%s*MASTER%s*$") then attr = 1 --1´ú±íÇ¿ÖÆ¶Ámaster end end return tokens, attr end --- -- return the first command token -- -- * strips the leading comments function first_stmt_token(tokens) for i = 1, #tokens do local token = tokens[i] -- normalize the query if token["token_name"] == "TK_COMMENT" then elseif token["token_name"] == "TK_LITERAL" then -- commit and rollback at LITERALS return token else -- TK_SQL_* are normal tokens return token end end return nil end --- --[[ returns an array of simple token values without id and name, and stripping all comments @param tokens an array of tokens, as produced by the tokenize() function @param quote_strings : if set, the string tokens will be quoted @see tokenize --]] function bare_tokens (tokens, quote_strings) local simple_tokens = {} for i = 1, #tokens do local token = tokens[i] if (token['token_name'] == 'TK_STRING') and quote_strings then table.insert(simple_tokens, string.format('%q', token['text'] )) elseif (token['token_name'] ~= 'TK_COMMENT') then table.insert(simple_tokens, token['text']) end end return simple_tokens end --- --[[ Returns a text query from an array of tokens, stripping off comments @param tokens an array of tokens, as produced by the tokenize() function @param start_item ignores tokens before this one @param end_item ignores token after this one @see tokenize --]] function tokens_to_query ( tokens , start_item, end_item ) if not start_item then start_item = 1 end if not end_item then end_item = #tokens end local counter = 0 local new_query = '' for i = 1, #tokens do local token = tokens[i] counter = counter + 1 if (counter >= start_item and counter <= end_item ) then if (token['token_name'] == 'TK_STRING') then new_query = new_query .. string.format('%q', token['text'] ) elseif token['token_name'] ~= 'TK_COMMENT' then new_query = new_query .. token['text'] end if (token['token_name'] ~= 'TK_FUNCTION') and (token['token_name'] ~= 'TK_COMMENT') then new_query = new_query .. ' ' end end end return new_query end --- --[[ returns an array of tokens, stripping off all comments @param tokens an array of tokens, as produced by the tokenize() function @see tokenize, simple_tokens --]] function tokens_without_comments (tokens) local new_tokens = {} for i = 1, #tokens do local token = tokens[i] if (token['token_name'] ~= 'TK_COMMENT' and token['token_name'] ~= 'TK_COMMENT_MYSQL') then table.insert(new_tokens, token) end end return new_tokens end
gpl-2.0
chelog/brawl
addons/brawl-weapons/lua/cw/shared/cw_attachments.lua
1
13711
AddCSLuaFile() -- thanks to this module/plug-in based design, you can simply change a few vars to whatever you wish to get the desired functionality in your gamemode without having to modify the base itself CustomizableWeaponry.registeredAttachments = {} CustomizableWeaponry.registeredAttachmentsSKey = {} -- SKey stands for 'string key', whereas the registeredAttachments has numerical indexes CustomizableWeaponry.suppressors = {} CustomizableWeaponry.sights = {} CustomizableWeaponry.knownStatTexts = {} CustomizableWeaponry.knownVariableTexts = {} CustomizableWeaponry.giveAllAttachmentsOnSpawn = 1 -- set to 0 to disable all attachments on spawn CustomizableWeaponry.canOpenInteractionMenu = true -- whether the interaction menu can be opened CustomizableWeaponry.playSoundsOnInteract = true -- whether it should play sounds when interacting with the weapon (attaching stuff, changing ammo, etc) CustomizableWeaponry.customizationEnabled = true -- whether we can customize our guns in general CustomizableWeaponry.customizationMenuKey = "+menu_context" -- the key we need to press to toggle the customization menu CustomizableWeaponry.textColors = {POSITIVE = Color(200, 255, 200, 255), NEGATIVE = Color(255, 200, 200, 255), VPOSITIVE = Color(175, 255, 175, 255), VNEGATIVE = Color(255, 150, 150, 255), REGULAR = Color(255, 255, 255, 255), COSMETIC = Color(169, 240, 255, 255), BLACK = Color(0, 0, 0, 255), GRAY = Color(200, 200, 200, 255)} CustomizableWeaponry.sounds = {UNSUPPRESSED = 0, SUPPRESSED = 1} local fallbackFuncs = {} function fallbackFuncs:canEquip() return true end local totalAtts = 1 -- base func for registering atts function CustomizableWeaponry:registerAttachment(tbl) -- register suppressors in a separate table with it's name as a key to avoid having to loop when doing stuff with attachments if tbl.isSuppressor then CustomizableWeaponry.suppressors[tbl.name] = tbl end if tbl.isSight then CustomizableWeaponry.sights[tbl.name] = tbl end if tbl.reticle then tbl._reticle = Material(tbl.reticle) tbl._reticleIcon = surface.GetTextureID(tbl.reticle) end tbl.id = totalAtts -- create convars for setting up which attachments should be given upon spawn if SERVER then local cvName = "cw_att_" .. tbl.name CreateConVar(cvName, CustomizableWeaponry.giveAllAttachmentsOnSpawn, {FCVAR_ARCHIVE, FCVAR_NOTIFY}) tbl.cvar = cvName end local cvName = "cw_att_" .. tbl.name .. "_cl" if CLIENT then CreateClientConVar(cvName, CustomizableWeaponry.giveAllAttachmentsOnSpawn, true, true) end tbl.clcvar = cvName -- set the metatable of the current attachment to a fallback table, so that we can fallback to pre-defined funcs in case we're calling a nil method setmetatable(tbl, {__index = fallbackFuncs}) tbl.FOVModifier = tbl.FOVModifier and tbl.FOVModifier or 15 local val, key = self:findAttachment(tbl.name) -- don't register attachments that are already registered if val then -- instead, just override them self.registeredAttachments[key] = tbl self.registeredAttachmentsSKey[tbl.name] = tbl return end if CLIENT then self:createStatText(tbl) end table.insert(self.registeredAttachments, tbl) self.registeredAttachmentsSKey[tbl.name] = tbl totalAtts = totalAtts + 1 end function CustomizableWeaponry:findAttachment(name) -- find the matching attachment for k, v in ipairs(self.registeredAttachments) do if v.name == name then return v, k end end -- if there is none, return nil return nil end function CustomizableWeaponry:canBeAttached(attachmentData, attachmentList) if not attachmentData.dependencies then return true end attachmentList = attachmentList or self.Attachments local dependency = nil for k, v in pairs(attachmentList) do if v.last then for k2, v2 in ipairs(v.atts) do if attachmentData.dependencies[v2] then if v.last == k2 then return true else dependency = attachmentData.dependencies[v2] end end end end end return false, dependency end local emptyString = "" function CustomizableWeaponry:formAdditionalText(att) if att.isGrenadeLauncher then return CustomizableWeaponry.grenadeTypes.getGrenadeText(self) end return emptyString end function CustomizableWeaponry:cycleSubCustomization() if self.SightColorTarget then CustomizableWeaponry.colorableParts.cycleColor(self, self.SightColorTarget) elseif self.GrenadeTarget then CustomizableWeaponry.grenadeTypes.cycleGrenades(self) end self.SubCustomizationCycleTime = nil end local by = " by " local percentage = "%" local tempPositive = {} local tempNegative = {} function CustomizableWeaponry:prepareText(text, color) if text and color then -- sort into 2 different tables if color == CustomizableWeaponry.textColors.POSITIVE then table.insert(tempPositive, {t = text, c = color}) else table.insert(tempNegative, {t = text, c = color}) end end end -- this func is called only once per attachment, so don't worry about a possible performance bottleneck, even if it has a lot of loops function CustomizableWeaponry:createStatText(att) -- no point in doing anything if there are no stat modifiers if not att.statModifiers then return end -- create a new desc table in case it has none if not att.description then att.description = {} end local pos = 0 -- get position of positive stat text for key, value in ipairs(att.description) do if value.c == CustomizableWeaponry.textColors.POSITIVE or value.c == CustomizableWeaponry.textColors.VPOSITIVE then pos = math.max(pos, key) + 1 end end -- if there is none, assume first possible position if pos == 0 then pos = #att.description + 1 end -- loop through, format negative and positive texts into 2 separate tables for stat, amount in pairs(att.statModifiers) do self:prepareText(self:formatWeaponStatText(stat, amount)) end for stat, data in pairs(CustomizableWeaponry.knownVariableTexts) do if att[stat] then self:prepareText(self:formatWeaponVariableText(att, stat, data)) end end -- now insert the positive text first and increment the position of positive text by 1 (since it's positive text we're inserting) for key, data in ipairs(tempPositive) do table.insert(att.description, pos, data) pos = pos + 1 end -- now insert negative text, but don't increment the position, since it's negative text for key, data in ipairs(tempNegative) do table.insert(att.description, pos, data) end table.Empty(tempNegative) table.Empty(tempPositive) -- loop through, find the spot where the positive stat text is --[[for k, v in ipairs(att.description) do if v.c == CustomizableWeaponry.textColors.POSITIVE or v.c == CustomizableWeaponry.textColors.VPOSITIVE then pos = k + 1 break end end -- loop through, insert POSITIVE text, count amount of text inserts for stat, amount in pairs(att.statModifiers) do local text, color = self:formatWeaponStatText(stat, amount) if text and color and color == CustomizableWeaponry.textColors.POSITIVE then table.insert(att.description, pos, {t = text, c = color}) end end pos = nil -- loop through again, this time, find where the negative text is for k, v in ipairs(att.description) do if v.c == CustomizableWeaponry.textColors.NEGATIVE or v.c == CustomizableWeaponry.textColors.VNEGATIVE then pos = k + 1 break end end -- if there is none, assume bottom of description table if not pos then pos = #att.description + 1 end for stat, amount in pairs(att.statModifiers) do local text, color = self:formatWeaponStatText(stat, amount) if text and color and color == CustomizableWeaponry.textColors.NEGATIVE then table.insert(att.description, pos, {t = text, c = color}) end end]]-- end function CustomizableWeaponry:formatWeaponStatText(target, amount) local statText = self.knownStatTexts[target] if statText then -- return text and colors as specified in the table if amount < 0 then return statText.lesser .. by .. math.Round(math.abs(amount * 100)) .. percentage, statText.lesserColor elseif amount > 0 then return statText.greater .. by .. math.Round(math.abs(amount * 100)) .. percentage, statText.greaterColor end end -- no result, rip return nil end function CustomizableWeaponry:formatWeaponVariableText(attachmentData, variable, varData) local var = attachmentData[variable] if var then if varData.formatText then return varData.formatText(attachmentData, var, varData) else if var < 0 then return varData.lesser .. by .. var, varData.lesserColor elseif var > 0 then return varData.greater .. by .. var, varData.greaterColor end end end end -- 'name' - name of the stat in the 'statModifiers' table -- 'greaterThan' - the text to display when the stat is greater than zero -- 'lesserThan' - the text to display when the stat is lesser than zero function CustomizableWeaponry:registerRecognizedStat(name, lesser, greater, lesserColor, greaterColor) self.knownStatTexts[name] = {lesser = lesser, greater = greater, lesserColor = lesserColor, greaterColor = greaterColor} end function CustomizableWeaponry:registerRecognizedVariable(name, lesser, greater, lesserColor, greaterColor, attachCallback, detachCallback, formatText) self.knownVariableTexts[name] = {lesser = lesser, greater = greater, lesserColor = lesserColor, greaterColor = greaterColor, attachCallback = attachCallback, detachCallback = detachCallback, formatText = formatText} end -- register the recognized stats so that people just have to fill out the 'statModifiers' table and be done with it CustomizableWeaponry:registerRecognizedStat("DamageMult", "Decreases damage", "Increases damage", CustomizableWeaponry.textColors.NEGATIVE, CustomizableWeaponry.textColors.POSITIVE) CustomizableWeaponry:registerRecognizedStat("RecoilMult", "Decreases recoil", "Increases recoil", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE) CustomizableWeaponry:registerRecognizedStat("FireDelayMult", "Increases firerate", "Decreases firerate", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE) CustomizableWeaponry:registerRecognizedStat("HipSpreadMult", "Decreases hip spread", "Increases hip spread", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE) CustomizableWeaponry:registerRecognizedStat("AimSpreadMult", "Decreases aim spread", "Increases aim spread", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE) CustomizableWeaponry:registerRecognizedStat("ClumpSpreadMult", "Decreases clump spread", "Increases clump spread", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE) CustomizableWeaponry:registerRecognizedStat("DrawSpeedMult", "Decreases deploy speed", "Increases deploy speed", CustomizableWeaponry.textColors.NEGATIVE, CustomizableWeaponry.textColors.POSITIVE) CustomizableWeaponry:registerRecognizedStat("ReloadSpeedMult", "Decreases reload speed", "Increases reload speed", CustomizableWeaponry.textColors.NEGATIVE, CustomizableWeaponry.textColors.POSITIVE) CustomizableWeaponry:registerRecognizedStat("OverallMouseSensMult", "Decreases handling", "Increases handling", CustomizableWeaponry.textColors.NEGATIVE, CustomizableWeaponry.textColors.POSITIVE) CustomizableWeaponry:registerRecognizedStat("VelocitySensitivityMult", "Increases mobility", "Decreases mobility", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE) CustomizableWeaponry:registerRecognizedStat("SpreadPerShotMult", "Decreases spread per shot", "Increases spread per shot", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE) CustomizableWeaponry:registerRecognizedStat("MaxSpreadIncMult", "Decreases accumulative spread", "Increases accumulative spread", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE) CustomizableWeaponry:registerRecognizedVariable("SpeedDec", "Increases movement speed by ", "Decreases movement speed by ", CustomizableWeaponry.textColors.POSITIVE, CustomizableWeaponry.textColors.NEGATIVE, function(weapon, attachmentData) weapon.SpeedDec = weapon.SpeedDec + attachmentData.SpeedDec end, function(weapon, attachmentData) weapon.SpeedDec = weapon.SpeedDec - attachmentData.SpeedDec end, -- attachmentData is the current attachment -- value is the value of the variable -- varData is the variable data we’re registering with registerRecognizedVariable function(attachmentData, value, varData) if value > 0 then return varData.greater .. math.abs(value) .. " points", varData.greaterColor end return varData.lesser .. math.abs(value) .. " points", varData.lesserColor end) -- too lazy to re-write the directory every single time, so just create a local string that we'll concatenate local path = "cw/shared/attachments/" -- load attachment files for k, v in pairs(file.Find("cw/shared/attachments/*", "LUA")) do loadFile(path .. v) end local path = "cw/shared/ammotypes/" -- load ammo type files (they're the same as attachments, really, but this way it's very easy to integrate it with the weapon customization menu) for k, v in pairs(file.Find("cw/shared/ammotypes/*", "LUA")) do loadFile(path .. v) end
gpl-3.0
RedSnake64/openwrt-luci-packages
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/iwinfo.lua
31
1569
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.iwinfo", package.seeall) function rrdargs( graph, plugin, plugin_instance ) -- -- signal/noise diagram -- local snr = { title = "%H: Signal and noise on %pi", vlabel = "dBm", number_format = "%5.1lf dBm", data = { types = { "signal_noise", "signal_power" }, options = { signal_power = { title = "Signal", overlay = true, color = "0000ff" }, signal_noise = { title = "Noise", overlay = true, color = "ff0000" } } } } -- -- signal quality diagram -- local quality = { title = "%H: Signal quality on %pi", vlabel = "Quality", number_format = "%3.0lf", data = { types = { "signal_quality" }, options = { signal_quality = { title = "Quality", noarea = true, color = "0000ff" } } } } -- -- phy rate diagram -- local bitrate = { title = "%H: Average phy rate on %pi", vlabel = "MBit/s", number_format = "%5.1lf%sBit/s", data = { types = { "bitrate" }, options = { bitrate = { title = "Rate", color = "00ff00" } } } } -- -- associated stations -- local stations = { title = "%H: Associated stations on %pi", vlabel = "Stations", number_format = "%3.0lf", data = { types = { "stations" }, options = { stations = { title = "Stations", color = "0000ff" } } } } return { snr, quality, bitrate, stations } end
apache-2.0
cloner-hooshesiyah/shidbot
bot/seedbot.lua
1
10308
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "plug", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "admin" }, sudo_users = {245846142,223632718,0,tonumber(our_id)},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Our team! Alphonse (@Iwals) I M /-\ N (@Imandaneshi) Siyanew (@Siyanew) Rondoozle (@Potus) Seyedan (@Seyedan25) Special thanks to: Juan Potato Siyanew Topkecleon Vamptacus Our channels: English: @TeleSeedCH Persian: @IranSeed ]], help_text_realm = [[ Realm Commands: !creategroup [name] Create a group !createrealm [name] Create a realm !setname [name] Set realm name !setabout [group_id] [text] Set a group's about text !setrules [grupo_id] [text] Set a group's rules !lock [grupo_id] [setting] Lock a group's setting !unlock [grupo_id] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [grupo_id] Kick all memebers and delete group !kill realm [realm_id] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Get a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups » Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id Return group id or user id !help Get commands list !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules [text] Set [text] as rules !set about [text] Set [text] as about !settings Returns group settings !newlink Create/revoke your group link !link Returns group link !owner Returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] [text] Save [text] as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] Returns user id !log Will return group logs !banlist Will return group ban list » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
qq779089973/ramod
luci/libs/nixio/axTLS/www/lua/download.lua
180
1550
#!/usr/local/bin/lua require"luasocket" function receive (connection) connection:settimeout(0) local s, status = connection:receive (2^10) if status == "timeout" then coroutine.yield (connection) end return s, status end function download (host, file, outfile) --local f = assert (io.open (outfile, "w")) local c = assert (socket.connect (host, 80)) c:send ("GET "..file.." HTTP/1.0\r\n\r\n") while true do local s, status = receive (c) --f:write (s) if status == "closed" then break end end c:close() --f:close() end local threads = {} function get (host, file, outfile) print (string.format ("Downloading %s from %s to %s", file, host, outfile)) local co = coroutine.create (function () return download (host, file, outfile) end) table.insert (threads, co) end function dispatcher () while true do local n = table.getn (threads) if n == 0 then break end local connections = {} for i = 1, n do local status, res = coroutine.resume (threads[i]) if not res then table.remove (threads, i) break else table.insert (connections, res) end end if table.getn (connections) == n then socket.select (connections) end end end local url = arg[1] if not url then print (string.format ("usage: %s url [times]", arg[0])) os.exit() end local times = arg[2] or 5 url = string.gsub (url, "^http.?://", "") local _, _, host, file = string.find (url, "^([^/]+)(/.*)") local _, _, fn = string.find (file, "([^/]+)$") for i = 1, times do get (host, file, fn..i) end dispatcher ()
mit
qq779089973/ramod
luci/modules/niu/luasrc/model/cbi/niu/network/wan.lua
51
2373
local cursor = require "luci.model.uci".cursor() if not cursor:get("network", "wan") then cursor:section("network", "interface", "wan", {proto = "none"}) cursor:save("network") end if not cursor:get("wireless", "client") then cursor:section("wireless", "wifi-iface", "client", {device = "_", doth = "1", _niu = "1", mode = "sta"}) cursor:save("wireless") end local function deviceroute(self) cursor:unload("network") local wd = cursor:get("network", "wan", "_wandev") or "" if wd == "none" then cursor:set("network", "wan", "proto", "none") end if wd:find("ethernet:") == 1 then cursor:set("network", "wan", "defaultroute", "1") if wd:find("!", 10) == 10 then --Unbridge from LAN local ethdev = wd:sub(11) local ifname = cursor:get("network", "lan", "ifname") local newifname = {} for k in ifname:gmatch("[^ ]+") do if k ~= ifname then newifname[#newifname+1] = k end end cursor:set("network", "lan", "ifname", table.concat(newifname, " ")) cursor:set("network", "wan", "_wandev", "ethernet:" .. ethdev) cursor:set("network", "wan", "ifname", ethdev) else cursor:set("network", "wan", "ifname", wd:sub(10)) end self:set_route("etherwan") else cursor:delete("network", "wan", "ifname") end if wd:find("wlan:") == 1 then local widev = wd:sub(6) if cursor:get("wireless", "client", "device") ~= widev then cursor:delete("wireless", "client", "network") cursor:set("wireless", "client", "mode", "sta") cursor:set("wireless", "client", "device", widev) cursor:delete_all("wireless", "wifi-iface", function(s) return s.device == widev and s._niu ~= "1" end) cursor:set("wireless", widev, "disabled", 0) end self:set_route("wlanwan1", "wlanwan2") else cursor:delete("wireless", "client", "device") cursor:delete("wireless", "client", "network") end cursor:save("wireless") cursor:save("network") end local d = Delegator() d.allow_finish = true d.allow_back = true d.allow_cancel = true d:add("device", "niu/network/wandevice") d:add("deviceroute", deviceroute) d:set("etherwan", "niu/network/etherwan") d:set("wlanwan1", "niu/network/wlanwanscan") d:set("wlanwan2", "niu/network/wlanwan") function d.on_cancel() cursor:revert("network") cursor:revert("wireless") end function d.on_done() cursor:commit("network") cursor:commit("wireless") end return d
mit
bjakja/Kainote
Thirdparty/LuaJIT/dynasm/dasm_arm64.lua
1
36385
------------------------------------------------------------------------------ -- DynASM ARM64 module. -- -- Copyright (C) 2005-2022 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM64 module", version = "1.5.0", vernum = 10500, release = "2021-05-02", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local format, byte, char = _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local ror, tohex, tobit = bit.ror, bit.tohex, bit.tobit -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "REL_A", "IMM", "IMM6", "IMM12", "IMM13W", "IMM13X", "IMML", "IMMV", "VREG", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { xzr = "@x31", wzr = "@w31", lr = "x30", } -- Int. register name -> ext. name. local map_reg_rev = { ["@x31"] = "xzr", ["@w31"] = "wzr", x30 = "lr", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, } local map_extend = { uxtb = 0, uxth = 1, uxtw = 2, uxtx = 3, sxtb = 4, sxth = 5, sxtw = 6, sxtx = 7, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ local parse_reg_type local function parse_reg(expr, shift) if not expr then werror("expected register name") end local tname, ovreg = match(expr, "^([%w_]+):(@?%l%d+)$") if not tname then tname, ovreg = match(expr, "^([%w_]+):(R[xwqdshb]%b())$") end local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local ok31, rt, r = match(expr, "^(@?)([xwqdshb])([123]?[0-9])$") if r then r = tonumber(r) if r <= 30 or (r == 31 and ok31 ~= "" or (rt ~= "w" and rt ~= "x")) then if not parse_reg_type then parse_reg_type = rt elseif parse_reg_type ~= rt then werror("register size mismatch") end return shl(r, shift), tp end end local vrt, vreg = match(expr, "^R([xwqdshb])(%b())$") if vreg then if not parse_reg_type then parse_reg_type = vrt elseif parse_reg_type ~= vrt then werror("register size mismatch") end if shift then waction("VREG", shift, vreg) end return 0 end werror("bad register name `"..expr.."'") end local function parse_reg_base(expr) if expr == "sp" then return 0x3e0 end local base, tp = parse_reg(expr, 5) if parse_reg_type ~= "x" then werror("bad register type") end parse_reg_type = false return base, tp end local parse_ctx = {} local loadenv = setfenv and function(s) local code = loadstring(s, "") if code then setfenv(code, parse_ctx) end return code end or function(s) return load(s, "", nil, parse_ctx) end -- Try to parse simple arithmetic, too, since some basic ops are aliases. local function parse_number(n) local x = tonumber(n) if x then return x end local code = loadenv("return "..n) if code then local ok, y = pcall(code) if ok and type(y) == "number" then return y end end return nil end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then if shr(n, 12) == 0 then return shl(n, 10) elseif band(n, 0xff000fff) == 0 then return shr(n, 2) + 0x00400000 end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm13(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) local r64 = parse_reg_type == "x" if n and n % 1 == 0 and n >= 0 and n <= 0xffffffff then local inv = false if band(n, 1) == 1 then n = bit.bnot(n); inv = true end local t = {} for i=1,32 do t[i] = band(n, 1); n = shr(n, 1) end local b = table.concat(t) b = b..(r64 and (inv and "1" or "0"):rep(32) or b) local p0, p1, p0a, p1a = b:match("^(0+)(1+)(0*)(1*)") if p0 then local w = p1a == "" and (r64 and 64 or 32) or #p1+#p0a if band(w, w-1) == 0 and b == b:sub(1, w):rep(64/w) then local s = band(-2*w, 0x3f) - 1 if w == 64 then s = s + 0x1000 end if inv then return shl(w-#p1-#p0, 16) + shl(s+w-#p1, 10) else return shl(w-#p0, 16) + shl(s+#p1, 10) end end end werror("out of range immediate `"..imm.."'") elseif r64 then waction("IMM13X", 0, format("(unsigned int)(%s)", imm)) actargs[#actargs+1] = format("(unsigned int)((unsigned long long)(%s)>>32)", imm) return 0 else waction("IMM13W", 0, imm) return 0 end end local function parse_imm6(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then if n >= 0 and n <= 63 then return shl(band(n, 0x1f), 19) + (n >= 32 and 0x80000000 or 0) end werror("out of range immediate `"..imm.."'") else waction("IMM6", 0, imm) return 0 end end local function parse_imm_load(imm, scale) local n = parse_number(imm) if n then local m = sar(n, scale) if shl(m, scale) == n and m >= 0 and m < 0x1000 then return shl(m, 10) + 0x01000000 -- Scaled, unsigned 12 bit offset. elseif n >= -256 and n < 256 then return shl(band(n, 511), 12) -- Unscaled, signed 9 bit offset. end werror("out of range immediate `"..imm.."'") else waction("IMML", scale, imm) return 0 end end local function parse_fpimm(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then local m, e = math.frexp(n) local s, e2 = 0, band(e-2, 7) if m < 0 then m = -m; s = 0x00100000 end m = m*32-16 if m % 1 == 0 and m >= 0 and m <= 15 and sar(shl(e2, 29), 29)+2 == e then return s + shl(e2, 17) + shl(m, 13) end werror("out of range immediate `"..imm.."'") else werror("NYI fpimm action") end end local function parse_shift(expr) local s, s2 = match(expr, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end return parse_imm(s2, 6, 10, 0, false) + shl(s, 22) end local function parse_lslx16(expr) local n = match(expr, "^lsl%s*#(%d+)$") n = tonumber(n) if not n then werror("expected shift operand") end if band(n, parse_reg_type == "x" and 0xffffffcf or 0xffffffef) ~= 0 then werror("bad shift amount") end return shl(n, 17) end local function parse_extend(expr) local s, s2 = match(expr, "^(%S+)%s*(.*)$") if s == "lsl" then s = parse_reg_type == "x" and 3 or 2 else s = map_extend[s] end if not s then werror("expected extend operand") end return (s2 == "" and 0 or parse_imm(s2, 3, 10, 0, false)) + shl(s, 13) end local function parse_cond(expr, inv) local c = map_cond[expr] if not c then werror("expected condition operand") end return shl(bit.bxor(c, inv), 12) end local function parse_load(params, nparams, n, op) if params[n+2] then werror("too many operands") end local scale = shr(op, 30) local pn, p2 = params[n], params[n+1] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") if not p1 then if not p2 then local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local base, tp = parse_reg_base(reg) if tp then waction("IMML", scale, format(tp.ctypefmt, tailr)) return op + base end end end werror("expected address operand") end if p2 then if wb == "!" then werror("bad use of '!'") end op = op + parse_reg_base(p1) + parse_imm(p2, 9, 12, 0, true) + 0x400 elseif wb == "!" then local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$") if not p1a then werror("bad use of '!'") end op = op + parse_reg_base(p1a) + parse_imm(p2a, 9, 12, 0, true) + 0xc00 else local p1a, p2a = match(p1, "^([^,%s]*)%s*(.*)$") op = op + parse_reg_base(p1a) if p2a ~= "" then local imm = match(p2a, "^,%s*#(.*)$") if imm then op = op + parse_imm_load(imm, scale) else local p2b, p3b, p3s = match(p2a, "^,%s*([^,%s]*)%s*,?%s*(%S*)%s*(.*)$") op = op + parse_reg(p2b, 16) + 0x00200800 if parse_reg_type ~= "x" and parse_reg_type ~= "w" then werror("bad index register type") end if p3b == "" then if parse_reg_type ~= "x" then werror("bad index register type") end op = op + 0x6000 else if p3s == "" or p3s == "#0" then elseif p3s == "#"..scale then op = op + 0x1000 else werror("bad scale") end if parse_reg_type == "x" then if p3b == "lsl" and p3s ~= "" then op = op + 0x6000 elseif p3b == "sxtx" then op = op + 0xe000 else werror("bad extend/shift specifier") end else if p3b == "uxtw" then op = op + 0x4000 elseif p3b == "sxtw" then op = op + 0xc000 else werror("bad extend/shift specifier") end end end end else if wb == "!" then werror("bad use of '!'") end op = op + 0x01000000 end end return op end local function parse_load_pair(params, nparams, n, op) if params[n+2] then werror("too many operands") end local pn, p2 = params[n], params[n+1] local scale = shr(op, 30) == 0 and 2 or 3 local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") if not p1 then if not p2 then local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local base, tp = parse_reg_base(reg) if tp then waction("IMM", 32768+7*32+15+scale*1024, format(tp.ctypefmt, tailr)) return op + base + 0x01000000 end end end werror("expected address operand") end if p2 then if wb == "!" then werror("bad use of '!'") end op = op + 0x00800000 else local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$") if p1a then p1, p2 = p1a, p2a else p2 = "#0" end op = op + (wb == "!" and 0x01800000 or 0x01000000) end return op + parse_reg_base(p1) + parse_imm(p2, 7, 15, scale, true) end local function parse_label(label, def) local prefix = label:sub(1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, label:sub(3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[label:sub(3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end -- &expr (pointer) if label:sub(1, 1) == "&" then return "A", 0, format("(ptrdiff_t)(%s)", label:sub(2)) end end end local function branch_type(op) if band(op, 0x7c000000) == 0x14000000 then return 0 -- B, BL elseif shr(op, 24) == 0x54 or band(op, 0x7e000000) == 0x34000000 or band(op, 0x3b000000) == 0x18000000 then return 0x800 -- B.cond, CBZ, CBNZ, LDR* literal elseif band(op, 0x7e000000) == 0x36000000 then return 0x1000 -- TBZ, TBNZ elseif band(op, 0x9f000000) == 0x10000000 then return 0x2000 -- ADR elseif band(op, 0x9f000000) == band(0x90000000) then return 0x3000 -- ADRP else assert(false, "unknown branch type") end end ------------------------------------------------------------------------------ local map_op, op_template local function op_alias(opname, f) return function(params, nparams) if not params then return "-> "..opname:sub(1, -3) end f(params, nparams) op_template(params, map_op[opname], nparams) end end local function alias_bfx(p) p[4] = "#("..p[3]:sub(2)..")+("..p[4]:sub(2)..")-1" end local function alias_bfiz(p) parse_reg(p[1], 0) if parse_reg_type == "w" then p[3] = "#(32-("..p[3]:sub(2).."))%32" p[4] = "#("..p[4]:sub(2)..")-1" else p[3] = "#(64-("..p[3]:sub(2).."))%64" p[4] = "#("..p[4]:sub(2)..")-1" end end local alias_lslimm = op_alias("ubfm_4", function(p) parse_reg(p[1], 0) local sh = p[3]:sub(2) if parse_reg_type == "w" then p[3] = "#(32-("..sh.."))%32" p[4] = "#31-("..sh..")" else p[3] = "#(64-("..sh.."))%64" p[4] = "#63-("..sh..")" end end) -- Template strings for ARM instructions. map_op = { -- Basic data processing instructions. add_3 = "0b000000DNMg|11000000pDpNIg|8b206000pDpNMx", add_4 = "0b000000DNMSg|0b200000DNMXg|8b200000pDpNMXx|8b200000pDpNxMwX", adds_3 = "2b000000DNMg|31000000DpNIg|ab206000DpNMx", adds_4 = "2b000000DNMSg|2b200000DNMXg|ab200000DpNMXx|ab200000DpNxMwX", cmn_2 = "2b00001fNMg|3100001fpNIg|ab20601fpNMx", cmn_3 = "2b00001fNMSg|2b20001fNMXg|ab20001fpNMXx|ab20001fpNxMwX", sub_3 = "4b000000DNMg|51000000pDpNIg|cb206000pDpNMx", sub_4 = "4b000000DNMSg|4b200000DNMXg|cb200000pDpNMXx|cb200000pDpNxMwX", subs_3 = "6b000000DNMg|71000000DpNIg|eb206000DpNMx", subs_4 = "6b000000DNMSg|6b200000DNMXg|eb200000DpNMXx|eb200000DpNxMwX", cmp_2 = "6b00001fNMg|7100001fpNIg|eb20601fpNMx", cmp_3 = "6b00001fNMSg|6b20001fNMXg|eb20001fpNMXx|eb20001fpNxMwX", neg_2 = "4b0003e0DMg", neg_3 = "4b0003e0DMSg", negs_2 = "6b0003e0DMg", negs_3 = "6b0003e0DMSg", adc_3 = "1a000000DNMg", adcs_3 = "3a000000DNMg", sbc_3 = "5a000000DNMg", sbcs_3 = "7a000000DNMg", ngc_2 = "5a0003e0DMg", ngcs_2 = "7a0003e0DMg", and_3 = "0a000000DNMg|12000000pDNig", and_4 = "0a000000DNMSg", orr_3 = "2a000000DNMg|32000000pDNig", orr_4 = "2a000000DNMSg", eor_3 = "4a000000DNMg|52000000pDNig", eor_4 = "4a000000DNMSg", ands_3 = "6a000000DNMg|72000000DNig", ands_4 = "6a000000DNMSg", tst_2 = "6a00001fNMg|7200001fNig", tst_3 = "6a00001fNMSg", bic_3 = "0a200000DNMg", bic_4 = "0a200000DNMSg", orn_3 = "2a200000DNMg", orn_4 = "2a200000DNMSg", eon_3 = "4a200000DNMg", eon_4 = "4a200000DNMSg", bics_3 = "6a200000DNMg", bics_4 = "6a200000DNMSg", movn_2 = "12800000DWg", movn_3 = "12800000DWRg", movz_2 = "52800000DWg", movz_3 = "52800000DWRg", movk_2 = "72800000DWg", movk_3 = "72800000DWRg", -- TODO: this doesn't cover all valid immediates for mov reg, #imm. mov_2 = "2a0003e0DMg|52800000DW|320003e0pDig|11000000pDpNg", mov_3 = "2a0003e0DMSg", mvn_2 = "2a2003e0DMg", mvn_3 = "2a2003e0DMSg", adr_2 = "10000000DBx", adrp_2 = "90000000DBx", csel_4 = "1a800000DNMCg", csinc_4 = "1a800400DNMCg", csinv_4 = "5a800000DNMCg", csneg_4 = "5a800400DNMCg", cset_2 = "1a9f07e0Dcg", csetm_2 = "5a9f03e0Dcg", cinc_3 = "1a800400DNmcg", cinv_3 = "5a800000DNmcg", cneg_3 = "5a800400DNmcg", ccmn_4 = "3a400000NMVCg|3a400800N5VCg", ccmp_4 = "7a400000NMVCg|7a400800N5VCg", madd_4 = "1b000000DNMAg", msub_4 = "1b008000DNMAg", mul_3 = "1b007c00DNMg", mneg_3 = "1b00fc00DNMg", smaddl_4 = "9b200000DxNMwAx", smsubl_4 = "9b208000DxNMwAx", smull_3 = "9b207c00DxNMw", smnegl_3 = "9b20fc00DxNMw", smulh_3 = "9b407c00DNMx", umaddl_4 = "9ba00000DxNMwAx", umsubl_4 = "9ba08000DxNMwAx", umull_3 = "9ba07c00DxNMw", umnegl_3 = "9ba0fc00DxNMw", umulh_3 = "9bc07c00DNMx", udiv_3 = "1ac00800DNMg", sdiv_3 = "1ac00c00DNMg", -- Bit operations. sbfm_4 = "13000000DN12w|93400000DN12x", bfm_4 = "33000000DN12w|b3400000DN12x", ubfm_4 = "53000000DN12w|d3400000DN12x", extr_4 = "13800000DNM2w|93c00000DNM2x", sxtb_2 = "13001c00DNw|93401c00DNx", sxth_2 = "13003c00DNw|93403c00DNx", sxtw_2 = "93407c00DxNw", uxtb_2 = "53001c00DNw", uxth_2 = "53003c00DNw", sbfx_4 = op_alias("sbfm_4", alias_bfx), bfxil_4 = op_alias("bfm_4", alias_bfx), ubfx_4 = op_alias("ubfm_4", alias_bfx), sbfiz_4 = op_alias("sbfm_4", alias_bfiz), bfi_4 = op_alias("bfm_4", alias_bfiz), ubfiz_4 = op_alias("ubfm_4", alias_bfiz), lsl_3 = function(params, nparams) if params and params[3]:byte() == 35 then return alias_lslimm(params, nparams) else return op_template(params, "1ac02000DNMg", nparams) end end, lsr_3 = "1ac02400DNMg|53007c00DN1w|d340fc00DN1x", asr_3 = "1ac02800DNMg|13007c00DN1w|9340fc00DN1x", ror_3 = "1ac02c00DNMg|13800000DNm2w|93c00000DNm2x", clz_2 = "5ac01000DNg", cls_2 = "5ac01400DNg", rbit_2 = "5ac00000DNg", rev_2 = "5ac00800DNw|dac00c00DNx", rev16_2 = "5ac00400DNg", rev32_2 = "dac00800DNx", -- Loads and stores. ["strb_*"] = "38000000DwL", ["ldrb_*"] = "38400000DwL", ["ldrsb_*"] = "38c00000DwL|38800000DxL", ["strh_*"] = "78000000DwL", ["ldrh_*"] = "78400000DwL", ["ldrsh_*"] = "78c00000DwL|78800000DxL", ["str_*"] = "b8000000DwL|f8000000DxL|bc000000DsL|fc000000DdL", ["ldr_*"] = "18000000DwB|58000000DxB|1c000000DsB|5c000000DdB|b8400000DwL|f8400000DxL|bc400000DsL|fc400000DdL", ["ldrsw_*"] = "98000000DxB|b8800000DxL", -- NOTE: ldur etc. are handled by ldr et al. ["stp_*"] = "28000000DAwP|a8000000DAxP|2c000000DAsP|6c000000DAdP", ["ldp_*"] = "28400000DAwP|a8400000DAxP|2c400000DAsP|6c400000DAdP", ["ldpsw_*"] = "68400000DAxP", -- Branches. b_1 = "14000000B", bl_1 = "94000000B", blr_1 = "d63f0000Nx", br_1 = "d61f0000Nx", ret_0 = "d65f03c0", ret_1 = "d65f0000Nx", -- b.cond is added below. cbz_2 = "34000000DBg", cbnz_2 = "35000000DBg", tbz_3 = "36000000DTBw|36000000DTBx", tbnz_3 = "37000000DTBw|37000000DTBx", -- Miscellaneous instructions. -- TODO: hlt, hvc, smc, svc, eret, dcps[123], drps, mrs, msr -- TODO: sys, sysl, ic, dc, at, tlbi -- TODO: hint, yield, wfe, wfi, sev, sevl -- TODO: clrex, dsb, dmb, isb nop_0 = "d503201f", brk_0 = "d4200000", brk_1 = "d4200000W", -- Floating point instructions. fmov_2 = "1e204000DNf|1e260000DwNs|1e270000DsNw|9e660000DxNd|9e670000DdNx|1e201000DFf", fabs_2 = "1e20c000DNf", fneg_2 = "1e214000DNf", fsqrt_2 = "1e21c000DNf", fcvt_2 = "1e22c000DdNs|1e624000DsNd", -- TODO: half-precision and fixed-point conversions. fcvtas_2 = "1e240000DwNs|9e240000DxNs|1e640000DwNd|9e640000DxNd", fcvtau_2 = "1e250000DwNs|9e250000DxNs|1e650000DwNd|9e650000DxNd", fcvtms_2 = "1e300000DwNs|9e300000DxNs|1e700000DwNd|9e700000DxNd", fcvtmu_2 = "1e310000DwNs|9e310000DxNs|1e710000DwNd|9e710000DxNd", fcvtns_2 = "1e200000DwNs|9e200000DxNs|1e600000DwNd|9e600000DxNd", fcvtnu_2 = "1e210000DwNs|9e210000DxNs|1e610000DwNd|9e610000DxNd", fcvtps_2 = "1e280000DwNs|9e280000DxNs|1e680000DwNd|9e680000DxNd", fcvtpu_2 = "1e290000DwNs|9e290000DxNs|1e690000DwNd|9e690000DxNd", fcvtzs_2 = "1e380000DwNs|9e380000DxNs|1e780000DwNd|9e780000DxNd", fcvtzu_2 = "1e390000DwNs|9e390000DxNs|1e790000DwNd|9e790000DxNd", scvtf_2 = "1e220000DsNw|9e220000DsNx|1e620000DdNw|9e620000DdNx", ucvtf_2 = "1e230000DsNw|9e230000DsNx|1e630000DdNw|9e630000DdNx", frintn_2 = "1e244000DNf", frintp_2 = "1e24c000DNf", frintm_2 = "1e254000DNf", frintz_2 = "1e25c000DNf", frinta_2 = "1e264000DNf", frintx_2 = "1e274000DNf", frinti_2 = "1e27c000DNf", fadd_3 = "1e202800DNMf", fsub_3 = "1e203800DNMf", fmul_3 = "1e200800DNMf", fnmul_3 = "1e208800DNMf", fdiv_3 = "1e201800DNMf", fmadd_4 = "1f000000DNMAf", fmsub_4 = "1f008000DNMAf", fnmadd_4 = "1f200000DNMAf", fnmsub_4 = "1f208000DNMAf", fmax_3 = "1e204800DNMf", fmaxnm_3 = "1e206800DNMf", fmin_3 = "1e205800DNMf", fminnm_3 = "1e207800DNMf", fcmp_2 = "1e202000NMf|1e202008NZf", fcmpe_2 = "1e202010NMf|1e202018NZf", fccmp_4 = "1e200400NMVCf", fccmpe_4 = "1e200410NMVCf", fcsel_4 = "1e200c00DNMCf", -- TODO: crc32*, aes*, sha*, pmull -- TODO: SIMD instructions. } for cond,c in pairs(map_cond) do map_op["b"..cond.."_1"] = tohex(0x54000000+c).."B" end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. local function parse_template(params, template, nparams, pos) local op = tonumber(template:sub(1, 8), 16) local n = 1 local rtt = {} parse_reg_type = false -- Process each character. for p in gmatch(template:sub(9), ".") do local q = params[n] if p == "D" then op = op + parse_reg(q, 0); n = n + 1 elseif p == "N" then op = op + parse_reg(q, 5); n = n + 1 elseif p == "M" then op = op + parse_reg(q, 16); n = n + 1 elseif p == "A" then op = op + parse_reg(q, 10); n = n + 1 elseif p == "m" then op = op + parse_reg(params[n-1], 16) elseif p == "p" then if q == "sp" then params[n] = "@x31" end elseif p == "g" then if parse_reg_type == "x" then op = op + 0x80000000 elseif parse_reg_type ~= "w" then werror("bad register type") end parse_reg_type = false elseif p == "f" then if parse_reg_type == "d" then op = op + 0x00400000 elseif parse_reg_type ~= "s" then werror("bad register type") end parse_reg_type = false elseif p == "x" or p == "w" or p == "d" or p == "s" then if parse_reg_type ~= p then werror("register size mismatch") end parse_reg_type = false elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "P" then op = parse_load_pair(params, nparams, n, op) elseif p == "B" then local mode, v, s = parse_label(q, false); n = n + 1 if not mode then werror("bad label `"..q.."'") end local m = branch_type(op) if mode == "A" then waction("REL_"..mode, v+m, format("(unsigned int)(%s)", s)) actargs[#actargs+1] = format("(unsigned int)((%s)>>32)", s) else waction("REL_"..mode, v+m, s, 1) end elseif p == "I" then op = op + parse_imm12(q); n = n + 1 elseif p == "i" then op = op + parse_imm13(q); n = n + 1 elseif p == "W" then op = op + parse_imm(q, 16, 5, 0, false); n = n + 1 elseif p == "T" then op = op + parse_imm6(q); n = n + 1 elseif p == "1" then op = op + parse_imm(q, 6, 16, 0, false); n = n + 1 elseif p == "2" then op = op + parse_imm(q, 6, 10, 0, false); n = n + 1 elseif p == "5" then op = op + parse_imm(q, 5, 16, 0, false); n = n + 1 elseif p == "V" then op = op + parse_imm(q, 4, 0, 0, false); n = n + 1 elseif p == "F" then op = op + parse_fpimm(q); n = n + 1 elseif p == "Z" then if q ~= "#0" and q ~= "#0.0" then werror("expected zero immediate") end n = n + 1 elseif p == "S" then op = op + parse_shift(q); n = n + 1 elseif p == "X" then op = op + parse_extend(q); n = n + 1 elseif p == "R" then op = op + parse_lslx16(q); n = n + 1 elseif p == "C" then op = op + parse_cond(q, 0); n = n + 1 elseif p == "c" then op = op + parse_cond(q, 1); n = n + 1 else assert(false) end end wputpos(pos, op) end function op_template(params, template, nparams) if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 4 positions. if secpos+4 > maxsecpos then wflush() end local pos = wpos() local lpos, apos, spos = #actlist, #actargs, secpos local ok, err for t in gmatch(template, "[^|]+") do ok, err = pcall(parse_template, params, t, nparams, pos) if ok then return end secpos = spos actlist[lpos+1] = nil actlist[lpos+2] = nil actlist[lpos+3] = nil actlist[lpos+4] = nil actargs[apos+1] = nil actargs[apos+2] = nil actargs[apos+3] = nil actargs[apos+4] = nil end error(err, 0) end map_op[".template__"] = op_template ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if not mode or mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. local function op_data(params) if not params then return "imm..." end local sz = params.op == ".long" and 4 or 8 for _,p in ipairs(params) do local imm = parse_number(p) if imm then local n = tobit(imm) if n == imm or (n < 0 and n + 2^32 == imm) then wputw(n < 0 and n + 2^32 or n) if sz == 8 then wputw(imm < 0 and 0xffffffff or 0) end elseif sz == 4 then werror("bad immediate `"..p.."'") else imm = nil end end if not imm then local mode, v, s = parse_label(p, false) if sz == 4 then if mode then werror("label does not fit into .long") end waction("IMMV", 0, p) elseif mode and mode ~= "A" then waction("REL_"..mode, v+0x8000, s, 1) else if mode == "A" then p = s end waction("IMMV", 0, format("(unsigned int)(%s)", p)) waction("IMMV", 0, format("(unsigned int)((unsigned long long)(%s)>>32)", p)) end end if secpos+2 > maxsecpos then wflush() end end end map_op[".long_*"] = op_data map_op[".quad_*"] = op_data map_op[".addr_*"] = op_data -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
gpl-3.0
qq779089973/ramod
luci/applications/luci-asterisk/luasrc/asterisk/cc_idd.lua
92
7735
--[[ LuCI - Asterisk - International Direct Dialing Prefixes and Country Codes Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module "luci.asterisk.cc_idd" CC_IDD = { -- Country, CC, IDD { "Afghanistan", "93", "00" }, { "Albania", "355", "00" }, { "Algeria", "213", "00" }, { "American Samoa", "684", "00" }, { "Andorra", "376", "00" }, { "Angola", "244", "00" }, { "Anguilla", "264", "011" }, { "Antarctica", "672", "" }, { "Antigua", "268", "011" }, { "Argentina", "54", "00" }, { "Armenia", "374", "00" }, { "Aruba", "297", "00" }, { "Ascension Island", "247", "00" }, { "Australia", "61", "0011" }, { "Austria", "43", "00" }, { "Azberbaijan", "994", "00" }, { "Bahamas", "242", "011" }, { "Bahrain", "973", "00" }, { "Bangladesh", "880", "00" }, { "Barbados", "246", "011" }, { "Barbuda", "268", "011" }, { "Belarus", "375", "810" }, { "Belgium", "32", "00" }, { "Belize", "501", "00" }, { "Benin", "229", "00" }, { "Bermuda", "441", "011" }, { "Bhutan", "975", "00" }, { "Bolivia", "591", "00" }, { "Bosnia", "387", "00" }, { "Botswana", "267", "00" }, { "Brazil", "55", "00" }, { "British Virgin Islands", "284", "011" }, { "Brunei", "673", "00" }, { "Bulgaria", "359", "00" }, { "Burkina Faso", "226", "00" }, { "Burma (Myanmar)", "95", "00" }, { "Burundi", "257", "00" }, { "Cambodia", "855", "001" }, { "Cameroon", "237", "00" }, { "Canada", "1", "011" }, { "Cape Verde Islands", "238", "0" }, { "Cayman Islands", "345", "011" }, { "Central African Rep.", "236", "00" }, { "Chad", "235", "15" }, { "Chile", "56", "00" }, { "China", "86", "00" }, { "Christmas Island", "61", "0011" }, { "Cocos Islands", "61", "0011" }, { "Colombia", "57", "00" }, { "Comoros", "269", "00" }, { "Congo", "242", "00" }, { "Congo, Dem. Rep. of", "243", "00" }, { "Cook Islands", "682", "00" }, { "Costa Rica", "506", "00" }, { "Croatia", "385", "00" }, { "Cuba", "53", "119" }, { "Cyprus", "357", "00" }, { "Czech Republic", "420", "00" }, { "Denmark", "45", "00" }, { "Diego Garcia", "246", "00" }, { "Djibouti", "253", "00" }, { "Dominica", "767", "011" }, { "Dominican Rep.", "809", "011" }, { "Ecuador", "593", "00" }, { "Egypt", "20", "00" }, { "El Salvador", "503", "00" }, { "Equatorial Guinea", "240", "00" }, { "Eritrea", "291", "00" }, { "Estonia", "372", "00" }, { "Ethiopia", "251", "00" }, { "Faeroe Islands", "298", "00" }, { "Falkland Islands", "500", "00" }, { "Fiji Islands", "679", "00" }, { "Finland", "358", "00" }, { "France", "33", "00" }, { "French Antilles", "596", "00" }, { "French Guiana", "594", "00" }, { "French Polynesia", "689", "00" }, { "Gabon", "241", "00" }, { "Gambia", "220", "00" }, { "Georgia", "995", "810" }, { "Germany", "49", "00" }, { "Ghana", "233", "00" }, { "Gibraltar", "350", "00" }, { "Greece", "30", "00" }, { "Greenland", "299", "00" }, { "Grenada", "473", "011" }, { "Guadeloupe", "590", "00" }, { "Guam", "671", "011" }, { "Guantanamo Bay", "5399", "00" }, { "Guatemala", "502", "00" }, { "Guinea", "224", "00" }, { "Guinea Bissau", "245", "00" }, { "Guyana", "592", "001" }, { "Haiti", "509", "00" }, { "Honduras", "504", "00" }, { "Hong Kong", "852", "001" }, { "Hungary", "36", "00" }, { "Iceland", "354", "00" }, { "India", "91", "00" }, { "Indonesia", "62", { "001", "008" } }, { "Iran", "98", "00" }, { "Iraq", "964", "00" }, { "Ireland", "353", "00" }, { "Israel", "972", "00" }, { "Italy", "39", "00" }, { "Ivory Coast", "225", "00" }, { "Jamaica", "876", "011" }, { "Japan", "81", "001" }, { "Jordan", "962", "00" }, { "Kazakhstan", "7", "810" }, { "Kenya", "254", "000" }, { "Kiribati", "686", "00" }, { "Korea, North", "850", "00" }, { "Korea, South", "82", "001" }, { "Kuwait", "965", "00" }, { "Kyrgyzstan", "996", "00" }, { "Laos", "856", "00" }, { "Latvia", "371", "00" }, { "Lebanon", "961", "00" }, { "Lesotho", "266", "00" }, { "Liberia", "231", "00" }, { "Libya", "218", "00" }, { "Liechtenstein", "423", "00" }, { "Lithuania", "370", "00" }, { "Luxembourg", "352", "00" }, { "Macau", "853", "00" }, { "Macedonia", "389", "00" }, { "Madagascar", "261", "00" }, { "Malawi", "265", "00" }, { "Malaysia", "60", "00" }, { "Maldives", "960", "00" }, { "Mali", "223", "00" }, { "Malta", "356", "00" }, { "Mariana Islands", "670", "011" }, { "Marshall Islands", "692", "011" }, { "Martinique", "596", "00" }, { "Mauritania", "222", "00" }, { "Mauritius", "230", "00" }, { "Mayotte Islands", "269", "00" }, { "Mexico", "52", "00" }, { "Micronesia", "691", "011" }, { "Midway Island", "808", "011" }, { "Moldova", "373", "00" }, { "Monaco", "377", "00" }, { "Mongolia", "976", "001" }, { "Montserrat", "664", "011" }, { "Morocco", "212", "00" }, { "Mozambique", "258", "00" }, { "Myanmar (Burma)", "95", "00" }, { "Namibia", "264", "00" }, { "Nauru", "674", "00" }, { "Nepal", "977", "00" }, { "Netherlands", "31", "00" }, { "Netherlands Antilles", "599", "00" }, { "Nevis", "869", "011" }, { "New Caledonia", "687", "00" }, { "New Zealand", "64", "00" }, { "Nicaragua", "505", "00" }, { "Niger", "227", "00" }, { "Nigeria", "234", "009" }, { "Niue", "683", "00" }, { "Norfolk Island", "672", "00" }, { "Norway", "47", "00" }, { "Oman", "968", "00" }, { "Pakistan", "92", "00" }, { "Palau", "680", "011" }, { "Palestine", "970", "00" }, { "Panama", "507", "00" }, { "Papua New Guinea", "675", "05" }, { "Paraguay", "595", "002" }, { "Peru", "51", "00" }, { "Philippines", "63", "00" }, { "Poland", "48", "00" }, { "Portugal", "351", "00" }, { "Puerto Rico", { "787", "939" }, "011" }, { "Qatar", "974", "00" }, { "Reunion Island", "262", "00" }, { "Romania", "40", "00" }, { "Russia", "7", "810" }, { "Rwanda", "250", "00" }, { "St. Helena", "290", "00" }, { "St. Kitts", "869", "011" }, { "St. Lucia", "758", "011" }, { "St. Perre & Miquelon", "508", "00" }, { "St. Vincent", "784", "011" }, { "San Marino", "378", "00" }, { "Sao Tome & Principe", "239", "00" }, { "Saudi Arabia", "966", "00" }, { "Senegal", "221", "00" }, { "Serbia", "381", "99" }, { "Seychelles", "248", "00" }, { "Sierra Leone", "232", "00" }, { "Singapore", "65", "001" }, { "Slovakia", "421", "00" }, { "Slovenia", "386", "00" }, { "Solomon Islands", "677", "00" }, { "Somalia", "252", "00" }, { "South Africa", "27", "09" }, { "Spain", "34", "00" }, { "Sri Lanka", "94", "00" }, { "Sudan", "249", "00" }, { "Suriname", "597", "00" }, { "Swaziland", "268", "00" }, { "Sweden", "46", "00" }, { "Switzerland", "41", "00" }, { "Syria", "963", "00" }, { "Taiwan", "886", "002" }, { "Tajikistan", "992", "810" }, { "Tanzania", "255", "00" }, { "Thailand", "66", "001" }, { "Togo", "228", "00" }, { "Tonga", "676", "00" }, { "Trinidad & Tobago", "868", "011" }, { "Tunisia", "216", "00" }, { "Turkey", "90", "00" }, { "Turkmenistan", "993", "810" }, { "Turks & Caicos", "649", "011" }, { "Tuvalu", "688", "00" }, { "Uganda", "256", "000" }, { "Ukraine", "380", "810" }, { "United Arab Emirates", "971", "00" }, { "United Kingdom", "44", "00" }, { "Uruguay", "598", "00" }, { "USA", "1", "011" }, { "US Virgin Islands", "340", "011" }, { "Uzbekistan", "998", "810" }, { "Vanuatu", "678", "00" }, { "Vatican City", "39", "00" }, { "Venezuela", "58", "00" }, { "Vietnam", "84", "00" }, { "Wake Island", "808", "00" }, { "Wallis & Futuna", "681", "19" }, { "Western Samoa", "685", "00" }, { "Yemen", "967", "00" }, { "Yugoslavia", "381", "99" }, { "Zambia", "260", "00" }, { "Zimbabwe", "263", "00" } }
mit
Noltari/luci
modules/luci-base/luasrc/cbi.lua
9
43526
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. module("luci.cbi", package.seeall) require("luci.template") local util = require("luci.util") require("luci.http") --local event = require "luci.sys.event" local fs = require("nixio.fs") local uci = require("luci.model.uci") local datatypes = require("luci.cbi.datatypes") local dispatcher = require("luci.dispatcher") local class = util.class local instanceof = util.instanceof FORM_NODATA = 0 FORM_PROCEED = 0 FORM_VALID = 1 FORM_DONE = 1 FORM_INVALID = -1 FORM_CHANGED = 2 FORM_SKIP = 4 AUTO = true CREATE_PREFIX = "cbi.cts." REMOVE_PREFIX = "cbi.rts." RESORT_PREFIX = "cbi.sts." FEXIST_PREFIX = "cbi.cbe." -- Loads a CBI map from given file, creating an environment and returns it function load(cbimap, ...) local fs = require "nixio.fs" local i18n = require "luci.i18n" require("luci.config") require("luci.util") local upldir = "/etc/luci-uploads/" local cbidir = luci.util.libpath() .. "/model/cbi/" local func, err if fs.access(cbidir..cbimap..".lua") then func, err = loadfile(cbidir..cbimap..".lua") elseif fs.access(cbimap) then func, err = loadfile(cbimap) else func, err = nil, "Model '" .. cbimap .. "' not found!" end assert(func, err) local env = { translate=i18n.translate, translatef=i18n.translatef, arg={...} } setfenv(func, setmetatable(env, {__index = function(tbl, key) return rawget(tbl, key) or _M[key] or _G[key] end})) local maps = { func() } local uploads = { } local has_upload = false for i, map in ipairs(maps) do if not instanceof(map, Node) then error("CBI map returns no valid map object!") return nil else map:prepare() if map.upload_fields then has_upload = true for _, field in ipairs(map.upload_fields) do uploads[ field.config .. '.' .. (field.section.sectiontype or '1') .. '.' .. field.option ] = true end end end end if has_upload then local uci = luci.model.uci.cursor() local prm = luci.http.context.request.message.params local fd, cbid luci.http.setfilehandler( function( field, chunk, eof ) if not field then return end if field.name and not cbid then local c, s, o = field.name:gmatch( "cbid%.([^%.]+)%.([^%.]+)%.([^%.]+)" )() if c and s and o then local t = uci:get( c, s ) or s if uploads[c.."."..t.."."..o] then local path = upldir .. field.name fd = io.open(path, "w") if fd then cbid = field.name prm[cbid] = path end end end end if field.name == cbid and fd then fd:write(chunk) end if eof and fd then fd:close() fd = nil cbid = nil end end ) end return maps end -- -- Compile a datatype specification into a parse tree for evaluation later on -- local cdt_cache = { } function compile_datatype(code) local i local pos = 0 local esc = false local depth = 0 local stack = { } for i = 1, #code+1 do local byte = code:byte(i) or 44 if esc then esc = false elseif byte == 92 then esc = true elseif byte == 40 or byte == 44 then if depth <= 0 then if pos < i then local label = code:sub(pos, i-1) :gsub("\\(.)", "%1") :gsub("^%s+", "") :gsub("%s+$", "") if #label > 0 and tonumber(label) then stack[#stack+1] = tonumber(label) elseif label:match("^'.*'$") or label:match('^".*"$') then stack[#stack+1] = label:gsub("[\"'](.*)[\"']", "%1") elseif type(datatypes[label]) == "function" then stack[#stack+1] = datatypes[label] stack[#stack+1] = { } else error("Datatype error, bad token %q" % label) end end pos = i + 1 end depth = depth + (byte == 40 and 1 or 0) elseif byte == 41 then depth = depth - 1 if depth <= 0 then if type(stack[#stack-1]) ~= "function" then error("Datatype error, argument list follows non-function") end stack[#stack] = compile_datatype(code:sub(pos, i-1)) pos = i + 1 end end end return stack end function verify_datatype(dt, value) if dt and #dt > 0 then if not cdt_cache[dt] then local c = compile_datatype(dt) if c and type(c[1]) == "function" then cdt_cache[dt] = c else error("Datatype error, not a function expression") end end if cdt_cache[dt] then return cdt_cache[dt][1](value, unpack(cdt_cache[dt][2])) end end return true end -- Node pseudo abstract class Node = class() function Node.__init__(self, title, description) self.children = {} self.title = title or "" self.description = description or "" self.template = "cbi/node" end -- hook helper function Node._run_hook(self, hook) if type(self[hook]) == "function" then return self[hook](self) end end function Node._run_hooks(self, ...) local f local r = false for _, f in ipairs(arg) do if type(self[f]) == "function" then self[f](self) r = true end end return r end -- Prepare nodes function Node.prepare(self, ...) for k, child in ipairs(self.children) do child:prepare(...) end end -- Append child nodes function Node.append(self, obj) table.insert(self.children, obj) end -- Parse this node and its children function Node.parse(self, ...) for k, child in ipairs(self.children) do child:parse(...) end end -- Render this node function Node.render(self, scope) scope = scope or {} scope.self = self luci.template.render(self.template, scope) end -- Render the children function Node.render_children(self, ...) local k, node for k, node in ipairs(self.children) do node.last_child = (k == #self.children) node.index = k node:render(...) end end --[[ A simple template element ]]-- Template = class(Node) function Template.__init__(self, template) Node.__init__(self) self.template = template end function Template.render(self) luci.template.render(self.template, {self=self}) end function Template.parse(self, readinput) self.readinput = (readinput ~= false) return Map.formvalue(self, "cbi.submit") and FORM_DONE or FORM_NODATA end --[[ Map - A map describing a configuration file ]]-- Map = class(Node) function Map.__init__(self, config, ...) Node.__init__(self, ...) self.config = config self.parsechain = {self.config} self.template = "cbi/map" self.apply_on_parse = nil self.readinput = true self.proceed = false self.flow = {} self.uci = uci.cursor() self.save = true self.changed = false local path = "%s/%s" %{ self.uci:get_confdir(), self.config } if fs.stat(path, "type") ~= "reg" then fs.writefile(path, "") end local ok, err = self.uci:load(self.config) if not ok then local url = dispatcher.build_url(unpack(dispatcher.context.request)) local source = self:formvalue("cbi.source") if type(source) == "string" then fs.writefile(path, source:gsub("\r\n", "\n")) ok, err = self.uci:load(self.config) if ok then luci.http.redirect(url) end end self.save = false end if not ok then self.template = "cbi/error" self.error = err self.source = fs.readfile(path) or "" self.pageaction = false end end function Map.formvalue(self, key) return self.readinput and luci.http.formvalue(key) or nil end function Map.formvaluetable(self, key) return self.readinput and luci.http.formvaluetable(key) or {} end function Map.get_scheme(self, sectiontype, option) if not option then return self.scheme and self.scheme.sections[sectiontype] else return self.scheme and self.scheme.variables[sectiontype] and self.scheme.variables[sectiontype][option] end end function Map.submitstate(self) return self:formvalue("cbi.submit") end -- Chain foreign config function Map.chain(self, config) table.insert(self.parsechain, config) end function Map.state_handler(self, state) return state end -- Use optimized UCI writing function Map.parse(self, readinput, ...) if self:formvalue("cbi.skip") then self.state = FORM_SKIP elseif not self.save then self.state = FORM_INVALID elseif not self:submitstate() then self.state = FORM_NODATA end -- Back out early to prevent unauthorized changes on the subsequent parse if self.state ~= nil then return self:state_handler(self.state) end self.readinput = (readinput ~= false) self:_run_hooks("on_parse") Node.parse(self, ...) if self.save then self:_run_hooks("on_save", "on_before_save") local i, config for i, config in ipairs(self.parsechain) do self.uci:save(config) end self:_run_hooks("on_after_save") if (not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply") then self:_run_hooks("on_before_commit") if self.apply_on_parse == false then for i, config in ipairs(self.parsechain) do self.uci:commit(config) end end self:_run_hooks("on_commit", "on_after_commit", "on_before_apply") if self.apply_on_parse == true or self.apply_on_parse == false then self.uci:apply(self.apply_on_parse) self:_run_hooks("on_apply", "on_after_apply") else -- This is evaluated by the dispatcher and delegated to the -- template which in turn fires XHR to perform the actual -- apply actions. self.apply_needed = true end -- Reparse sections Node.parse(self, true) end for i, config in ipairs(self.parsechain) do self.uci:unload(config) end if type(self.commit_handler) == "function" then self:commit_handler(self:submitstate()) end end if not self.save then self.state = FORM_INVALID elseif self.proceed then self.state = FORM_PROCEED elseif self.changed then self.state = FORM_CHANGED else self.state = FORM_VALID end return self:state_handler(self.state) end function Map.render(self, ...) self:_run_hooks("on_init") Node.render(self, ...) end -- Creates a child section function Map.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- UCI add function Map.add(self, sectiontype) return self.uci:add(self.config, sectiontype) end -- UCI set function Map.set(self, section, option, value) if type(value) ~= "table" or #value > 0 then if option then return self.uci:set(self.config, section, option, value) else return self.uci:set(self.config, section, value) end else return Map.del(self, section, option) end end -- UCI del function Map.del(self, section, option) if option then return self.uci:delete(self.config, section, option) else return self.uci:delete(self.config, section) end end -- UCI get function Map.get(self, section, option) if not section then return self.uci:get_all(self.config) elseif option then return self.uci:get(self.config, section, option) else return self.uci:get_all(self.config, section) end end --[[ Compound - Container ]]-- Compound = class(Node) function Compound.__init__(self, ...) Node.__init__(self) self.template = "cbi/compound" self.children = {...} end function Compound.populate_delegator(self, delegator) for _, v in ipairs(self.children) do v.delegator = delegator end end function Compound.parse(self, ...) local cstate, state = 0 for k, child in ipairs(self.children) do cstate = child:parse(...) state = (not state or cstate < state) and cstate or state end return state end --[[ Delegator - Node controller ]]-- Delegator = class(Node) function Delegator.__init__(self, ...) Node.__init__(self, ...) self.nodes = {} self.defaultpath = {} self.pageaction = false self.readinput = true self.allow_reset = false self.allow_cancel = false self.allow_back = false self.allow_finish = false self.template = "cbi/delegator" end function Delegator.set(self, name, node) assert(not self.nodes[name], "Duplicate entry") self.nodes[name] = node end function Delegator.add(self, name, node) node = self:set(name, node) self.defaultpath[#self.defaultpath+1] = name end function Delegator.insert_after(self, name, after) local n = #self.chain + 1 for k, v in ipairs(self.chain) do if v == after then n = k + 1 break end end table.insert(self.chain, n, name) end function Delegator.set_route(self, ...) local n, chain, route = 0, self.chain, {...} for i = 1, #chain do if chain[i] == self.current then n = i break end end for i = 1, #route do n = n + 1 chain[n] = route[i] end for i = n + 1, #chain do chain[i] = nil end end function Delegator.get(self, name) local node = self.nodes[name] if type(node) == "string" then node = load(node, name) end if type(node) == "table" and getmetatable(node) == nil then node = Compound(unpack(node)) end return node end function Delegator.parse(self, ...) if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then if self:_run_hooks("on_cancel") then return FORM_DONE end end if not Map.formvalue(self, "cbi.delg.current") then self:_run_hooks("on_init") end local newcurrent self.chain = self.chain or self:get_chain() self.current = self.current or self:get_active() self.active = self.active or self:get(self.current) assert(self.active, "Invalid state") local stat = FORM_DONE if type(self.active) ~= "function" then self.active:populate_delegator(self) stat = self.active:parse() else self:active() end if stat > FORM_PROCEED then if Map.formvalue(self, "cbi.delg.back") then newcurrent = self:get_prev(self.current) else newcurrent = self:get_next(self.current) end elseif stat < FORM_PROCEED then return stat end if not Map.formvalue(self, "cbi.submit") then return FORM_NODATA elseif stat > FORM_PROCEED and (not newcurrent or not self:get(newcurrent)) then return self:_run_hook("on_done") or FORM_DONE else self.current = newcurrent or self.current self.active = self:get(self.current) if type(self.active) ~= "function" then self.active:populate_delegator(self) local stat = self.active:parse(false) if stat == FORM_SKIP then return self:parse(...) else return FORM_PROCEED end else return self:parse(...) end end end function Delegator.get_next(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k+1] end end end function Delegator.get_prev(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k-1] end end end function Delegator.get_chain(self) local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath return type(x) == "table" and x or {x} end function Delegator.get_active(self) return Map.formvalue(self, "cbi.delg.current") or self.chain[1] end --[[ Page - A simple node ]]-- Page = class(Node) Page.__init__ = Node.__init__ Page.parse = function() end --[[ SimpleForm - A Simple non-UCI form ]]-- SimpleForm = class(Node) function SimpleForm.__init__(self, config, title, description, data) Node.__init__(self, title, description) self.config = config self.data = data or {} self.template = "cbi/simpleform" self.dorender = true self.pageaction = false self.readinput = true end SimpleForm.formvalue = Map.formvalue SimpleForm.formvaluetable = Map.formvaluetable function SimpleForm.parse(self, readinput, ...) self.readinput = (readinput ~= false) if self:formvalue("cbi.skip") then return FORM_SKIP end if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then return FORM_DONE end if self:submitstate() then Node.parse(self, 1, ...) end local valid = true for k, j in ipairs(self.children) do for i, v in ipairs(j.children) do valid = valid and (not v.tag_missing or not v.tag_missing[1]) and (not v.tag_invalid or not v.tag_invalid[1]) and (not v.error) end end local state = not self:submitstate() and FORM_NODATA or valid and FORM_VALID or FORM_INVALID self.dorender = not self.handle if self.handle then local nrender, nstate = self:handle(state, self.data) self.dorender = self.dorender or (nrender ~= false) state = nstate or state end return state end function SimpleForm.render(self, ...) if self.dorender then Node.render(self, ...) end end function SimpleForm.submitstate(self) return self:formvalue("cbi.submit") end function SimpleForm.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- Creates a child field function SimpleForm.field(self, class, ...) local section for k, v in ipairs(self.children) do if instanceof(v, SimpleSection) then section = v break end end if not section then section = self:section(SimpleSection) end if instanceof(class, AbstractValue) then local obj = class(self, section, ...) obj.track_missing = true section:append(obj) return obj else error("class must be a descendent of AbstractValue") end end function SimpleForm.set(self, section, option, value) self.data[option] = value end function SimpleForm.del(self, section, option) self.data[option] = nil end function SimpleForm.get(self, section, option) return self.data[option] end function SimpleForm.get_scheme() return nil end Form = class(SimpleForm) function Form.__init__(self, ...) SimpleForm.__init__(self, ...) self.embedded = true end --[[ AbstractSection ]]-- AbstractSection = class(Node) function AbstractSection.__init__(self, map, sectiontype, ...) Node.__init__(self, ...) self.sectiontype = sectiontype self.map = map self.config = map.config self.optionals = {} self.defaults = {} self.fields = {} self.tag_error = {} self.tag_invalid = {} self.tag_deperror = {} self.changed = false self.optional = true self.addremove = false self.dynamic = false end -- Define a tab for the section function AbstractSection.tab(self, tab, title, desc) self.tabs = self.tabs or { } self.tab_names = self.tab_names or { } self.tab_names[#self.tab_names+1] = tab self.tabs[tab] = { title = title, description = desc, childs = { } } end -- Check whether the section has tabs function AbstractSection.has_tabs(self) return (self.tabs ~= nil) and (next(self.tabs) ~= nil) end -- Appends a new option function AbstractSection.option(self, class, option, ...) if instanceof(class, AbstractValue) then local obj = class(self.map, self, option, ...) self:append(obj) self.fields[option] = obj return obj elseif class == true then error("No valid class was given and autodetection failed.") else error("class must be a descendant of AbstractValue") end end -- Appends a new tabbed option function AbstractSection.taboption(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot assign option to not existing tab %q" % tostring(tab)) local l = self.tabs[tab].childs local o = AbstractSection.option(self, ...) if o then l[#l+1] = o end return o end -- Render a single tab function AbstractSection.render_tab(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot render not existing tab %q" % tostring(tab)) local k, node for k, node in ipairs(self.tabs[tab].childs) do node.last_child = (k == #self.tabs[tab].childs) node.index = k node:render(...) end end -- Parse optional options function AbstractSection.parse_optionals(self, section, noparse) if not self.optional then return end self.optionals[section] = {} local field = nil if not noparse then field = self.map:formvalue("cbi.opt."..self.config.."."..section) end for k,v in ipairs(self.children) do if v.optional and not v:cfgvalue(section) and not self:has_tabs() then if field == v.option then field = nil self.map.proceed = true else table.insert(self.optionals[section], v) end end end if field and #field > 0 and self.dynamic then self:add_dynamic(field) end end -- Add a dynamic option function AbstractSection.add_dynamic(self, field, optional) local o = self:option(Value, field, field) o.optional = optional end -- Parse all dynamic options function AbstractSection.parse_dynamic(self, section) if not self.dynamic then return end local arr = luci.util.clone(self:cfgvalue(section)) local form = self.map:formvaluetable("cbid."..self.config.."."..section) for k, v in pairs(form) do arr[k] = v end for key,val in pairs(arr) do local create = true for i,c in ipairs(self.children) do if c.option == key then create = false end end if create and key:sub(1, 1) ~= "." then self.map.proceed = true self:add_dynamic(key, true) end end end -- Returns the section's UCI table function AbstractSection.cfgvalue(self, section) return self.map:get(section) end -- Push events function AbstractSection.push_events(self) --luci.util.append(self.map.events, self.events) self.map.changed = true end -- Removes the section function AbstractSection.remove(self, section) self.map.proceed = true return self.map:del(section) end -- Creates the section function AbstractSection.create(self, section) local stat if section then stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype) else section = self.map:add(self.sectiontype) stat = section end if stat then for k,v in pairs(self.children) do if v.default then self.map:set(section, v.option, v.default) end end for k,v in pairs(self.defaults) do self.map:set(section, k, v) end end self.map.proceed = true return stat end SimpleSection = class(AbstractSection) function SimpleSection.__init__(self, form, ...) AbstractSection.__init__(self, form, nil, ...) self.template = "cbi/nullsection" end Table = class(AbstractSection) function Table.__init__(self, form, data, ...) local datasource = {} local tself = self datasource.config = "table" self.data = data or {} datasource.formvalue = Map.formvalue datasource.formvaluetable = Map.formvaluetable datasource.readinput = true function datasource.get(self, section, option) return tself.data[section] and tself.data[section][option] end function datasource.submitstate(self) return Map.formvalue(self, "cbi.submit") end function datasource.del(...) return true end function datasource.get_scheme() return nil end AbstractSection.__init__(self, datasource, "table", ...) self.template = "cbi/tblsection" self.rowcolors = true self.anonymous = true end function Table.parse(self, readinput) self.map.readinput = (readinput ~= false) for i, k in ipairs(self:cfgsections()) do if self.map:submitstate() then Node.parse(self, k) end end end function Table.cfgsections(self) local sections = {} for i, v in luci.util.kspairs(self.data) do table.insert(sections, i) end return sections end function Table.update(self, data) self.data = data end --[[ NamedSection - A fixed configuration section defined by its name ]]-- NamedSection = class(AbstractSection) function NamedSection.__init__(self, map, section, stype, ...) AbstractSection.__init__(self, map, stype, ...) -- Defaults self.addremove = false self.template = "cbi/nsection" self.section = section end function NamedSection.prepare(self) AbstractSection.prepare(self) AbstractSection.parse_optionals(self, self.section, true) end function NamedSection.parse(self, novld) local s = self.section local active = self:cfgvalue(s) if self.addremove then local path = self.config.."."..s if active then -- Remove the section if self.map:formvalue("cbi.rns."..path) and self:remove(s) then self:push_events() return end else -- Create and apply default values if self.map:formvalue("cbi.cns."..path) then self:create(s) return end end end if active then AbstractSection.parse_dynamic(self, s) if self.map:submitstate() then Node.parse(self, s) end AbstractSection.parse_optionals(self, s) if self.changed then self:push_events() end end end --[[ TypedSection - A (set of) configuration section(s) defined by the type addremove: Defines whether the user can add/remove sections of this type anonymous: Allow creating anonymous sections validate: a validation function returning nil if the section is invalid ]]-- TypedSection = class(AbstractSection) function TypedSection.__init__(self, map, type, ...) AbstractSection.__init__(self, map, type, ...) self.template = "cbi/tsection" self.deps = {} self.anonymous = false end function TypedSection.prepare(self) AbstractSection.prepare(self) local i, s for i, s in ipairs(self:cfgsections()) do AbstractSection.parse_optionals(self, s, true) end end -- Return all matching UCI sections for this TypedSection function TypedSection.cfgsections(self) local sections = {} self.map.uci:foreach(self.map.config, self.sectiontype, function (section) if self:checkscope(section[".name"]) then table.insert(sections, section[".name"]) end end) return sections end -- Limits scope to sections that have certain option => value pairs function TypedSection.depends(self, option, value) table.insert(self.deps, {option=option, value=value}) end function TypedSection.parse(self, novld) if self.addremove then -- Remove local crval = REMOVE_PREFIX .. self.config local name = self.map:formvaluetable(crval) for k,v in pairs(name) do if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end if self:cfgvalue(k) and self:checkscope(k) then self:remove(k) end end end local co for i, k in ipairs(self:cfgsections()) do AbstractSection.parse_dynamic(self, k) if self.map:submitstate() then Node.parse(self, k, novld) end AbstractSection.parse_optionals(self, k) end if self.addremove then -- Create local created local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype local origin, name = next(self.map:formvaluetable(crval)) if self.anonymous then if name then created = self:create(nil, origin) end else if name then -- Ignore if it already exists if self:cfgvalue(name) then name = nil self.err_invalid = true else name = self:checkscope(name) if not name then self.err_invalid = true end if name and #name > 0 then created = self:create(name, origin) and name if not created then self.invalid_cts = true end end end end end if created then AbstractSection.parse_optionals(self, created) end end if self.sortable then local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype local order = self.map:formvalue(stval) if order and #order > 0 then local sids, sid = { }, nil for sid in util.imatch(order) do sids[#sids+1] = sid end if #sids > 0 then self.map.uci:reorder(self.config, sids) self.changed = true end end end if created or self.changed then self:push_events() end end -- Verifies scope of sections function TypedSection.checkscope(self, section) -- Check if we are not excluded if self.filter and not self:filter(section) then return nil end -- Check if at least one dependency is met if #self.deps > 0 and self:cfgvalue(section) then local stat = false for k, v in ipairs(self.deps) do if self:cfgvalue(section)[v.option] == v.value then stat = true end end if not stat then return nil end end return self:validate(section) end -- Dummy validate function function TypedSection.validate(self, section) return section end --[[ AbstractValue - An abstract Value Type null: Value can be empty valid: A function returning the value if it is valid otherwise nil depends: A table of option => value pairs of which one must be true default: The default value size: The size of the input fields rmempty: Unset value if empty optional: This value is optional (see AbstractSection.optionals) ]]-- AbstractValue = class(Node) function AbstractValue.__init__(self, map, section, option, ...) Node.__init__(self, ...) self.section = section self.option = option self.map = map self.config = map.config self.tag_invalid = {} self.tag_missing = {} self.tag_reqerror = {} self.tag_error = {} self.deps = {} --self.cast = "string" self.track_missing = false self.rmempty = true self.default = nil self.size = nil self.optional = false end function AbstractValue.prepare(self) self.cast = self.cast or "string" end -- Add a dependencie to another section field function AbstractValue.depends(self, field, value) local deps if type(field) == "string" then deps = {} deps[field] = value else deps = field end table.insert(self.deps, deps) end -- Serialize dependencies function AbstractValue.deplist2json(self, section, deplist) local deps, i, d = { } if type(self.deps) == "table" then for i, d in ipairs(deplist or self.deps) do local a, k, v = { } for k, v in pairs(d) do if k:find("!", 1, true) then a[k] = v elseif k:find(".", 1, true) then a['cbid.%s' % k] = v else a['cbid.%s.%s.%s' %{ self.config, section, k }] = v end end deps[#deps+1] = a end end return util.serialize_json(deps) end -- Serialize choices function AbstractValue.choices(self) if type(self.keylist) == "table" and #self.keylist > 0 then local i, k, v = nil, nil, {} for i, k in ipairs(self.keylist) do v[k] = self.vallist[i] or k end return v end return nil end -- Generates the unique CBID function AbstractValue.cbid(self, section) return "cbid."..self.map.config.."."..section.."."..self.option end -- Return whether this object should be created function AbstractValue.formcreated(self, section) local key = "cbi.opt."..self.config.."."..section return (self.map:formvalue(key) == self.option) end -- Returns the formvalue for this object function AbstractValue.formvalue(self, section) return self.map:formvalue(self:cbid(section)) end function AbstractValue.additional(self, value) self.optional = value end function AbstractValue.mandatory(self, value) self.rmempty = not value end function AbstractValue.add_error(self, section, type, msg) self.error = self.error or { } self.error[section] = msg or type self.section.error = self.section.error or { } self.section.error[section] = self.section.error[section] or { } table.insert(self.section.error[section], msg or type) if type == "invalid" then self.tag_invalid[section] = true elseif type == "missing" then self.tag_missing[section] = true end self.tag_error[section] = true self.map.save = false end function AbstractValue.parse(self, section, novld) local fvalue = self:formvalue(section) local cvalue = self:cfgvalue(section) -- If favlue and cvalue are both tables and have the same content -- make them identical if type(fvalue) == "table" and type(cvalue) == "table" then local equal = #fvalue == #cvalue if equal then for i=1, #fvalue do if cvalue[i] ~= fvalue[i] then equal = false end end end if equal then fvalue = cvalue end end if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI local val_err fvalue, val_err = self:validate(fvalue, section) fvalue = self:transform(fvalue) if not fvalue and not novld then self:add_error(section, "invalid", val_err) end if self.alias then self.section.aliased = self.section.aliased or {} self.section.aliased[section] = self.section.aliased[section] or {} self.section.aliased[section][self.alias] = true end if fvalue and (self.forcewrite or not (fvalue == cvalue)) then if self:write(section, fvalue) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end end else -- Unset the UCI or error if self.rmempty or self.optional then if not self.alias or not self.section.aliased or not self.section.aliased[section] or not self.section.aliased[section][self.alias] then if self:remove(section) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end end elseif cvalue ~= fvalue and not novld then -- trigger validator with nil value to get custom user error msg. local _, val_err = self:validate(nil, section) self:add_error(section, "missing", val_err) end end end -- Render if this value exists or if it is mandatory function AbstractValue.render(self, s, scope) if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then scope = scope or {} scope.section = s scope.cbid = self:cbid(s) Node.render(self, scope) end end -- Return the UCI value of this object function AbstractValue.cfgvalue(self, section) local value if self.tag_error[section] then value = self:formvalue(section) else value = self.map:get(section, self.alias or self.option) end if not value then return nil elseif not self.cast or self.cast == type(value) then return value elseif self.cast == "string" then if type(value) == "table" then return value[1] end elseif self.cast == "table" then return { value } end end -- Validate the form value function AbstractValue.validate(self, value) if self.datatype and value then if type(value) == "table" then local v for _, v in ipairs(value) do if v and #v > 0 and not verify_datatype(self.datatype, v) then return nil end end else if not verify_datatype(self.datatype, value) then return nil end end end return value end AbstractValue.transform = AbstractValue.validate -- Write to UCI function AbstractValue.write(self, section, value) return self.map:set(section, self.alias or self.option, value) end -- Remove from UCI function AbstractValue.remove(self, section) return self.map:del(section, self.alias or self.option) end --[[ Value - A one-line value maxlength: The maximum length ]]-- Value = class(AbstractValue) function Value.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/value" self.keylist = {} self.vallist = {} self.readonly = nil end function Value.reset_values(self) self.keylist = {} self.vallist = {} end function Value.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function Value.parse(self, section, novld) if self.readonly then return end AbstractValue.parse(self, section, novld) end -- DummyValue - This does nothing except being there DummyValue = class(AbstractValue) function DummyValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dvalue" self.value = nil end function DummyValue.cfgvalue(self, section) local value if self.value then if type(self.value) == "function" then value = self:value(section) else value = self.value end else value = AbstractValue.cfgvalue(self, section) end return value end function DummyValue.parse(self) end --[[ Flag - A flag being enabled or disabled ]]-- Flag = class(AbstractValue) function Flag.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/fvalue" self.enabled = "1" self.disabled = "0" self.default = self.disabled end -- A flag can only have two states: set or unset function Flag.parse(self, section, novld) local fexists = self.map:formvalue( FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option) if fexists then local fvalue = self:formvalue(section) and self.enabled or self.disabled local cvalue = self:cfgvalue(section) local val_err fvalue, val_err = self:validate(fvalue, section) if not fvalue then if not novld then self:add_error(section, "invalid", val_err) end return end if fvalue == self.default and (self.optional or self.rmempty) then self:remove(section) else self:write(section, fvalue) end if (fvalue ~= cvalue) then self.section.changed = true end else self:remove(section) self.section.changed = true end end function Flag.cfgvalue(self, section) return AbstractValue.cfgvalue(self, section) or self.default end function Flag.validate(self, value) return value end --[[ ListValue - A one-line value predefined in a list widget: The widget that will be used (select, radio) ]]-- ListValue = class(AbstractValue) function ListValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/lvalue" self.size = 1 self.widget = "select" self:reset_values() end function ListValue.reset_values(self) self.keylist = {} self.vallist = {} self.deplist = {} end function ListValue.value(self, key, val, ...) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) table.insert(self.deplist, {...}) end function ListValue.validate(self, val) if luci.util.contains(self.keylist, val) then return val else return nil end end --[[ MultiValue - Multiple delimited values widget: The widget that will be used (select, checkbox) delimiter: The delimiter that will separate the values (default: " ") ]]-- MultiValue = class(AbstractValue) function MultiValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/mvalue" self.widget = "checkbox" self.delimiter = " " self:reset_values() end function MultiValue.render(self, ...) if self.widget == "select" and not self.size then self.size = #self.vallist end AbstractValue.render(self, ...) end function MultiValue.reset_values(self) self.keylist = {} self.vallist = {} self.deplist = {} end function MultiValue.value(self, key, val) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function MultiValue.valuelist(self, section) local val = self:cfgvalue(section) if not(type(val) == "string") then return {} end return luci.util.split(val, self.delimiter) end function MultiValue.validate(self, val) val = (type(val) == "table") and val or {val} local result for i, value in ipairs(val) do if luci.util.contains(self.keylist, value) then result = result and (result .. self.delimiter .. value) or value end end return result end StaticList = class(MultiValue) function StaticList.__init__(self, ...) MultiValue.__init__(self, ...) self.cast = "table" self.valuelist = self.cfgvalue if not self.override_scheme and self.map:get_scheme(self.section.sectiontype, self.option) then local vs = self.map:get_scheme(self.section.sectiontype, self.option) if self.value and vs.values and not self.override_values then for k, v in pairs(vs.values) do self:value(k, v) end end end end function StaticList.validate(self, value) value = (type(value) == "table") and value or {value} local valid = {} for i, v in ipairs(value) do if luci.util.contains(self.keylist, v) then table.insert(valid, v) end end return valid end DynamicList = class(AbstractValue) function DynamicList.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dynlist" self.cast = "table" self:reset_values() end function DynamicList.reset_values(self) self.keylist = {} self.vallist = {} end function DynamicList.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function DynamicList.write(self, section, value) local t = { } if type(value) == "table" then local x for _, x in ipairs(value) do if x and #x > 0 then t[#t+1] = x end end else t = { value } end if self.cast == "string" then value = table.concat(t, " ") else value = t end return AbstractValue.write(self, section, value) end function DynamicList.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if type(value) == "string" then local x local t = { } for x in value:gmatch("%S+") do if #x > 0 then t[#t+1] = x end end value = t end return value end function DynamicList.formvalue(self, section) local value = AbstractValue.formvalue(self, section) if type(value) == "string" then if self.cast == "string" then local x local t = { } for x in value:gmatch("%S+") do t[#t+1] = x end value = t else value = { value } end end return value end DropDown = class(MultiValue) function DropDown.__init__(self, ...) ListValue.__init__(self, ...) self.template = "cbi/dropdown" self.delimiter = " " end --[[ TextValue - A multi-line value rows: Rows ]]-- TextValue = class(AbstractValue) function TextValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/tvalue" end --[[ Button ]]-- Button = class(AbstractValue) function Button.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/button" self.inputstyle = nil self.rmempty = true self.unsafeupload = false end FileUpload = class(AbstractValue) function FileUpload.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/upload" if not self.map.upload_fields then self.map.upload_fields = { self } else self.map.upload_fields[#self.map.upload_fields+1] = self end end function FileUpload.formcreated(self, section) if self.unsafeupload then return AbstractValue.formcreated(self, section) or self.map:formvalue("cbi.rlf."..section.."."..self.option) or self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") or self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox") else return AbstractValue.formcreated(self, section) or self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox") end end function FileUpload.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) if val and fs.access(val) then return val end return nil end -- If we have a new value, use it -- otherwise use old value -- deletion should be managed by a separate button object -- unless self.unsafeupload is set in which case if the user -- choose to remove the old file we do so. -- Also, allow to specify (via textbox) a file already on router function FileUpload.formvalue(self, section) local val = AbstractValue.formvalue(self, section) if val then if self.unsafeupload then if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") then return val end fs.unlink(val) self.value = nil return nil elseif val ~= "" then return val end end val = luci.http.formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox") if val == "" then val = nil end if not self.unsafeupload then if not val then val = self.map:formvalue("cbi.rlf."..section.."."..self.option) end end return val end function FileUpload.remove(self, section) if self.unsafeupload then local val = AbstractValue.formvalue(self, section) if val and fs.access(val) then fs.unlink(val) end return AbstractValue.remove(self, section) else return nil end end FileBrowser = class(AbstractValue) function FileBrowser.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/browser" end
apache-2.0
mrshayan/iran_power_ok
bot/utils.lua
473
24167
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
cloner-hooshesiyah/shidbot
bot/utils.lua
473
24167
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
alivilteram/seedteam
bot/utils.lua
473
24167
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
linkgo/nodemcu-quick
library.lua
1
1284
-- init.lua uart.setup(0,115200,8,0,1) -- ls() l = file.list() for k,v in pairs(l) do print("name: "..k..",size: "..v) end -- cat() local f=... print(args: ..f) file.open(f, r) print(file.read(EOF)) file.close() -- list nearby APs function listap(t) for k,v in pairs(t) do print(k.. : ..v) end end wifi.sta.getap(listap) -- mqtt connect, replace IP_ADDR to real world value open("mqtt_conn.lua", "w+") m = mqtt.Client("nodemcu", 120, nil, nil) m:on("connect", function(con) print ("connected") end) m:on("offline", function(con) print ("offline") end) m:connect("IP_ADDR", 1883, 0, function(conn) print("connected") end) -- mqtt publish m:publish("/nodemcu/report", "nodemcu: "..adc.read(0), 0, 0, function(conn) print("sent") end) -- mqtt publish, keep doing so for 10 sec, with a 1 sec interval print("start publishing...") tmr.alarm(0, 1000, 1, function() dofile("mqtt_pub.lua") end) tmr.alarm(1, 10000, 0, function() print("stopping tmr 0") tmr.stop(0) end) -- mqtt subscribe, message will be handled in m:on() m:on("message", function(conn, topic, data) print(topic .. ":" ) if data ~= nil then print(data) end end) m:subscribe("+", 0, function(conn) print("subscribe success") end) -- after mqtt things done, close connection m:close()
bsd-2-clause