content
stringlengths 5
1.05M
|
|---|
RegisterNetEvent("rcore_arcade:ticketResult")
AddEventHandler("rcore_arcade:ticketResult", function(ticket)
showNotification(_U("bought_ticket", ticket, Config.ticketPrice[ticket].time))
-- Will set time player can be in arcade from Config
seconds = 1
minutes = Config.ticketPrice[ticket].time
-- Tell the script that player has Ticket and can enter.
gotTicket = true
end)
RegisterNetEvent("rcore_arcade:nomoney")
AddEventHandler("rcore_arcade:nomoney", function()
showNotification(_U("not_enough_money"))
end)
RegisterNUICallback('exit', function()
SendNUIMessage({
type = "off",
game = "",
})
SetNuiFocus(false, false)
end)
|
--[[
--==Contributers==--
- Egor Dorichev (egordorichev)
]]
local editors = {
sfx = dofile("/rom/Editors/Sfx.lua")
}
local current = editors.sfx
while true do
Graphics.clear()
current._update()
current._draw()
Graphics.flip()
end
|
--[[
NOTE: THIS FILE IS NO LONGER IN USE
THE FUNCTIONS HAVE BEEN INCORPORATED INTO THE PS_VM.LUA FILE
]]
local Scanner = require("lj2ps.ps_scanner")
local octetstream = require("lj2ps.octetstream")
local ps_common = require("lj2ps.ps_common")
local TokenType = ps_common.TokenType
local Interpreter = {}
setmetatable(Interpreter, {
__call = function(self, ...)
return self:new(...)
end;
})
local Interpreter_mt = {
__index = Interpreter
}
function Interpreter.new(self, vm)
local obj = {
Vm = vm;
}
setmetatable(obj, Interpreter_mt)
return obj
end
function Interpreter.createFromString(self, vm, input)
local bs = octetstream(input)
return Interpreter:new(vm, bs)
end
--[[
Instance Methods
]]
-- bs - type can be either 'string' or 'octetstream'
function Interpreter.runStream(self, bs)
local scnr = Scanner(self.Vm, bs)
-- Iterate through tokens
for _, token in scnr:tokens(bs) do
--print("INTERP: ", token.kind, token.value)
if token.kind == TokenType.BOOLEAN or
token.kind == TokenType.NUMBER or
token.kind == TokenType.STRING or
token.kind == TokenType.HEXSTRING then
self.Vm.OperandStack:push(token.value)
elseif token.kind == TokenType.LITERAL_NAME then
-- defining a name with '/name'
self.Vm.OperandStack:push(token.value)
elseif token.kind == TokenType.EXECUTABLE_NAME then
--print(" interp.runstream(self.Vm:execName): ", token.value)
self.Vm:execName(token.value)
elseif token.kind == TokenType.LITERAL_ARRAY then
--print("LITERAL_ARRAY, isExecutable: ", token.value, token.value.isExecutable)
self.Vm.OperandStack:push(token.value)
elseif token.kind == TokenType.PROCEDURE then
-- pure procedure definition, push it on the stack
-- probably saving for a bind or control flow or looping
self.Vm.OperandStack:push(token.value)
else
-- it's some other literal value type
print("INTERP, UNKNOWN Token Kind: ", token.kind)
--print("INTERP, push: ", TokenType[token.kind], token.value)
--self.Vm.OperandStack:push(token.value)
end
end
end
--[[
function Interpreter.run(self, bs)
if type(bs) == "string" then
bs = octetstream(bs)
end
return self:runStream(bs)
end
--]]
return Interpreter
|
--[[
Title: Local Service History
Author(s): big
CreateDate: 2021.12.16
Place: Foshan
use the lib:
------------------------------------------------------------
local LocalServiceHistory = NPL.load('(gl)Mod/WorldShare/service/LocalService/LocalServiceHistory.lua')
------------------------------------------------------------
]]
-- service
local KeepworkServiceProject = NPL.load('(gl)Mod/WorldShare/service/KeepworkService/Project.lua')
-- database
local Bookmark = NPL.load('(gl)Mod/WorldShare/database/Bookmark.lua')
local LocalServiceHistory = NPL.export()
function LocalServiceHistory:LoadWorld(world)
if world then
self:WriteWorldRecord(world)
end
end
function LocalServiceHistory:WriteWorldRecord(world)
if not world or type(world) ~= 'table' then
return
end
if world and
type(world) == 'table' and
world.kpProjectId then
self:Visit(world.kpProjectId)
end
Bookmark:SetItem(world)
end
function LocalServiceHistory:GetWorldRecord()
local bookmarkItems = Bookmark:GetBookmark()
if not bookmarkItems or type(bookmarkItems) ~= 'table' then
return {}
end
local items = {}
for key, item in ipairs(bookmarkItems) do
if item and
type(item) == 'table' and
item.projectId then
items[#items + 1] = item
end
end
return items
end
function LocalServiceHistory:Visit(projectId)
KeepworkServiceProject:Visit(projectId)
end
|
local DataIter = torch.class('DepDataIter')
function DataIter.conllx_iter(infile)
local fin = io.open(infile)
return function()
local items = {}
while true do
local line = fin:read()
if line == nil then break end
line = line:trim()
if line:len() == 0 then
break
end
local fields = line:splitc('\t')
assert(#fields == 10, 'MUST have 10 fields')
local item = {p1 = tonumber(fields[1]), wd = fields[2],
pos = fields[5], p2 = fields[7], rel = fields[8]}
table.insert(items, item)
end
if #items > 0 then
return items
else
fin:close()
end
end
end
function DataIter.getDataSize(infiles)
local sizes = {}
for _, infile in ipairs(infiles) do
local size = 0
local diter = DataIter.conllx_iter(infile)
for ds in diter do
size = size + 1
end
sizes[#sizes + 1] = size
end
return sizes
end
function DataIter.showVocab(vocab)
for k, v in pairs(vocab) do
xprint(k)
if type(v) == 'table' then
print ' -- table'
else
print( ' -- ' .. tostring(v) )
end
end
end
function DataIter.createVocab(infile, ignoreCase, freqCut, maxNVocab)
local wordFreq = {}
local wordVec = {}
local diter = DataIter.conllx_iter(infile)
local function addwd(wd)
local wd = ignoreCase and wd:lower() or wd
local freq = wordFreq[wd]
if freq == nil then
wordFreq[wd] = 1
wordVec[#wordVec + 1] = wd
else
wordFreq[wd] = freq + 1
end
end
for sent in diter do
addwd('###root###')
for _, ditem in ipairs(sent) do
addwd(ditem.wd)
end
end
local idx2word
if freqCut and freqCut >= 0 then
idx2word = {}
idx2word[#idx2word + 1] = 'UNK'
for _, wd in ipairs(wordVec) do
if wordFreq[wd] > freqCut then idx2word[#idx2word + 1] = wd end
end
printf('original word count = %d, after freq cut = %d, word count = %d\n', #wordVec, freqCut, #idx2word)
end
if maxNVocab and maxNVocab > 0 then
if #idx2word > 0 then
print( 'WARING: rewrote idx2word with maxNVocab = ' .. maxNVocab )
end
idx2word = {}
idx2word[#idx2word + 1] = 'UNK'
local wfs = {}
for _, k in ipairs(wordVec) do table.insert(wfs, {k, wordFreq[k]}) end
table.sort(wfs, function(x, y) return x[2] > y[2] end)
local lfreq = -1
for cnt, kv in ipairs(wfs) do
idx2word[#idx2word + 1] = kv[1]
lfreq = kv[2]
if cnt >= maxNVocab-1 then break end
end
printf('original word count = %d, after maxNVocab = %d, word count = %d, lowest freq = %d\n', #wordVec, maxNVocab, #idx2word, lfreq)
end
local word2idx = {}
for i, w in ipairs(idx2word) do word2idx[w] = i end
local vocab = {word2idx = word2idx, idx2word = idx2word,
freqCut = freqCut, ignoreCase = ignoreCase, maxNVocab = maxNVocab,
UNK_STR = 'UNK', UNK = word2idx['UNK'],
ROOT_STR = '###root###', ROOT = word2idx['###root###']}
vocab['nvocab'] = table.len(word2idx)
DataIter.showVocab(vocab)
return vocab
end
function DataIter.toBatch(sents, vocab, batchSize)
local dtype = 'torch.LongTensor'
local maxn = -1
for _, sent in ipairs(sents) do if sent:size(1) > maxn then maxn = sent:size(1) end end
assert(maxn ~= -1)
local x = (torch.ones(maxn + 1, batchSize) * vocab.UNK):type(dtype)
local x_mask = torch.zeros(maxn + 1, batchSize)
local y = torch.zeros(maxn, batchSize):type(dtype)
x[{ 1, {} }] = vocab.ROOT
x_mask[{ 1, {} }] = 1
for i, sent in ipairs(sents) do
local slen = sent:size(1)
x[{ {2, slen + 1}, i }] = sent[{ {}, 1 }]
x_mask[{ {2, slen + 1}, i }] = 1
y[{ {1, slen}, i }] = sent[{ {}, 2 }]
end
return x, x_mask, y
end
function DataIter.sent2dep(vocab, sent)
local d = {}
local word2idx = vocab.word2idx
for _, ditem in ipairs(sent) do
local wd = vocab.ignoreCase and ditem.wd:lower() or ditem.wd
local wid = word2idx[wd] or vocab.UNK
d[#d + 1] = {wid, ditem.p2 + 1}
end
return torch.Tensor(d), #d
end
function DataIter.createBatch(vocab, infile, batchSize, maxlen)
maxlen = maxlen or 100
local diter = DataIter.conllx_iter(infile)
local isEnd = false
return function()
if not isEnd then
local sents = {}
for i = 1, batchSize do
local sent = diter()
if sent == nil then isEnd = true break end
local s, len = DataIter.sent2dep(vocab, sent)
if len <= maxlen then
sents[#sents + 1] = s
else
print ( 'delete sentence with length ' .. tostring(len) )
end
end
if #sents > 0 then
return DataIter.toBatch(sents, vocab, batchSize)
end
end
end
end
function DataIter.createBatchSort(vocab, infile, batchSize, maxlen)
maxlen = maxlen or 100
local diter = DataIter.conllx_iter(infile)
local all_sents = {}
for sent in diter do
local s, len = DataIter.sent2dep(vocab, sent)
all_sents[#all_sents + 1] = s
end
-- print(all_sents[1])
table.sort(all_sents, function(a, b) return a:size(1) < b:size(1) end)
local cnt = 0
local ndata = #all_sents
return function()
local sents = {}
for i = 1, batchSize do
cnt = cnt + 1
if cnt <= ndata then
sents[#sents + 1] = all_sents[cnt]
end
end
if #sents > 0 then
return DataIter.toBatch(sents, vocab, batchSize)
end
end
end
function DataIter.loadAllSents(vocab, infile, maxlen)
local diter = DataIter.conllx_iter(infile)
local all_sents = {}
local del_cnt = 0
for sent in diter do
local s, len = DataIter.sent2dep(vocab, sent)
if len <= maxlen then
all_sents[#all_sents + 1] = s
else
del_cnt = del_cnt + 1
end
end
if del_cnt > 0 then
printf( 'WARNING!!! delete %d sentences that longer than %d\n', del_cnt, maxlen)
end
return all_sents
end
function DataIter.createBatchShuffleSort(all_sents_, vocab, batchSize, sort_flag, shuffle)
assert(sort_flag ~= nil and (shuffle == true or shuffle == false))
local function shuffle_dataset(all_sents)
local tmp_sents = {}
local idxs = torch.randperm(#all_sents)
for i = 1, idxs:size(1) do
tmp_sents[#tmp_sents + 1] = all_sents[ idxs[i] ]
end
return tmp_sents
end
local all_sents
if shuffle then
all_sents = shuffle_dataset(all_sents_)
end
local len_idxs = {}
for i, sent in ipairs(all_sents) do
len_idxs[#len_idxs + 1] = {sent:size(1), i}
end
local kbatches = sort_flag * batchSize
local new_idxs = {}
local N = #len_idxs
for istart = 1, N, kbatches do
iend = math.min(istart + kbatches - 1, N)
local tmpa = {}
for i = istart, iend do
tmpa[#tmpa + 1] = len_idxs[i]
end
table.sort(tmpa, function( a, b ) return a[1] < b[1] end)
for _, tmp in ipairs(tmpa) do
new_idxs[#new_idxs + 1] = tmp[2]
end
end
local final_all_sents = {}
for _, idx in ipairs(new_idxs) do
final_all_sents[#final_all_sents + 1] = all_sents[idx]
end
local cnt, ndata = 0, #final_all_sents
return function()
local sents = {}
for i = 1, batchSize do
cnt = cnt + 1
if cnt > ndata then break end
sents[#sents + 1] = final_all_sents[cnt]
end
if #sents > 0 then
return DataIter.toBatch(sents, vocab, batchSize)
end
end
end
local function main()
--[[
require '../utils/shortcut'
local infile = '/Users/xing/Desktop/depparse/train.autopos'
local diter = DepDataIter.conllx_iter(infile)
local cnt = 0
for item in diter do
-- print(item)
cnt = cnt + 1
-- if cnt == 1 then break end
end
printf('totally %d sentences\n', cnt)
--]]
--[[
require '../utils/shortcut'
local infile = '/Users/xing/Desktop/depparse/train.autopos'
local vocab = DepDataIter.createVocab(infile, true)
--]]
require '../utils/shortcut'
local infile = '/Users/xing/Desktop/depparse/train.autopos'
local vocab = DepDataIter.createVocab(infile, true, 1)
print 'get vocab done!'
local validfile = '/Users/xing/Desktop/depparse/train.autopos'
local batchIter = DepDataIter.createBatch(vocab, validfile, 30, 100)
local cnt = 0
for x, x_maks, y in batchIter do
cnt = cnt + 1
end
print( 'totally ' .. cnt )
-- batchIter()
-- batchIter()
end
if not package.loaded['DepDataIter'] then
main()
end
|
local debug, table, tostring, string, type, pairs = debug, table, tostring, string, type, pairs
module (...)
---debuggery
function debug.dump(tbl)
local function tcopy(t) local nt={}; for i,v in pairs(t) do nt[i]=v end; return nt end
local function printy(thing, prefix, tablestack)
local t = type(thing)
if t == "nil" then return "nil"
elseif t == "string" then return string.format('%q', thing)
elseif t == "number" then return tostring(thing)
elseif t == "table" then
if tablestack and tablestack[thing] then return string.format("%s (recursion)", tostring(thing)) end
local kids, pre, substack = {}, " " .. prefix, (tablestack and tcopy(tablestack) or {})
substack[thing]=true
for k, v in pairs(thing) do
table.insert(kids, string.format('%s%s=%s,',pre,printy(k, ''),printy(v, pre, substack)))
end
return string.format("%s{\n%s\n%s}", tostring(thing), table.concat(kids, "\n"), prefix)
else
return tostring(thing)
end
end
local ret = printy(tbl, "", {})
return ret
end
table.show = debug.dump
|
--[[
This is an utility script for CTR.
Game: Crash Team Racing [NTSC-U] [SCUS-94426]
Emulator: psxjinv2.0.2
https://code.google.com/p/psxjin/
Script by Rodrigo A. do Amaral (Amaraticando)
https://www.youtube.com/user/RodrigoAmaral666
]]
TIMETRIAL_ADRESS = 0x001AC795
ram={
on_level = 0x0008D447,
environment = 0x0008D0FC,
track = 0x0008D930,
character = 0x00086E84,
lap = 0x001FFE38
}
ram_track={ -- abs Penta on Coco Park = 0x001AC795
[3] = 0, [7] = 6760, [1] = 78772, [6] = 127784, [16] = 145852, [9] = 162636,
[5] = 179844, [8] = 188720, [0] = 197572, [13] = 200000, [10] = 211044, [12] = 211740,
[4] = 211932, [15] = 212564, [11] = 213252, [2] = 214872, [14] = 215340, [17] = 224656
}
ram_racer_timetrial={ -- (char_number -> relative adress) abs speed Penta on Dingo Canyon=0x001DAE1FD
[13] = 0, [6] = 1732, [9] = 3332, [3] = 4380, [10] = 4488,
[12] = 6456, [2] = 6476, [4] = 6700, [8] = 7164, [14] = 7872,
[1] = 8668, [11] = 9444, [7] = 9816, [0] = 10260, [5] = 10628
}
track_name = {
[0] = "Crash Cove", [1] = "Roo's Tubes", [2] = "Tiger Temple",
[3] = "Coco Park", [4] = "Mystery Caves", [5] = "Blizzard Bluff",
[6] = "Sewer Speedway", [7] = "Dingo Canyon", [8] = "Papu's Pyramid",
[9] = "Dragon Mines", [10] = "Polar Pass", [11] = "Cortex Castle",
[12] = "Tiny Arena", [13] = "Hot Air Skyway", [14] = "N.Gin Labs",
[15] = "Oxide Station", [16] = "Slide Coliseum", [17] = "Turbo Track"
}
racer_name = {
[0] = "Crash Bandicoot", [1] = "Dr. Neo Cortex", [2] = "Tiny Tiger", [3] = "Coco Bandicoot",
[4] = "N. Gin", [5] = "Dingodile", [6] = "Polar", [7] = "Pura",
[8] = "Pinstripe", [9] = "Papu Papu", [10] = "Ripper Roo", [11] = "Komodo Joe",
[12] = "Dr. N. Tropy", [13] = "Penta Penguin", [14] = "Fake Crash", [15] = "Nitros Oxide"
}
function info()
local environment_number = memory.readbyte(ram["environment"])
local racer_number = memory.readbyte(ram["character"]) or 0
local track_number = memory.readbyte(ram["track"]) or 0
if racer_number>=0 and racer_number<=15 then
gui.text(042, 002, string.format("%s", racer_name[racer_number]))
end
if track_number>=0 and track_number<=17 then
gui.text(042, 010, string.format("%s - Environment %d", track_name[track_number], environment_number))
end
local adress = TIMETRIAL_ADRESS + ram_track[track_number] + ram_racer_timetrial[racer_number]
local absSpeed = memory.readbyte(adress)
local horiSpeed = memory.readbytesigned(adress+2)
local vertSpeed = memory.readbytesigned(adress+4)
local turboReserves = memory.readword(adress+85)
local slideTimer = memory.readword(adress+79)
local absPos = memory.readbyte(adress+252)
local absSubPos = memory.readbyte(adress+251)
local maxAbsPos = memory.readbyte(adress+256)
local maxAbsSubPos = memory.readbyte(adress+255)
local jumpTimer = memory.readword(adress+111)
local landing = memory.readbyte(adress+99)
gui.text(442, 130, string.format("Abs. Sp. = %d", absSpeed))
gui.text(479, 192, string.format("%3d", horiSpeed))
gui.text(442, 138, string.format("Vrt. Sp. = %d", vertSpeed))
gui.text(440, 208, string.format("Turbo = %5d", turboReserves))
gui.text(434, 192, string.format("%5d", slideTimer))
gui.text(240, 002, string.format("%3d.%02X/%3d.%02X", absPos, absSubPos, maxAbsPos, maxAbsSubPos))
gui.text(471, 172, string.format("%5d", jumpTimer))
gui.text(479, 180, string.format("%3d", landing))
end
function display()
local on_level = memory.readbytesigned(ram["on_level"])
if on_level==2 then
info()
else
gui.clearuncommitted()
end
return
end
while true do
display()
emu.frameadvance()
end
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local voices = { {text = 'Any time\'s a good time to buy some furniture!'} }
npcHandler:addModule(VoiceModule:new(voices))
-- Wooden Stake
local stakeKeyword = keywordHandler:addKeyword({'stake'}, StdModule.say, {npcHandler = npcHandler, text = 'Making a stake from a chair? Are you insane??! I won\'t waste my chairs on you for free! You will have to pay for it, but since I consider your plan a blasphemy, it will cost 5000 gold pieces. Okay?'},
function(player) return player:getStorageValue(Storage.FriendsandTraders.TheBlessedStake) ~= -1 end
)
stakeKeyword:addChildKeyword({'yes'}, StdModule.say, {npcHandler = npcHandler, text = 'Argh... my heart aches! Alright... a promise is a promise. Here - take this wooden stake, and now get lost.', ungreet = true},
function(player) return player:getMoney() >= 5000 end,
function(player) player:removeMoney(5000) player:addItem(5941, 1) end
)
stakeKeyword:addChildKeyword({'yes'}, StdModule.say, {npcHandler = npcHandler, text = 'You can\'t even pay for that.', reset = true})
stakeKeyword:addChildKeyword({''}, StdModule.say, {npcHandler = npcHandler, text = 'Phew. No chair-killing.', reset = true})
-- Others
npcHandler:setMessage(MESSAGE_GREET, 'Nice to meet you, Mister |PLAYERNAME|! Looking for furniture? You\'ve come to the right place!')
npcHandler:setMessage(MESSAGE_FAREWELL, 'You\'ll come back. They all do.')
npcHandler:setMessage(MESSAGE_WALKAWAY, 'Good bye.')
npcHandler:setMessage(MESSAGE_SENDTRADE, 'Have a look. Most furniture comes in handy kits. Just use them in your house to assemble the furniture. Do you want to see only a certain type of furniture?')
npcHandler:addModule(FocusModule:new())
|
local dictWeb = {
["èr"] = "二贰",
["shí"] = "十时实蚀",
["yǐ"] = "乙已以蚁倚",
["yī"] = "一衣医依伊揖壹",
["chǎng,ān,hàn"] = "厂",
["dīng,zhēng"] = "丁",
["qī"] = "七戚欺漆柒凄嘁",
["bǔ,bo"] = "卜",
["rén"] = "人仁",
["rù"] = "入褥",
["jiǔ"] = "九久酒玖灸韭",
["ér"] = "儿而",
["bā"] = "八巴疤叭芭捌笆",
["jǐ,jī"] = "几",
["le,liǎo"] = "了",
["lì"] = "力历厉立励利例栗粒吏沥荔俐莉砾雳痢",
["dāo"] = "刀",
["nǎi"] = "乃奶",
["sān"] = "三叁",
["yòu"] = "又右幼诱佑",
["yú"] = "于余鱼娱渔榆愚隅逾舆",
["shì"] = "士示世市式势事侍饰试视柿是适室逝释誓拭恃嗜",
["gān,gàn"] = "干",
["gōng"] = "工弓公功攻宫恭躬",
["kuī"] = "亏盔窥",
["tǔ"] = "土",
["cùn"] = "寸",
["dà,dài,tài"] = "大",
["cái"] = "才材财裁",
["xià"] = "下夏",
["zhàng"] = "丈仗帐胀障杖账",
["yǔ,yù,yú"] = "与",
["shàng,shǎng"] = "上",
["wàn,mò"] = "万",
["kǒu"] = "口",
["xiǎo"] = "小晓",
["jīn"] = "巾斤今金津筋襟",
["shān"] = "山删衫珊",
["qiān"] = "千迁牵谦签",
["qǐ"] = "乞企启起",
["chuān"] = "川穿",
["gè,gě"] = "个各",
["sháo"] = "勺芍",
["yì"] = "亿义艺忆议亦异役译易疫益谊意毅翼屹抑邑绎奕逸肄溢",
["jí"] = "及吉级极即急疾集籍棘辑嫉",
["fán"] = "凡烦矾樊",
["xī"] = "夕西吸希析牺息悉惜稀锡溪熄膝昔晰犀熙嬉蟋",
["wán"] = "丸完玩顽",
["me,mó,ma,yāo"] = "么",
["guǎng,ān"] = "广",
["wáng,wú"] = "亡",
["mén"] = "门们",
["shī"] = "尸失师诗狮施湿虱",
["zhī"] = "之支汁芝肢脂蜘",
["jǐ"] = "己挤脊",
["zǐ"] = "子紫姊籽滓",
["wèi"] = "卫未位味畏胃喂慰谓猬蔚魏",
["yě"] = "也冶野",
["nǚ,rǔ"] = "女",
["rèn"] = "刃认韧纫",
["fēi"] = "飞非啡",
["xí"] = "习席袭媳",
["mǎ"] = "马码玛",
["chā,chá,chǎ"] = "叉",
["fēng"] = "丰封疯峰锋蜂枫",
["xiāng"] = "乡香箱厢湘镶",
["jǐng"] = "井警阱",
["wáng,wàng"] = "王",
["kāi"] = "开揩",
["tiān"] = "天添",
["wú"] = "无吴芜梧蜈",
["fū,fú"] = "夫",
["zhuān"] = "专砖",
["yuán"] = "元园原圆援缘源袁猿辕",
["yún"] = "云匀耘",
["zhā,zā,zhá"] = "扎",
["mù"] = "木目牧墓幕暮慕沐募睦穆",
["wǔ"] = "五午伍武侮舞捂鹉",
["tīng"] = "厅听",
["bù,fǒu"] = "不",
["qū,ōu"] = "区",
["quǎn"] = "犬",
["tài"] = "太态泰汰",
["yǒu"] = "友",
["chē,jū"] = "车",
["pǐ"] = "匹",
["yóu"] = "尤由邮犹油游",
["jù"] = "巨拒具俱剧距惧锯聚炬",
["yá"] = "牙芽崖蚜涯衙",
["bǐ"] = "比彼笔鄙匕秕",
["jiē"] = "皆阶接街秸",
["hù"] = "互户护沪",
["qiè,qiē"] = "切",
["wǎ,wà"] = "瓦",
["zhǐ"] = "止旨址纸指趾",
["tún,zhūn"] = "屯",
["shǎo,shào"] = "少",
["rì"] = "日",
["zhōng,zhòng"] = "中",
["gāng"] = "冈刚纲缸肛",
["nèi,nà"] = "内",
["bèi"] = "贝备倍辈狈惫焙",
["shuǐ"] = "水",
["jiàn,xiàn"] = "见",
["niú"] = "牛",
["shǒu"] = "手守首",
["máo"] = "毛矛茅锚",
["qì"] = "气弃汽器迄泣",
["shēng"] = "升生声牲笙甥",
["cháng,zhǎng"] = "长",
["shén,shí"] = "什",
["piàn,piān"] = "片",
["pú,pū"] = "仆",
["huà,huā"] = "化",
["bì"] = "币必毕闭毙碧蔽弊避壁庇蓖痹璧",
["chóu,qiú"] = "仇",
["zhuǎ,zhǎo"] = "爪",
["jǐn,jìn"] = "仅",
["réng"] = "仍",
["fù,fǔ"] = "父",
["cóng,zòng"] = "从",
["fǎn"] = "反返",
["jiè"] = "介戒届界借诫",
["xiōng"] = "凶兄胸匈汹",
["fēn,fèn"] = "分",
["fá"] = "乏伐罚阀筏",
["cāng"] = "仓苍舱沧",
["yuè"] = "月阅悦跃越岳粤",
["shì,zhī"] = "氏",
["wù"] = "勿务物误悟雾坞晤",
["qiàn"] = "欠歉",
["fēng,fěng"] = "风",
["dān"] = "丹耽",
["wū"] = "乌污呜屋巫诬",
["fèng"] = "凤奉",
["gōu,gòu"] = "勾",
["wén"] = "文闻蚊",
["liù,lù"] = "六",
["huǒ"] = "火伙",
["fāng"] = "方芳",
["dǒu,dòu"] = "斗",
["wèi,wéi"] = "为",
["dìng"] = "订定锭",
["jì"] = "计记技忌际季剂迹既继寄绩妓荠寂鲫冀",
["xīn"] = "心辛欣新薪锌",
["chǐ,chě"] = "尺",
["yǐn"] = "引饮蚓瘾",
["chǒu"] = "丑",
["kǒng"] = "孔恐",
["duì"] = "队对",
["bàn"] = "办半扮伴瓣绊",
["yǔ,yú"] = "予",
["yǔn"] = "允陨",
["quàn"] = "劝",
["shū"] = "书叔殊梳舒疏输蔬抒枢淑",
["shuāng"] = "双霜",
["yù"] = "玉育狱浴预域欲遇御裕愈誉芋郁喻寓豫",
["huàn"] = "幻换唤患宦涣焕痪",
["kān"] = "刊堪勘",
["mò"] = "末沫漠墨默茉陌寞",
["jī"] = "击饥圾机肌鸡积基激讥叽唧畸箕",
["dǎ,dá"] = "打",
["qiǎo"] = "巧",
["zhèng,zhēng"] = "正症挣",
["pū"] = "扑",
["bā,pá"] = "扒",
["gān"] = "甘肝竿柑",
["qù"] = "去",
["rēng"] = "扔",
["gǔ"] = "古谷股鼓",
["běn"] = "本",
["jié,jiē"] = "节结",
["shù,shú,zhú"] = "术",
["bǐng"] = "丙柄饼秉禀",
["kě,kè"] = "可",
["zuǒ"] = "左",
["bù"] = "布步怖部埠",
["shí,dàn"] = "石",
["lóng"] = "龙聋隆咙胧窿",
["yà"] = "轧亚讶",
["miè"] = "灭蔑",
["píng"] = "平评凭瓶萍坪",
["dōng"] = "东冬",
["kǎ,qiǎ"] = "卡",
["běi,bèi"] = "北",
["yè"] = "业页夜液谒腋",
["jiù"] = "旧救就舅臼疚",
["shuài"] = "帅蟀",
["guī"] = "归规闺硅瑰",
["zhàn,zhān"] = "占",
["dàn"] = "旦但诞淡蛋氮",
["qiě,jū"] = "且",
["yè,xié"] = "叶",
["jiǎ"] = "甲钾",
["dīng"] = "叮盯",
["shēn"] = "申伸身深呻绅",
["hào,háo"] = "号",
["diàn"] = "电店垫殿玷淀惦奠",
["tián"] = "田甜恬",
["shǐ"] = "史使始驶矢屎",
["zhī,zhǐ"] = "只",
["yāng"] = "央殃秧鸯",
["diāo"] = "叼雕刁碉",
["jiào"] = "叫轿较窖酵",
["lìng"] = "另",
["dāo,tāo"] = "叨",
["sì"] = "四寺饲肆",
["tàn"] = "叹炭探碳",
["qiū"] = "丘秋蚯",
["hé"] = "禾河荷盒",
["fù"] = "付负妇附咐赴复傅富腹覆赋缚",
["dài"] = "代带贷怠袋逮戴",
["xiān"] = "仙先掀锨",
["yí"] = "仪宜姨移遗夷胰",
["bái"] = "白",
["zǎi,zǐ,zī"] = "仔",
["chì"] = "斥赤翅",
["tā"] = "他它塌",
["guā"] = "瓜刮",
["hū"] = "乎呼忽",
["cóng"] = "丛",
["lìng,líng,lǐng"] = "令",
["yòng"] = "用",
["shuǎi"] = "甩",
["yìn"] = "印",
["lè,yuè"] = "乐",
["jù,gōu"] = "句",
["cōng"] = "匆葱聪囱",
["fàn"] = "犯饭泛范贩",
["cè"] = "册厕测策",
["wài"] = "外",
["chù,chǔ"] = "处",
["niǎo"] = "鸟",
["bāo"] = "包胞苞褒",
["zhǔ"] = "主煮嘱拄",
["shǎn"] = "闪陕",
["lán"] = "兰拦栏蓝篮澜",
["tóu,tou"] = "头",
["huì"] = "汇绘贿惠慧讳诲晦秽",
["hàn"] = "汉旱捍悍焊撼翰憾",
["tǎo"] = "讨",
["xué"] = "穴学",
["xiě"] = "写",
["níng,nìng,zhù"] = "宁",
["ràng"] = "让",
["lǐ"] = "礼李里理鲤",
["xùn"] = "训讯迅汛驯逊殉",
["yǒng"] = "永咏泳勇蛹踊",
["mín"] = "民",
["chū"] = "出初",
["ní"] = "尼",
["sī"] = "司丝私斯撕嘶",
["liáo"] = "辽疗僚聊寥嘹缭",
["jiā"] = "加佳嘉枷",
["nú"] = "奴",
["zhào,shào"] = "召",
["biān"] = "边编鞭蝙",
["pí"] = "皮疲脾啤",
["yùn"] = "孕运韵酝蕴",
["fā,fà"] = "发",
["shèng"] = "圣胜剩",
["tái,tāi"] = "台苔",
["jiū"] = "纠究揪鸠",
["mǔ"] = "母亩牡拇姆",
["káng,gāng"] = "扛",
["xíng"] = "刑形型邢",
["dòng"] = "动冻栋洞",
["kǎo"] = "考烤拷",
["kòu"] = "扣寇",
["tuō"] = "托拖脱",
["lǎo"] = "老",
["gǒng"] = "巩汞拱",
["zhí"] = "执直侄值职植",
["kuò"] = "扩阔廓",
["yáng"] = "扬阳杨洋",
["dì,de"] = "地",
["sǎo,sào"] = "扫",
["chǎng,cháng"] = "场",
["ěr"] = "耳尔饵",
["máng"] = "芒忙盲茫",
["xiǔ"] = "朽",
["pǔ,pò,pō,piáo"] = "朴",
["quán"] = "权全泉拳痊",
["guò,guo,guō"] = "过",
["chén"] = "臣尘辰沉陈晨忱",
["zài"] = "再在",
["xié"] = "协胁斜携鞋谐",
["yā,yà"] = "压",
["yàn"] = "厌艳宴验雁焰砚唁谚堰",
["yǒu,yòu"] = "有",
["cún"] = "存",
["bǎi"] = "百摆",
["kuā,kuà"] = "夸",
["jiàng"] = "匠酱",
["duó"] = "夺踱",
["huī"] = "灰挥恢辉徽",
["dá"] = "达",
["sǐ"] = "死",
["liè"] = "列劣烈猎",
["guǐ"] = "轨鬼诡",
["xié,yá,yé,yú,xú"] = "邪",
["jiá,jiā,gā,xiá"] = "夹",
["chéng"] = "成呈诚承城程惩橙",
["mài"] = "迈麦卖",
["huà,huá"] = "划",
["zhì"] = "至志帜制质治致秩智置挚掷窒滞稚",
["cǐ"] = "此",
["zhēn"] = "贞针侦珍真斟榛",
["jiān"] = "尖奸歼坚肩艰兼煎",
["guāng"] = "光",
["dāng,dàng"] = "当",
["zǎo"] = "早枣澡蚤藻",
["tù,tǔ"] = "吐",
["xià,hè"] = "吓",
["chóng"] = "虫崇",
["tuán"] = "团",
["tóng,tòng"] = "同",
["qū,qǔ"] = "曲",
["diào"] = "吊钓掉",
["yīn"] = "因阴音姻茵",
["chī"] = "吃嗤痴",
["ma,má,mǎ"] = "吗",
["yǔ"] = "屿宇羽",
["fān"] = "帆翻",
["huí"] = "回茴蛔",
["qǐ,kǎi"] = "岂",
["zé"] = "则责",
["suì"] = "岁碎穗祟遂隧",
["ròu"] = "肉",
["zhū,shú"] = "朱",
["wǎng"] = "网往枉",
["nián"] = "年",
["diū"] = "丢",
["shé"] = "舌",
["zhú"] = "竹逐烛",
["qiáo"] = "乔侨桥瞧荞憔",
["wěi"] = "伟伪苇纬萎",
["chuán,zhuàn"] = "传",
["pāng"] = "乓",
["pīng"] = "乒",
["xiū,xǔ"] = "休",
["fú"] = "伏扶俘浮符幅福凫芙袱辐蝠",
["yōu"] = "优忧悠幽",
["yán"] = "延严言岩炎沿盐颜阎蜒檐",
["jiàn"] = "件建荐贱剑健舰践鉴键箭涧",
["rèn,rén"] = "任",
["huá,huà,huā"] = "华",
["jià,jiè,jie"] = "价",
["shāng"] = "伤商",
["fèn,bīn"] = "份",
["fǎng"] = "仿访纺",
["yǎng,áng"] = "仰",
["zì"] = "自字",
["xiě,xuè"] = "血",
["xiàng"] = "向项象像橡",
["sì,shì"] = "似",
["hòu"] = "后厚候",
["zhōu"] = "舟州周洲",
["háng,xíng"] = "行",
["huì,kuài"] = "会",
["shā"] = "杀纱杉砂",
["hé,gě"] = "合",
["zhào"] = "兆赵照罩",
["zhòng"] = "众仲",
["yé"] = "爷",
["sǎn"] = "伞",
["chuàng,chuāng"] = "创",
["duǒ"] = "朵躲",
["wēi"] = "危威微偎薇巍",
["xún"] = "旬寻巡询循",
["zá"] = "杂砸",
["míng"] = "名明鸣铭螟",
["duō"] = "多哆",
["zhēng"] = "争征睁筝蒸怔狰",
["sè"] = "色涩瑟",
["zhuàng"] = "壮状撞",
["chōng,chòng"] = "冲",
["bīng"] = "冰兵",
["zhuāng"] = "庄装妆桩",
["qìng"] = "庆",
["liú"] = "刘留流榴琉硫瘤",
["qí,jì,zī,zhāi"] = "齐",
["cì"] = "次赐",
["jiāo"] = "交郊浇娇骄胶椒焦蕉礁",
["chǎn"] = "产铲阐",
["wàng"] = "妄忘旺望",
["chōng"] = "充",
["wèn"] = "问",
["chuǎng"] = "闯",
["yáng,xiáng"] = "羊",
["bìng,bīng"] = "并",
["dēng"] = "灯登蹬",
["mǐ"] = "米",
["guān"] = "关官棺",
["hàn,hán"] = "汗",
["jué"] = "决绝掘诀爵",
["jiāng"] = "江姜僵缰",
["tāng,shāng"] = "汤",
["chí"] = "池驰迟持弛",
["xīng,xìng"] = "兴",
["zhái"] = "宅",
["ān"] = "安氨庵鞍",
["jiǎng"] = "讲奖桨蒋",
["jūn"] = "军均君钧",
["xǔ,hǔ"] = "许",
["fěng"] = "讽",
["lùn,lún"] = "论",
["nóng"] = "农浓脓",
["shè"] = "设社舍涉赦",
["nà,nǎ,nèi,nā"] = "那",
["jìn,jǐn"] = "尽",
["dǎo"] = "导岛蹈捣祷",
["sūn,xùn"] = "孙",
["zhèn"] = "阵振震镇",
["shōu"] = "收",
["fáng"] = "防妨房肪",
["rú"] = "如儒蠕",
["mā"] = "妈",
["xì,hū"] = "戏",
["hǎo,hào"] = "好",
["tā,jiě"] = "她",
["guān,guàn"] = "观冠",
["huān"] = "欢",
["hóng,gōng"] = "红",
["mǎi"] = "买",
["xiān,qiàn"] = "纤",
["jì,jǐ"] = "纪济",
["yuē,yāo"] = "约",
["shòu"] = "寿受授售兽瘦",
["nòng,lòng"] = "弄",
["jìn"] = "进近晋浸",
["wéi"] = "违围唯维桅",
["yuǎn,yuàn"] = "远",
["tūn"] = "吞",
["tán"] = "坛谈痰昙谭潭檀",
["fǔ"] = "抚斧府俯辅腐甫脯",
["huài,pēi,pī,péi"] = "坏",
["rǎo"] = "扰",
["pī"] = "批披坯霹",
["zhǎo"] = "找沼",
["chě"] = "扯",
["zǒu"] = "走",
["chāo"] = "抄钞超",
["bà"] = "坝爸霸",
["gòng"] = "贡",
["zhé,shé,zhē"] = "折",
["qiǎng,qiāng,chēng"] = "抢",
["zhuā"] = "抓",
["xiào"] = "孝笑效哮啸",
["pāo"] = "抛",
["tóu"] = "投",
["kàng"] = "抗炕",
["fén"] = "坟焚",
["kēng"] = "坑",
["dǒu"] = "抖陡蚪",
["ké,qiào"] = "壳",
["fāng,fáng"] = "坊",
["niǔ"] = "扭纽钮",
["kuài"] = "块快筷",
["bǎ,bà"] = "把",
["bào"] = "报抱爆豹",
["jié"] = "劫杰洁捷截竭",
["què"] = "却确鹊",
["huā"] = "花",
["fēn"] = "芬吩纷氛",
["qín"] = "芹琴禽勤秦擒",
["láo"] = "劳牢",
["lú"] = "芦炉卢庐颅",
["gān,gǎn"] = "杆",
["kè"] = "克刻客课",
["sū,sù"] = "苏",
["dù"] = "杜渡妒镀",
["gàng,gāng"] = "杠",
["cūn"] = "村",
["qiú"] = "求球囚",
["xìng"] = "杏幸性姓",
["gèng,gēng"] = "更",
["liǎng"] = "两",
["lì,lí"] = "丽",
["shù"] = "束述树竖恕庶墅漱",
["dòu"] = "豆逗痘",
["hái,huán"] = "还",
["fǒu,pǐ"] = "否",
["lái"] = "来莱",
["lián"] = "连怜帘莲联廉镰",
["xiàn,xuán"] = "县",
["zhù,chú"] = "助",
["dāi"] = "呆",
["kuàng"] = "旷况矿框眶",
["ya,yā"] = "呀",
["zú"] = "足族",
["dūn"] = "吨蹲墩",
["kùn"] = "困",
["nán"] = "男",
["chǎo,chāo"] = "吵",
["yuán,yún,yùn"] = "员",
["chuàn"] = "串",
["chuī"] = "吹炊",
["ba,bā"] = "吧",
["hǒu"] = "吼",
["gǎng"] = "岗",
["bié,biè"] = "别",
["dīng,dìng"] = "钉",
["gào"] = "告",
["wǒ"] = "我",
["luàn"] = "乱",
["tū"] = "秃突凸",
["xiù"] = "秀袖绣锈嗅",
["gū,gù"] = "估",
["měi"] = "每美",
["hé,hē,hè"] = "何",
["tǐ,tī,bèn"] = "体",
["bó,bǎi,bà"] = "伯",
["zuò"] = "作坐座做",
["líng"] = "伶灵铃陵零龄玲凌菱蛉翎",
["dī"] = "低堤滴",
["yòng,yōng"] = "佣",
["nǐ"] = "你拟",
["zhù"] = "住注驻柱祝铸贮蛀",
["zào"] = "皂灶造燥躁噪",
["fó,fú,bì,bó"] = "佛",
["chè"] = "彻撤澈",
["tuǒ"] = "妥椭",
["lín"] = "邻林临琳磷鳞",
["hán"] = "含寒函涵韩",
["chà"] = "岔衩",
["cháng"] = "肠尝常偿",
["dù,dǔ"] = "肚",
["guī,jūn,qiū"] = "龟",
["miǎn"] = "免勉娩冕缅",
["jiǎo,jué"] = "角",
["kuáng"] = "狂",
["tiáo,tiāo"] = "条",
["luǎn"] = "卵",
["yíng"] = "迎盈营蝇赢荧莹萤",
["xì,jì"] = "系",
["chuáng"] = "床",
["kù"] = "库裤酷",
["yìng,yīng"] = "应",
["lěng"] = "冷",
["zhè,zhèi"] = "这",
["xù"] = "序叙绪续絮蓄旭恤酗婿",
["xián"] = "闲贤弦咸衔嫌涎舷",
["jiān,jiàn"] = "间监",
["pàn"] = "判盼叛畔",
["mēn,mèn"] = "闷",
["wāng"] = "汪",
["dì,tì,tuí"] = "弟",
["shā,shà"] = "沙",
["shà,shā"] = "煞",
["càn"] = "灿",
["wò"] = "沃卧握",
["méi,mò"] = "没",
["gōu"] = "沟钩",
["shěn,chén"] = "沈",
["huái"] = "怀槐徊淮",
["sòng"] = "宋送诵颂讼",
["hóng"] = "宏虹洪鸿",
["qióng"] = "穷琼",
["zāi"] = "灾栽",
["liáng"] = "良梁粮粱",
["zhèng"] = "证郑政",
["bǔ"] = "补捕哺",
["sù"] = "诉肃素速塑粟溯",
["shí,zhì"] = "识",
["cí"] = "词辞慈磁祠瓷雌",
["zhěn"] = "诊枕疹",
["niào,suī"] = "尿",
["céng"] = "层",
["jú"] = "局菊橘",
["wěi,yǐ"] = "尾",
["zhāng"] = "张章彰樟",
["gǎi"] = "改",
["lù"] = "陆录鹿路赂",
["ē,ā"] = "阿",
["zǔ"] = "阻组祖诅",
["miào"] = "妙庙",
["yāo"] = "妖腰邀夭吆",
["nǔ"] = "努",
["jìn,jìng"] = "劲",
["rěn"] = "忍",
["qū"] = "驱屈岖蛆躯",
["chún"] = "纯唇醇",
["nà"] = "纳钠捺",
["bó"] = "驳脖博搏膊舶渤",
["zòng,zǒng"] = "纵",
["wén,wèn"] = "纹",
["lǘ"] = "驴",
["huán"] = "环",
["qīng"] = "青轻倾清蜻氢卿",
["xiàn"] = "现限线宪陷馅羡献腺",
["biǎo"] = "表",
["mǒ,mò,mā"] = "抹",
["lǒng"] = "拢垄",
["dān,dàn,dǎn"] = "担",
["bá"] = "拔跋",
["jiǎn"] = "拣茧俭捡检减剪简柬碱",
["tǎn"] = "坦毯袒",
["chōu"] = "抽",
["yā"] = "押鸦鸭",
["guǎi"] = "拐",
["pāi"] = "拍",
["zhě"] = "者",
["dǐng"] = "顶鼎",
["yōng"] = "拥庸",
["chāi,cā"] = "拆",
["dǐ"] = "抵",
["jū,gōu"] = "拘",
["lā"] = "垃",
["lā,lá"] = "拉",
["bàn,pàn"] = "拌",
["zhāo"] = "招昭",
["pō"] = "坡泼颇",
["bō"] = "拨波玻菠播",
["zé,zhái"] = "择",
["tái"] = "抬",
["qí,jī"] = "其奇",
["qǔ"] = "取娶",
["kǔ"] = "苦",
["mào"] = "茂贸帽貌",
["ruò,rě"] = "若",
["miáo"] = "苗描瞄",
["píng,pēng"] = "苹",
["yīng"] = "英樱鹰莺婴缨鹦",
["qié"] = "茄",
["jīng"] = "茎京经惊晶睛精荆兢鲸",
["zhī,qí"] = "枝",
["bēi"] = "杯悲碑卑",
["guì,jǔ"] = "柜",
["bǎn"] = "板版",
["sōng"] = "松",
["qiāng"] = "枪腔",
["gòu"] = "构购够垢",
["sàng,sāng"] = "丧",
["huà"] = "画话桦",
["huò"] = "或货获祸惑霍",
["cì,cī"] = "刺",
["yǔ,yù"] = "雨语",
["bēn,bèn"] = "奔",
["fèn"] = "奋粪愤忿",
["hōng"] = "轰烘",
["qī,qì"] = "妻",
["ōu"] = "欧殴鸥",
["qǐng"] = "顷请",
["zhuǎn,zhuàn,zhuǎi"] = "转",
["zhǎn"] = "斩盏展",
["ruǎn"] = "软",
["lún"] = "轮仑伦沦",
["dào"] = "到盗悼道稻",
["chǐ"] = "齿耻侈",
["kěn"] = "肯垦恳啃",
["hǔ"] = "虎",
["xiē,suò"] = "些",
["lǔ"] = "虏鲁卤",
["shèn"] = "肾渗慎",
["shàng"] = "尚",
["guǒ"] = "果裹",
["kūn"] = "昆坤",
["guó"] = "国",
["chāng"] = "昌猖",
["chàng"] = "畅唱",
["diǎn"] = "典点碘",
["gù"] = "固故顾雇",
["áng"] = "昂",
["zhōng"] = "忠终钟盅衷",
["ne,ní"] = "呢",
["àn"] = "岸按案暗",
["tiě,tiē,tiè,"] = "帖",
["luó"] = "罗萝锣箩骡螺逻",
["kǎi"] = "凯慨",
["lǐng,líng"] = "岭",
["bài"] = "败拜",
["tú"] = "图徒途涂屠",
["chuí"] = "垂锤捶",
["zhī,zhì"] = "知织",
["guāi"] = "乖",
["gǎn"] = "秆赶敢感橄",
["hé,hè,huó,huò,hú"] = "和",
["gòng,gōng"] = "供共",
["wěi,wēi"] = "委",
["cè,zè,zhāi"] = "侧",
["pèi"] = "佩配沛",
["pò,pǎi"] = "迫",
["de,dì,dí"] = "的",
["pá"] = "爬",
["suǒ"] = "所索锁琐",
["jìng"] = "径竞竟敬静境镜靖",
["mìng"] = "命",
["cǎi,cài"] = "采",
["niàn"] = "念",
["tān"] = "贪摊滩瘫",
["rǔ"] = "乳辱",
["pín"] = "贫",
["fū"] = "肤麸孵敷",
["fèi"] = "肺废沸费吠",
["zhǒng"] = "肿",
["péng"] = "朋棚蓬膨硼鹏澎篷",
["fú,fù"] = "服",
["féi"] = "肥",
["hūn"] = "昏婚荤",
["tù"] = "兔",
["hú"] = "狐胡壶湖蝴弧葫",
["gǒu"] = "狗苟",
["bǎo"] = "饱宝保",
["xiǎng"] = "享响想",
["biàn"] = "变遍辨辩辫",
["dǐ,de"] = "底",
["jìng,chēng"] = "净",
["fàng"] = "放",
["nào"] = "闹",
["zhá"] = "闸铡",
["juàn,juǎn"] = "卷",
["quàn,xuàn"] = "券",
["dān,shàn,chán"] = "单",
["chǎo"] = "炒",
["qiǎn,jiān"] = "浅",
["fǎ"] = "法",
["xiè,yì"] = "泄",
["lèi"] = "泪类",
["zhān"] = "沾粘毡瞻",
["pō,bó"] = "泊",
["pào,pāo"] = "泡",
["xiè"] = "泻卸屑械谢懈蟹",
["ní,nì"] = "泥",
["zé,shì"] = "泽",
["pà"] = "怕帕",
["guài"] = "怪",
["zōng"] = "宗棕踪",
["shěn"] = "审婶",
["zhòu"] = "宙昼皱骤咒",
["kōng,kòng,kǒng"] = "空",
["láng,làng"] = "郎",
["chèn"] = "衬趁",
["gāi"] = "该",
["xiáng,yáng"] = "详",
["lì,dài"] = "隶",
["jū"] = "居鞠驹",
["shuā,shuà"] = "刷",
["mèng"] = "孟梦",
["gū"] = "孤姑辜咕沽菇箍",
["jiàng,xiáng"] = "降",
["mèi"] = "妹昧媚",
["jiě"] = "姐",
["jià"] = "驾架嫁稼",
["cān,shēn,cēn,sān"] = "参",
["liàn"] = "练炼恋链",
["xì"] = "细隙",
["shào"] = "绍哨",
["tuó"] = "驼驮鸵",
["guàn"] = "贯惯灌罐",
["zòu"] = "奏揍",
["chūn"] = "春椿",
["bāng"] = "帮邦梆",
["dú,dài"] = "毒",
["guà"] = "挂卦褂",
["kuǎ"] = "垮",
["kuà,kū"] = "挎",
["náo"] = "挠",
["dǎng,dàng"] = "挡",
["shuān"] = "拴栓",
["tǐng"] = "挺艇",
["kuò,guā"] = "括",
["shí,shè"] = "拾",
["tiāo,tiǎo"] = "挑",
["wā"] = "挖蛙洼",
["pīn"] = "拼",
["shèn,shén"] = "甚",
["mǒu"] = "某",
["nuó"] = "挪",
["gé"] = "革阁格隔",
["xiàng,hàng"] = "巷",
["cǎo"] = "草",
["chá"] = "茶察茬",
["dàng"] = "荡档",
["huāng"] = "荒慌",
["róng"] = "荣绒容熔融茸蓉溶榕",
["nán,nā"] = "南",
["biāo"] = "标彪膘",
["yào"] = "药耀",
["kū"] = "枯哭窟",
["xiāng,xiàng"] = "相",
["chá,zhā"] = "查",
["liǔ"] = "柳",
["bǎi,bó,bò"] = "柏",
["yào,yāo"] = "要",
["wāi"] = "歪",
["yán,yàn"] = "研",
["lí"] = "厘狸离犁梨璃黎漓篱",
["qì,qiè"] = "砌",
["miàn"] = "面",
["kǎn"] = "砍坎",
["shuǎ"] = "耍",
["nài"] = "耐奈",
["cán"] = "残蚕惭",
["zhàn"] = "战站栈绽蘸",
["bèi,bēi"] = "背",
["lǎn"] = "览懒揽缆榄",
["shěng,xǐng"] = "省",
["xiāo,xuē"] = "削",
["zhǎ"] = "眨",
["hǒng,hōng,hòng"] = "哄",
["xiǎn"] = "显险",
["mào,mò"] = "冒",
["yǎ,yā"] = "哑",
["yìng"] = "映硬",
["zuó"] = "昨",
["xīng"] = "星腥猩",
["pā"] = "趴",
["guì"] = "贵桂跪刽",
["sī,sāi"] = "思",
["xiā"] = "虾瞎",
["mǎ,mā,mà"] = "蚂",
["suī"] = "虽",
["pǐn"] = "品",
["mà"] = "骂",
["huá,huā"] = "哗",
["yè,yàn,yān"] = "咽",
["zán,zǎ"] = "咱",
["hā,hǎ,hà"] = "哈",
["yǎo"] = "咬舀",
["nǎ,něi,na,né"] = "哪",
["hāi,ké"] = "咳",
["xiá"] = "峡狭霞匣侠暇辖",
["gǔ,gū"] = "骨",
["gāng,gàng"] = "钢",
["tiē"] = "贴",
["yào,yuè"] = "钥",
["kàn,kān"] = "看",
["jǔ"] = "矩举",
["zěn"] = "怎",
["xuǎn"] = "选癣",
["zhòng,zhǒng,chóng"] = "种",
["miǎo"] = "秒渺藐",
["kē"] = "科棵颗磕蝌",
["biàn,pián"] = "便",
["zhòng,chóng"] = "重",
["liǎ"] = "俩",
["duàn"] = "段断缎锻",
["cù"] = "促醋簇",
["shùn"] = "顺瞬",
["xiū"] = "修羞",
["sú"] = "俗",
["qīn"] = "侵钦",
["xìn,shēn"] = "信",
["huáng"] = "皇黄煌凰惶蝗蟥",
["zhuī,duī"] = "追",
["jùn"] = "俊峻骏竣",
["dài,dāi"] = "待",
["xū"] = "须虚需",
["hěn"] = "很狠",
["dùn"] = "盾顿钝",
["lǜ"] = "律虑滤氯",
["pén"] = "盆",
["shí,sì,yì"] = "食",
["dǎn"] = "胆",
["táo"] = "逃桃陶萄淘",
["pàng"] = "胖",
["mài,mò"] = "脉",
["dú"] = "独牍",
["jiǎo"] = "狡饺绞脚搅",
["yuàn"] = "怨院愿",
["ráo"] = "饶",
["wān"] = "弯湾豌",
["āi"] = "哀哎埃",
["jiāng,jiàng"] = "将浆",
["tíng"] = "亭庭停蜓廷",
["liàng"] = "亮谅辆晾",
["dù,duó"] = "度",
["chuāng"] = "疮窗",
["qīn,qìng"] = "亲",
["zī"] = "姿资滋咨",
["dì"] = "帝递第蒂缔",
["chà,chā,chāi,cī"] = "差",
["yǎng"] = "养氧痒",
["qián"] = "前钱钳潜黔",
["mí"] = "迷谜靡",
["nì"] = "逆昵匿腻",
["zhà,zhá"] = "炸",
["zǒng"] = "总",
["làn"] = "烂滥",
["pào,páo,bāo"] = "炮",
["tì"] = "剃惕替屉涕",
["sǎ,xǐ"] = "洒",
["zhuó"] = "浊啄灼茁卓酌",
["xǐ,xiǎn"] = "洗",
["qià"] = "洽恰",
["pài"] = "派湃",
["huó"] = "活",
["rǎn"] = "染",
["héng"] = "恒衡",
["hún"] = "浑魂",
["nǎo"] = "恼脑",
["jué,jiào"] = "觉",
["hèn"] = "恨",
["xuān"] = "宣轩喧",
["qiè"] = "窃怯",
["biǎn,piān"] = "扁",
["ǎo"] = "袄",
["shén"] = "神",
["shuō,shuì,yuè"] = "说",
["tuì"] = "退蜕",
["chú"] = "除厨锄雏橱",
["méi"] = "眉梅煤霉玫枚媒楣",
["hái"] = "孩",
["wá"] = "娃",
["lǎo,mǔ"] = "姥",
["nù"] = "怒",
["hè"] = "贺赫褐鹤",
["róu"] = "柔揉蹂",
["bǎng"] = "绑膀",
["lěi"] = "垒蕾儡",
["rào"] = "绕",
["gěi,jǐ"] = "给",
["luò"] = "骆洛",
["luò,lào"] = "络",
["tǒng"] = "统桶筒捅",
["gēng"] = "耕羹",
["hào"] = "耗浩",
["bān"] = "班般斑搬扳颁",
["zhū"] = "珠株诸猪蛛",
["lāo"] = "捞",
["fěi"] = "匪诽",
["zǎi,zài"] = "载",
["mái,mán"] = "埋",
["shāo,shào"] = "捎稍",
["zhuō"] = "捉桌拙",
["niē"] = "捏",
["kǔn"] = "捆",
["dū,dōu"] = "都",
["sǔn"] = "损笋",
["juān"] = "捐鹃",
["zhé"] = "哲辙",
["rè"] = "热",
["wǎn"] = "挽晚碗惋婉",
["ái,āi"] = "挨",
["mò,mù"] = "莫",
["è,wù,ě,wū"] = "恶",
["tóng"] = "桐铜童彤瞳",
["xiào,jiào"] = "校",
["hé,hú"] = "核",
["yàng"] = "样漾",
["gēn"] = "根跟",
["gē"] = "哥鸽割歌戈",
["chǔ"] = "础储楚",
["pò"] = "破魄",
["tào"] = "套",
["chái"] = "柴豺",
["dǎng"] = "党",
["mián"] = "眠绵棉",
["shài"] = "晒",
["jǐn"] = "紧锦谨",
["yūn,yùn"] = "晕",
["huàng,huǎng"] = "晃",
["shǎng"] = "晌赏",
["ēn"] = "恩",
["ài,āi"] = "唉",
["ā,á,ǎ,à,a"] = "啊",
["bà,ba,pí"] = "罢",
["zéi"] = "贼",
["tiě"] = "铁",
["zuàn,zuān"] = "钻",
["qiān,yán"] = "铅",
["quē"] = "缺",
["tè"] = "特",
["chéng,shèng"] = "乘",
["dí"] = "敌笛涤嘀嫡",
["zū"] = "租",
["chèng"] = "秤",
["mì,bì"] = "秘泌",
["chēng,chèn,chèng"] = "称",
["tòu"] = "透",
["zhài"] = "债寨",
["dào,dǎo"] = "倒",
["tǎng,cháng"] = "倘",
["chàng,chāng"] = "倡",
["juàn"] = "倦绢眷",
["chòu,xiù"] = "臭",
["shè,yè,yì"] = "射",
["xú"] = "徐",
["háng"] = "航杭",
["ná"] = "拿",
["wēng"] = "翁嗡",
["diē"] = "爹跌",
["ài"] = "爱碍艾隘",
["gē,gé"] = "胳搁",
["cuì"] = "脆翠悴粹",
["zàng"] = "脏葬",
["láng"] = "狼廊琅榔",
["féng"] = "逢",
["è"] = "饿扼遏愕噩鳄",
["shuāi,cuī"] = "衰",
["gāo"] = "高糕羔篙",
["zhǔn"] = "准",
["bìng"] = "病",
["téng"] = "疼腾誊藤",
["liáng,liàng"] = "凉量",
["táng"] = "唐堂塘膛糖棠搪",
["pōu"] = "剖",
["chù,xù"] = "畜",
["páng,bàng"] = "旁磅",
["lǚ"] = "旅屡吕侣铝缕履",
["fěn"] = "粉",
["liào"] = "料镣",
["shāo"] = "烧",
["yān"] = "烟淹",
["tāo"] = "涛掏滔",
["lào"] = "涝酪",
["zhè"] = "浙蔗",
["xiāo"] = "消宵销萧硝箫嚣",
["hǎi"] = "海",
["zhǎng,zhàng"] = "涨",
["làng"] = "浪",
["rùn"] = "润闰",
["tàng"] = "烫",
["yǒng,chōng"] = "涌",
["huǐ"] = "悔毁",
["qiāo,qiǎo"] = "悄",
["hài"] = "害亥骇",
["jiā,jia,jie"] = "家",
["kuān"] = "宽",
["bīn"] = "宾滨彬缤濒",
["zhǎi"] = "窄",
["lǎng"] = "朗",
["dú,dòu"] = "读",
["zǎi"] = "宰",
["shàn,shān"] = "扇",
["shān,shàn"] = "苫",
["wà"] = "袜",
["xiáng"] = "祥翔",
["shuí"] = "谁",
["páo"] = "袍咆",
["bèi,pī"] = "被",
["tiáo,diào,zhōu"] = "调",
["yuān"] = "冤鸳渊",
["bō,bāo"] = "剥",
["ruò"] = "弱",
["péi"] = "陪培赔",
["niáng"] = "娘",
["tōng"] = "通",
["néng,nài"] = "能",
["nán,nàn,nuó"] = "难",
["sāng"] = "桑",
["pěng"] = "捧",
["dǔ"] = "堵赌睹",
["yǎn"] = "掩眼演衍",
["duī"] = "堆",
["pái,pǎi"] = "排",
["tuī"] = "推",
["jiào,jiāo"] = "教",
["lüè"] = "掠略",
["jù,jū"] = "据",
["kòng"] = "控",
["zhù,zhuó,zhe"] = "著",
["jūn,jùn"] = "菌",
["lè,lēi"] = "勒",
["méng"] = "萌盟檬朦",
["cài"] = "菜",
["tī"] = "梯踢剔",
["shāo,sào"] = "梢",
["fù,pì"] = "副",
["piào,piāo"] = "票",
["shuǎng"] = "爽",
["shèng,chéng"] = "盛",
["què,qiāo,qiǎo"] = "雀",
["xuě"] = "雪",
["chí,shi"] = "匙",
["xuán"] = "悬玄漩",
["mī,mí"] = "眯",
["la,lā"] = "啦",
["shé,yí"] = "蛇",
["lèi,léi,lěi"] = "累",
["zhǎn,chán"] = "崭",
["quān,juàn,juān"] = "圈",
["yín"] = "银吟淫",
["bèn"] = "笨",
["lóng,lǒng"] = "笼",
["mǐn"] = "敏皿闽悯",
["nín"] = "您",
["ǒu"] = "偶藕",
["tōu"] = "偷",
["piān"] = "偏篇翩",
["dé,děi,de"] = "得",
["jiǎ,jià"] = "假",
["pán"] = "盘",
["chuán"] = "船",
["cǎi"] = "彩睬踩",
["lǐng"] = "领",
["liǎn"] = "脸敛",
["māo,máo"] = "猫",
["měng"] = "猛锰",
["cāi"] = "猜",
["háo"] = "毫豪壕嚎",
["má"] = "麻",
["guǎn"] = "馆管",
["còu"] = "凑",
["hén"] = "痕",
["kāng"] = "康糠慷",
["xuán,xuàn"] = "旋",
["zhe,zhuó,zháo,zhāo"] = "着",
["lǜ,shuài"] = "率",
["gài,gě,hé"] = "盖",
["cū"] = "粗",
["lín,lìn"] = "淋",
["qú,jù"] = "渠",
["jiàn,jiān"] = "渐溅",
["hùn,hún"] = "混",
["pó"] = "婆",
["qíng"] = "情晴擎",
["cǎn"] = "惨",
["sù,xiǔ,xiù"] = "宿",
["yáo"] = "窑谣摇遥肴姚",
["móu"] = "谋",
["mì"] = "密蜜觅",
["huǎng"] = "谎恍幌",
["tán,dàn"] = "弹",
["suí"] = "随",
["yǐn,yìn"] = "隐",
["jǐng,gěng"] = "颈",
["shéng"] = "绳",
["qí"] = "骑棋旗歧祈脐畦崎鳍",
["chóu"] = "绸酬筹稠愁畴",
["lǜ,lù"] = "绿",
["dā"] = "搭",
["kuǎn"] = "款",
["tǎ"] = "塔",
["qū,cù"] = "趋",
["tí,dī,dǐ"] = "提",
["jiē,qì"] = "揭",
["xǐ"] = "喜徙",
["sōu"] = "搜艘",
["chā"] = "插",
["lǒu,lōu"] = "搂",
["qī,jī"] = "期",
["rě"] = "惹",
["sàn,sǎn"] = "散",
["dǒng"] = "董懂",
["gě,gé"] = "葛",
["pú"] = "葡菩蒲",
["zhāo,cháo"] = "朝",
["luò,là,lào"] = "落",
["kuí"] = "葵魁",
["bàng"] = "棒傍谤",
["yǐ,yī"] = "椅",
["sēn"] = "森",
["gùn,hùn"] = "棍",
["bī"] = "逼",
["zhí,shi"] = "殖",
["xià,shà"] = "厦",
["liè,liě"] = "裂",
["xióng"] = "雄熊",
["zàn"] = "暂赞",
["yǎ"] = "雅",
["chǎng"] = "敞",
["zhǎng"] = "掌",
["shǔ"] = "暑鼠薯黍蜀署曙",
["zuì"] = "最罪醉",
["hǎn"] = "喊罕",
["jǐng,yǐng"] = "景",
["lǎ"] = "喇",
["pēn,pèn"] = "喷",
["pǎo,páo"] = "跑",
["chuǎn"] = "喘",
["hē,hè,yè"] = "喝",
["hóu"] = "喉猴",
["pù,pū"] = "铺",
["hēi"] = "黑",
["guō"] = "锅郭",
["ruì"] = "锐瑞",
["duǎn"] = "短",
["é"] = "鹅额讹俄",
["děng"] = "等",
["kuāng"] = "筐",
["shuì"] = "税睡",
["zhù,zhú"] = "筑",
["shāi"] = "筛",
["dá,dā"] = "答",
["ào"] = "傲澳懊",
["pái"] = "牌徘",
["bǎo,bǔ,pù"] = "堡",
["ào,yù"] = "奥",
["fān,pān"] = "番",
["là,xī"] = "腊",
["huá"] = "猾滑",
["rán"] = "然燃",
["chán"] = "馋缠蝉",
["mán"] = "蛮馒",
["tòng"] = "痛",
["shàn"] = "善擅膳赡",
["zūn"] = "尊遵",
["pǔ"] = "普谱圃浦",
["gǎng,jiǎng"] = "港",
["céng,zēng"] = "曾",
["wēn"] = "温瘟",
["kě"] = "渴",
["zhā"] = "渣",
["duò"] = "惰舵跺",
["gài"] = "溉概丐钙",
["kuì"] = "愧",
["yú,tōu"] = "愉",
["wō"] = "窝蜗",
["cuàn"] = "窜篡",
["qún"] = "裙群",
["qiáng,qiǎng,jiàng"] = "强",
["shǔ,zhǔ"] = "属",
["zhōu,yù"] = "粥",
["sǎo"] = "嫂",
["huǎn"] = "缓",
["piàn"] = "骗",
["mō"] = "摸",
["shè,niè"] = "摄",
["tián,zhèn"] = "填",
["gǎo"] = "搞稿镐",
["suàn"] = "蒜算",
["méng,mēng,měng"] = "蒙",
["jìn,jīn"] = "禁",
["lóu"] = "楼娄",
["lài"] = "赖癞",
["lù,liù"] = "碌",
["pèng"] = "碰",
["léi"] = "雷",
["báo"] = "雹",
["dū"] = "督",
["nuǎn"] = "暖",
["xiē"] = "歇楔蝎",
["kuà"] = "跨胯",
["tiào,táo"] = "跳",
["é,yǐ"] = "蛾",
["sǎng"] = "嗓",
["qiǎn"] = "遣谴",
["cuò"] = "错挫措锉",
["ǎi"] = "矮蔼",
["shǎ"] = "傻",
["cuī"] = "催摧崔",
["tuǐ"] = "腿",
["chù"] = "触矗",
["jiě,jiè,xiè"] = "解",
["shù,shǔ,shuò"] = "数",
["mǎn"] = "满",
["liū,liù"] = "溜",
["gǔn"] = "滚",
["sāi,sài,sè"] = "塞",
["pì,bì"] = "辟",
["dié"] = "叠蝶谍碟",
["fèng,féng"] = "缝",
["qiáng"] = "墙",
["piě,piē"] = "撇",
["zhāi"] = "摘斋",
["shuāi"] = "摔",
["mó,mú"] = "模",
["bǎng,bàng"] = "榜",
["zhà"] = "榨乍诈",
["niàng"] = "酿",
["zāo"] = "遭糟",
["suān"] = "酸",
["shang,cháng"] = "裳",
["sòu"] = "嗽",
["là"] = "蜡辣",
["qiāo"] = "锹敲跷",
["zhuàn"] = "赚撰",
["wěn"] = "稳吻紊",
["bí"] = "鼻荸",
["mó"] = "膜魔馍摹蘑",
["xiān,xiǎn"] = "鲜",
["yí,nǐ"] = "疑",
["gāo,gào"] = "膏",
["zhē"] = "遮",
["duān"] = "端",
["màn"] = "漫慢曼幔",
["piāo,piào,piǎo"] = "漂",
["lòu"] = "漏陋",
["sài"] = "赛",
["nèn"] = "嫩",
["dèng"] = "凳邓瞪",
["suō,sù"] = "缩",
["qù,cù"] = "趣",
["sā,sǎ"] = "撒",
["tàng,tāng"] = "趟",
["chēng"] = "撑",
["zēng"] = "增憎",
["cáo"] = "槽曹",
["héng,hèng"] = "横",
["piāo"] = "飘",
["mán,mén"] = "瞒",
["tí"] = "题蹄啼",
["yǐng"] = "影颖",
["bào,pù"] = "暴",
["tà"] = "踏蹋",
["kào"] = "靠铐",
["pì"] = "僻屁譬",
["tǎng"] = "躺",
["dé"] = "德",
["mó,mā"] = "摩",
["shú"] = "熟秫赎",
["hú,hū,hù"] = "糊",
["pī,pǐ"] = "劈",
["cháo"] = "潮巢",
["cāo"] = "操糙",
["yàn,yān"] = "燕",
["diān"] = "颠掂",
["báo,bó,bò"] = "薄",
["cān"] = "餐",
["xǐng"] = "醒",
["zhěng"] = "整拯",
["zuǐ"] = "嘴",
["zèng"] = "赠",
["mó,mò"] = "磨",
["níng"] = "凝狞柠",
["jiǎo,zhuó"] = "缴",
["cā"] = "擦",
["cáng,zàng"] = "藏",
["fán,pó"] = "繁",
["bì,bei"] = "臂",
["bèng"] = "蹦泵",
["pān"] = "攀潘",
["chàn,zhàn"] = "颤",
["jiāng,qiáng"] = "疆",
["rǎng"] = "壤攘",
["jiáo,jué,jiào"] = "嚼",
["rǎng,rāng"] = "嚷",
["chǔn"] = "蠢",
["lù,lòu"] = "露",
["náng,nāng"] = "囊",
["dǎi"] = "歹",
["rǒng"] = "冗",
["hāng,bèn"] = "夯",
["āo,wā"] = "凹",
["féng,píng"] = "冯",
["yū"] = "迂淤",
["xū,yù"] = "吁",
["lèi,lē"] = "肋",
["kōu"] = "抠",
["lūn,lún"] = "抡",
["jiè,gài"] = "芥",
["xīn,xìn"] = "芯",
["chā,chà"] = "杈",
["xiāo,xiào"] = "肖",
["zhī,zī"] = "吱",
["ǒu,ōu,òu"] = "呕",
["nà,nè"] = "呐",
["qiàng,qiāng"] = "呛",
["tún,dùn"] = "囤",
["kēng,háng"] = "吭",
["shǔn"] = "吮",
["diàn,tián"] = "佃",
["sì,cì"] = "伺",
["zhǒu"] = "肘帚",
["diàn,tián,shèng"] = "甸",
["páo,bào"] = "刨",
["lìn"] = "吝赁躏",
["duì,ruì,yuè"] = "兑",
["zhuì"] = "坠缀赘",
["kē,kě"] = "坷",
["tuò,tà,zhí"] = "拓",
["fú,bì"] = "拂",
["nǐng,níng,nìng"] = "拧",
["ào,ǎo,niù"] = "拗",
["kē,hē"] = "苛",
["yān,yǎn"] = "奄",
["hē,a,kē"] = "呵",
["gā,kā"] = "咖",
["biǎn"] = "贬匾",
["jiǎo,yáo"] = "侥",
["chà,shā"] = "刹",
["āng"] = "肮",
["wèng"] = "瓮",
["nüè,yào"] = "疟",
["páng"] = "庞螃",
["máng,méng"] = "氓",
["gē,yì"] = "疙",
["jǔ,jù"] = "沮",
["zú,cù"] = "卒",
["nìng"] = "泞",
["chǒng"] = "宠",
["wǎn,yuān"] = "宛",
["mí,mǐ"] = "弥",
["qì,qiè,xiè"] = "契",
["xié,jiā"] = "挟",
["duò,duǒ"] = "垛",
["jiá"] = "荚颊",
["zhà,shān,shi,cè"] = "栅",
["bó,bèi"] = "勃",
["zhóu,zhòu"] = "轴",
["nüè"] = "虐",
["liē,liě,lié,lie"] = "咧",
["dǔn"] = "盹",
["xūn"] = "勋",
["yo,yō"] = "哟",
["mī"] = "咪",
["qiào,xiào"] = "俏",
["hóu,hòu"] = "侯",
["pēi"] = "胚",
["tāi"] = "胎",
["luán"] = "峦",
["sà"] = "飒萨",
["shuò"] = "烁",
["xuàn"] = "炫",
["píng,bǐng"] = "屏",
["nà,nuó"] = "娜",
["pá,bà"] = "耙",
["gěng"] = "埂耿梗",
["niè"] = "聂镊孽",
["mǎng"] = "莽",
["qī,xī"] = "栖",
["jiǎ,gǔ"] = "贾",
["chěng"] = "逞",
["pēng"] = "砰烹",
["láo,lào"] = "唠",
["bàng,bèng"] = "蚌",
["gōng,zhōng"] = "蚣",
["li,lǐ,lī"] = "哩",
["suō"] = "唆梭嗦",
["hēng"] = "哼",
["zāng"] = "赃",
["qiào"] = "峭窍撬",
["mǎo"] = "铆",
["ǎn"] = "俺",
["sǒng"] = "耸",
["juè,jué"] = "倔",
["yīn,yān,yǐn"] = "殷",
["guàng"] = "逛",
["něi"] = "馁",
["wō,guō"] = "涡",
["lào,luò"] = "烙",
["nuò"] = "诺懦糯",
["zhūn"] = "谆",
["niǎn,niē"] = "捻",
["qiā"] = "掐",
["yè,yē"] = "掖",
["chān,xiān,càn,shǎn"] = "掺",
["dǎn,shàn"] = "掸",
["fēi,fěi"] = "菲",
["qián,gān"] = "乾",
["shē"] = "奢赊",
["shuò,shí"] = "硕",
["luō,luó,luo"] = "啰",
["shá"] = "啥",
["hǔ,xià"] = "唬",
["tuò"] = "唾",
["bēng"] = "崩",
["dāng,chēng"] = "铛",
["xiǎn,xǐ"] = "铣",
["jiǎo,jiáo"] = "矫",
["tiáo"] = "笤",
["kuǐ,guī"] = "傀",
["xìn"] = "衅",
["dōu"] = "兜",
["jì,zhài"] = "祭",
["xiáo"] = "淆",
["tǎng,chǎng"] = "淌",
["chún,zhūn"] = "淳",
["shuàn"] = "涮",
["dāng"] = "裆",
["wèi,yù"] = "尉",
["duò,huī"] = "堕",
["chuò,chāo"] = "绰",
["bēng,běng,bèng"] = "绷",
["zōng,zèng"] = "综",
["zhuó,zuó"] = "琢",
["chuǎi,chuài,chuāi,tuán,zhuī"] = "揣",
["péng,bāng"] = "彭",
["chān"] = "搀",
["cuō"] = "搓",
["sāo"] = "搔",
["yē"] = "椰",
["zhuī,chuí"] = "椎",
["léng,lēng,líng"] = "棱",
["hān"] = "酣憨",
["sū"] = "酥",
["záo"] = "凿",
["qiào,qiáo"] = "翘",
["zhā,chā"] = "喳",
["bǒ"] = "跛",
["há,gé"] = "蛤",
["qiàn,kàn"] = "嵌",
["bāi"] = "掰",
["yān,ā"] = "腌",
["wàn"] = "腕",
["dūn,duì"] = "敦",
["kuì,huì"] = "溃",
["jiǒng"] = "窘",
["sāo,sǎo"] = "骚",
["pìn"] = "聘",
["bǎ"] = "靶",
["xuē"] = "靴薛",
["hāo"] = "蒿",
["léng"] = "楞",
["kǎi,jiē"] = "楷",
["pín,bīn"] = "频",
["zhuī"] = "锥",
["tuí"] = "颓",
["sāi"] = "腮",
["liú,liù"] = "馏",
["nì,niào"] = "溺",
["qǐn"] = "寝",
["luǒ"] = "裸",
["miù"] = "谬",
["jiǎo,chāo"] = "剿",
["áo,āo"] = "熬",
["niān"] = "蔫",
["màn,wàn"] = "蔓",
["chá,chā"] = "碴",
["xūn,xùn"] = "熏",
["tiǎn"] = "舔",
["sēng"] = "僧",
["da,dá"] = "瘩",
["guǎ"] = "寡",
["tuì,tùn"] = "褪",
["niǎn"] = "撵碾",
["liáo,liāo"] = "撩",
["cuō,zuǒ"] = "撮",
["ruǐ"] = "蕊",
["cháo,zhāo"] = "嘲",
["biē"] = "憋鳖",
["hēi,mò"] = "嘿",
["zhuàng,chuáng"] = "幢",
["jī,qǐ"] = "稽",
["lǒu"] = "篓",
["lǐn"] = "凛檩",
["biě,biē"] = "瘪",
["liáo,lào,lǎo"] = "潦",
["chéng,dèng"] = "澄",
["lèi,léi"] = "擂",
["piáo"] = "瓢",
["shà"] = "霎",
["mò,má"] = "蟆",
["qué"] = "瘸",
["liáo,liǎo"] = "燎",
["liào,liǎo"] = "瞭",
["sào,sāo"] = "臊",
["mí,méi"] = "糜",
["ái"] = "癌",
["tún"] = "臀",
["huò,huō,huá"] = "豁",
["pù,bào"] = "瀑",
["chuō"] = "戳",
["zǎn,cuán"] = "攒",
["cèng"] = "蹭",
["bò,bǒ"] = "簸",
["bó,bù"] = "簿",
["bìn"] = "鬓",
["suǐ"] = "髓",
["ráng"] = "瓤",
}
if type(module) == "table" then
module.exports = dictWeb
else
return dictWeb
end
|
local fruit = {}
math.randomseed(os.time())
--Luobo baicai wandou nangua gangzhe mogu guangchangsu yidianhong
local fruitType = {
"luobo",
"baicai",
"wandou",
"nangua",
"gangzhe",
"mogu",
"guangchangsu",
"yidianhong",
}
fruitType.luobo = 1
fruitType.baicai = 2
fruitType.wandou = 3
fruitType.nangua = 4
fruitType.gangzhe = 5
fruitType.mogu = 6
fruitType.guangchangsu=7
fruitType.yidianhong=8
--中奖概率
local gailu = {
luobo = 23.94,
baicai = 23.93,
wandou = 23.75,
nangua = 11.88,
gangzhe = 7.92,
mogu = 3.96,
guangchangsu = 2.64,
yidianhong = 1.98,
}
--倍率
local beilu = {
luobo = 2,
baicai = 2,
wandou = 4,
nangua = 8,
gangzhe = 12,
mogu = 24,
guangchangsu = 36,
yidianhong = 48,
}
local LUOBO = 0 + gailu.luobo*100
local BAICAI = LUOBO + gailu.baicai*100
local WANDOU = BAICAI + gailu.wandou*100
local NANGUA = WANDOU + gailu.nangua*100
local GANGZHE = NANGUA + gailu.gangzhe*100
local MOGU = GANGZHE + gailu.mogu*100
local GUANGCHANGSU = MOGU + gailu.guangchangsu*100
local YIDIANHONG = GUANGCHANGSU + gailu.yidianhong*100
-- print(LUOBO)
-- print(BAICAI)
-- print(WANDOU)
-- print(NANGUA)
-- print(GANGZHE)
-- print(MOGU)
-- print(GUANGCHANGSU)
-- print(YIDIANHONG)
-- io.read()
-- -- local BAICAI = 4748
-- -- local WANDOU = 7162
-- -- local NANGUA = 8350
-- -- local GANGZHE = 9142
-- -- local MOGU = 9538
-- -- local GUANGCHANGSU = 9802
-- -- local YIDIANHONG = 10000
local ERRORCODE = require "errorcode"
local MINDEALERMONEY = 10000000
fruit.player={}
fruit.alreadyya={}
function fruit:newgame( )--清除数据,游戏重新开始
local t=self.alreadyya
t.luobo=0
t.baicai=0
t.wandou=0
t.nangua=0
t.gangzhe=0
t.mogu=0
t.guangchangsu=0
t.yidianhong=0
for k,v in pairs(self.player) do
for i,j in pairs(v) do
if i~="money" and i~="win" and i~="currentwin" and i~="mylistnum" then
v[i]=0
end
end
end
end
function fruit:setDealer( id )--不允许外部调用
if not id then
self.dealer=nil--电脑做庄家
elseif not self.player[id] then
print("玩家不在房间,不能成为地主")
return false
elseif self.player[id].money<MINDEALERMONEY then
print("钱不够,不能成为地主")
return false
else
self.dealer={uniid=id,money=self.player[id].money}
return true
end
end
function fruit:exitDealer( id )--不允许外部调用
if self.dealer and self.dealer.uniid==id then
self:changeDearler( )
return true
else
return false
end
end
function fruit:getMyListNum( uniid )--返回我所在队列的是第几
for k,v in pairs(self.list) do
if v==uniid then
return k
end
end
if fruit:getDealerUid()==uniid then
return -1 --是庄家显示-1
end
return 0--没人显示0,防止为空
end
fruit.list={}
function fruit:wantDealer( id )
if self.dealer and self.dealer.uniid==id then
print("已是庄家,不要排队")
return false,ERRORCODE.alreadyisdealer
elseif not self.player[id] then
print(id)
print("玩家不在房间,不能上庄")
return false,ERRORCODE.nopeople
elseif self.player[id].money<MINDEALERMONEY then
print("你的钱不够")
return false,ERRORCODE.wantdealernoenoughmoney
else
for k,v in pairs(self.list) do
if v==id then
print("玩家已在列表")
return false,ERRORCODE.alreadyonlist
end
end
table.insert(self.list,id)
-- if not self.dealer then--电脑做庄家,新来的人马上上位 注释原因:因为状态未知,所以不能马上上位
-- self:changeDearler( )
-- end
end
return true
end
function fruit:changeDearler( )
self:setDealer(self:popDearlerList())
self.status.score=0
self.status.reselect=0
end
function fruit:exitDearlerList( id )
if not self.player[id] then
return false,ERRORCODE.nopeople
else
local index = -1
for k,v in pairs(self.list) do
if v==id then
index=k
break
end
end
if index==-1 then
print("玩家不在队列!")
return false,ERRORCODE.notinlist
else
table.remove(self.list,index)
end
end
return true
end
function fruit:getDearlerList( )
return self.list
end
function fruit:popDearlerList( )
if #self.list~=0 then
return table.remove(self.list,1)
else
print("队列为空")
return nil
end
end
function fruit:isComputer( )
if self.dealer then
return false
end
return true
end
function fruit:getDealer( )
return self.dealer
end
function fruit:getDealerUid( )
if not self.dealer then
return "computer"
else
return self.dealer.uniid
end
end
function fruit:getDealerMoney( )
if not self.dealer then
return tonumber(999999999999)
else
return self.dealer.money
end
end
function fruit:getResult( )
local x = math.random(10000)
local index = math.random(0,2)
if x>=1 and x<=LUOBO then--萝卜
return "luobo",index
elseif x>LUOBO and x<=BAICAI then--白菜
return "baicai",index
elseif x>BAICAI and x<=WANDOU then--豌豆
return "wandou",index
elseif x>WANDOU and x<=NANGUA then--南瓜
return "nangua",index
elseif x>NANGUA and x<=GANGZHE then --甘蔗
return "gangzhe",index
elseif x>GANGZHE and x<=MOGU then --蘑菇
return "mogu",index
elseif x>MOGU and x<= GUANGCHANGSU then --关仓术
return "guangchangsu",index
elseif x>GUANGCHANGSU and x<=YIDIANHONG then--一点红
return "yidianhong",index
end
end
function fruit:getPlayer( )
local tmp = {}
for k,v in pairs(self.player) do
table.insert(tmp,k)
end
return tmp
end
function fruit:newPlayer( uniid, money)
if self.player[uniid] then
print("player alreader exit in the game!")
return false,ERRORCODE.useralreadyexit
end
self.player[uniid]={}
self.player[uniid].money=money
self.player[uniid].luobo=0
self.player[uniid].baicai=0
self.player[uniid].wandou=0
self.player[uniid].nangua=0
self.player[uniid].gangzhe=0
self.player[uniid].mogu=0
self.player[uniid].guangchangsu=0
self.player[uniid].yidianhong=0
----
self.player[uniid].currentwin=0
self.player[uniid].win=0
self.player[uniid].mylistnum=0
return true
end
function fruit:playerExit( uniid )
--如果玩家在庄家排队的队列中,将其从队列移除
fruit:exitDearlerList( uniid )
print("------sadfasdfasdfasdfasdf",uniid)
self.player[uniid]=nil
if self.dealer and self.dealer.uniid==uniid then--如果玩家是dealer的话,把它退出
self.dealer=nil
self:setDealer(self:popDearlerList())--队列玩家做庄家
end
end
function fruit:getPlayerCount( )
local count = 0
for k,v in pairs(self.player) do
count=count+1
end
return count
end
------------------
function fruit:ya( uniid,type,money )
--print("userid",self:getDealerUid())
if money<0 or not fruitType[type] then--不合法的钱的,水果类型
return false,ERRORCODE.moneyandtype
elseif not self.player[uniid] then
print("此人不存在")
return false,ERRORCODE.nopeople
elseif self:getDealerUid()==uniid then
print("地主不要压")
return false,ERRORCODE.dealerya
end
type=fruitType[type]
if self.player[uniid][type]~=0 then
print("你已经压过",type)
return false,ERRORCODE.havedya
end
--print("aaaaaaa",self.player[uniid][type],type)
if self.player[uniid].money<money then--压的人钱已经不够
print("you havent so many money!")
return false,ERRORCODE.yanoenoughmoney
end
local playercount = self:getPlayerCount()-1--减不包括庄家
print("此处上限",playercount,beilu[type],(self:getDealerMoney()/playercount)/beilu[type],money)
if (self:getDealerMoney()/playercount)/beilu[type] >= money then
self.player[uniid][type]=money+self.player[uniid][type]
self.alreadyya[type]=self.alreadyya[type]+money
self.player[uniid].money=self.player[uniid].money-money
print("dealer have to pay you",(self.player[uniid][type])*beilu[type],self:getDealerMoney() )
return true
else
--压钱超庄家可赔上限
print("压钱超庄家可赔上限!",(self:getDealerMoney()/playercount)/beilu[type])
return false,ERRORCODE.uppermoneylimit
end
end
function fruit:yaLouBo( uniid,money )
return self:ya(uniid,fruitType.luobo,money)
end
function fruit:yaBaiCai( uniid,money )
return self:ya(uniid,fruitType.baicai,money)
end
function fruit:yaWanDou( uniid,money )
return self:ya(uniid,fruitType.wandou,money)
end
function fruit:yaNanGua( uniid,money )
return self:ya(uniid,fruitType.nangua,money)
end
function fruit:yaGangZhe( uniid,money )
return self:ya(uniid,fruitType.gangzhe,money)
end
function fruit:yaMoGu( uniid,money )
return self:ya(uniid,fruitType.mogu,money)
end
function fruit:yaGuangChangSu( uniid,money )
return self:ya(uniid,fruitType.guangchangsu,money)
end
function fruit:yaYiDianHong( uniid,money )
return self:ya(uniid,fruitType.yidianhong,money)
end
function fruit:syncDealerMoney( )--sync Dealer Money in Player[uniid]
if self.dealer then--如果此玩家是地主,将它的钱同步起来
local uniid = self.dealer.uniid
self.player[uniid].money=self.dealer.money
self.player[uniid].currentwin=self.status.score
self.player[uniid].win=self.player[uniid].currentwin+self.player[uniid].win
self.status.score=0--score 是一局的分数,
end
end
function fruit:getPlayerStatus( uniid )
local tmp = {}
for k,v in pairs(self.player[uniid]) do
tmp[k]=v
end
tmp.mylistnum=self:getMyListNum( uniid )--获得自己的排队队列
return tmp
end
function fruit:getPlayerMoney( uniid )
return self.player[uniid].money
end
function fruit:getReslectCount( )
return self.status.reselect
end
fruit.status={score=0,reselect=0}
function fruit:getGameStatus( )
self.status.dealer=self:getDealerUid()
self.status.dealermoney=self:getDealerMoney()
-- self.status.score=0--暂定
-- self.status.reselect=0--暂定
local t=self.alreadyya
self.status.luobo=t.luobo
self.status.baicai=t.baicai
self.status.wandou=t.wandou
self.status.nangua=t.nangua
self.status.gangzhe=t.gangzhe
self.status.mogu=t.mogu
self.status.guangchangsu=t.guangchangsu
self.status.yidianhong=t.yidianhong
self.status.waitinglist=self:getDearlerList()
self.status.onlinepeople=self:getPlayer()--在线的用户,包括自己
local tmp = {}
for k,v in pairs(self.status) do
tmp[k]=v
end
if self.dealer then
tmp.score=self.player[self:getDealerUid()].currentwin
end
return tmp
end
fruit.resulttable={}
function fruit:open( )
local result,index = self:getResult()
self.resulttable.result=result
self.resulttable.index=index
print("----------------------result",result,index)
self.status.reselect=self.status.reselect+1
local dealer = self:getDealer()
for k,v in pairs(self.player) do--遍历玩家table,把不是中奖的钱全部收为自己所有
v.currentwin=0--当前局的状态先置0
for i,j in pairs(v) do
--扩展性不是很好的If语句
if i~="money" and i~="win" and i~="currentwin" and i~="mylistnum" then
if i~= result then
if dealer then
dealer.money = dealer.money + j
--庄家需要知道他的分数
self.status.score = self.status.score + j
end
--记录玩家当前局所得,负就是失去
v.currentwin=v.currentwin-j
else
if dealer then
--print("beilu[i]*j",beilu[i]*j)
--庄家需要知道他的分数
self.status.score = self.status.score - beilu[i]*j
dealer.money = dealer.money - beilu[i]*j
-- v.money=v.money+beilu[i]*j+j----本钱还
end
v.money=v.money+beilu[i]*j--本钱不还,庄家赔相应倍率,本钱系统收取
v.currentwin=v.currentwin+beilu[i]*j-j--算上自己压的钱,其实只羸了倍率减一的钱
end
end
end
v.win=v.win+v.currentwin
end
self:syncDealerMoney( )--syncDealerMoney in Player[uniid]
local resulttmp = {}
resulttmp.result=self.resulttable.result
resulttmp.index=self.resulttable.index
return resulttmp
end
return fruit
|
local multiplier = technic.config:get_int("max_lag_reduction_multiplier")
local last_step = minetest.get_us_time()
local max_lag = 0
minetest.register_globalstep(function()
-- Calculate own dtime as a workaround to 2 second limit
local now = minetest.get_us_time()
local dtime = now - last_step
last_step = now
max_lag = max_lag * multiplier -- Decrease slowly
if dtime > max_lag then
max_lag = dtime
end
end)
function technic.get_max_lag()
return max_lag / 1000000
end
|
return setmetatable({}, {
__index = function (table, file)
local ok, icons = pcall(require, 'meta.icon.' .. file)
if not ok then
error('Icon set ' .. file .. ' not found.')
return ok
end
return icons
end,
})
|
--
-- Do Not Disturb utility
--
-- You need to set up a shortcut to toggle Do Not Disturb to use this script.
-- See the dndKeyStroke() function.
--
local no = require('lib/notification_lib')
local st = require('lib/string_lib')
local timer = require('lib/timer_lib')
local dnd = {}
local logger = hs.logger.new('dnd_lib', 5)
function dnd.isOn()
-- 1: on, 0: off
local result = hs.execute('defaults read com.apple.controlcenter "NSStatusItem Visible FocusModes"')
result = st.trim(result)
return result == '1'
end
-- The shortcut for Turn Do Not Disturb On/Off has to be set via:
-- System Preferences - Keyboard - Shortcuts - Mission Control - Turn Do Not Disturb On/Off
local function dndKeyStroke()
hs.eventtap.keyStroke({'ctrl', 'alt', 'cmd', 'shift'}, 'z')
end
function dnd.turnOn()
no.alert('Turning DND On')
if dnd.isOn() then
logger:d('DND is already on.')
else
logger:d('Turning DND On')
dndKeyStroke()
end
end
function dnd.turnOff()
no.alert('Turning DND Off')
if not dnd.isOn() then
logger:d('DND is already off.')
else
logger:d('Turning DND Off')
dndKeyStroke()
end
end
-- It has a retry logic since dndKeyStroke() could fail
-- especially when it's triggered right after waking up.
--
-- sleep() is needed between retrial since it takes time
-- until a change is applied and isOn() returns correct state.
function dnd.turnOffAfterSleep()
timer.safeDoUntil(function()
return not dnd.isOn()
end, function()
dndKeyStroke()
timer.sleep(8)
end, function()
logger:d('Failed to trun DND Off')
end)
end
function dnd.conditionallyTurnOnOff()
-- The number of connected screens can be also used.
if hs.battery.powerSource() == 'AC Power' then
logger:d('AC Power and turning off DND')
dnd.turnOffAfterSleep()
else
logger:d('No AC Power and turning on DND')
dnd.turnOn()
end
end
return dnd
|
object_mobile_dressed_npe_aquillia = object_mobile_shared_dressed_npe_aquillia:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_npe_aquillia, "object/mobile/dressed_npe_aquillia.iff")
|
--
-- Copyright (C) 2021 Vlad Lazarenko <vlad@lazarenko.me>
--
-- 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
--
-- https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
print("Configuring the application...")
local cfg = confetti
cfg.simple_string = "Hello, Lua!"
cfg.simple_number = 12345
cfg.simple_double_number = 19.86
cfg.simple_double_string = "-19.86"
cfg.simple_zero = 0
cfg.simple_yes = true
cfg.simple_no = false
cfg.simple_func = function()
return 2 + 2
end
cfg.simple_nested_func = function()
return function()
return 2 + 2 * 2
end
end
cfg.simple_nested_math = function()
return function()
return 2.5 * 2.5
end
end
cfg["user"] = {
name = "Vlad Lazarenko",
email = "vlad@lazarenko.me"
}
cfg.days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }
|
--[[
- Ball physics replication
Ball motion is server-authoritative and client-predictive
The server sets the position and rotation of a folder every frame representing the ball's position and direction
The client simulates the same physics occurring on the server according to its own perspective
Each time the folder moves, the client overwrites its own ball position and velocity
The client has an internal representation of the ball position and velocity which is separate from the visible ball
When there is an offset between the visible and non-visible ball, the visible ball gradually accelerates towards the desired position (rather than teleporting)
]]
local utils, BallPhysics, BrickController
local BALL_CONTAINER = script:GetCustomProperty("BALL_CONTAINER"):WaitForObject()
local BallController = {
BALL_CONTAINER = BALL_CONTAINER
}
function BallController.Setup(dependencies)
utils = dependencies.utils
BallPhysics = dependencies.BallPhysics
BrickController = dependencies.BrickController
Task.Spawn(function() -- delay to ensure dependencies call Setup first
for _, ball in pairs(BALL_CONTAINER:GetChildren()) do
BallController.AddBall(ball)
end
BALL_CONTAINER.childAddedEvent:Connect(function(_, ballObject)
BallController.AddBall(ballObject)
end)
end)
end
function BallController.AddBall(ballObject)
while not ballObject:GetCustomProperty("ServerPosition") do Task.Wait() end -- custom properties can be missing at first
local serverPosition = ballObject:GetCustomProperty("ServerPosition"):WaitForObject()
local serverTrigger = ballObject:GetCustomProperty("ServerTrigger"):WaitForObject()
local clientBall = ballObject:GetCustomProperty("ClientBall"):WaitForObject()
local clientContext = clientBall.parent
local clientTrigger = ballObject:GetCustomProperty("ClientTrigger"):WaitForObject()
local ball = {
object = ballObject,
position = serverTrigger:GetWorldPosition(),
velocity = serverTrigger:GetWorldRotation() * Vector3.FORWARD * utils.BALL_SPEED,
radius = utils.BALL_RADIUS,
reflectionsThisFrame = {}
}
ballObject.clientUserData.internalData = ball
local lastPosition = serverTrigger:GetWorldPosition()
local deltaTime = 0
local fixedDelta = utils.FIXED_DELTA_TIME
local loop = Task.Spawn(function(dt)
local position = serverTrigger:GetWorldPosition()*(Vector3.ONE - Vector3.UP)
if serverTrigger.parent == serverPosition then
deltaTime = deltaTime + dt
while deltaTime > fixedDelta do -- forward simulation
deltaTime = deltaTime - fixedDelta
ball.position = ball.position + ball.velocity * fixedDelta
BallPhysics.CheckCollisions(ball)
ball.reflectionsThisFrame = {}
if serverTrigger.parent ~= serverPosition then break end
end
if position ~= lastPosition then
local direction = serverTrigger:GetWorldRotation() * Vector3.FORWARD
ball.velocity = direction * ball.velocity.size
ball.position = ball.position:Lerp(position, .7)
lastPosition = position
end
clientBall:SetWorldPosition(clientBall:GetWorldPosition():Lerp(ball.position, .7))
else -- ball is attached to a paddle
lastPosition = position
clientBall:SetPosition(clientBall:GetPosition():Lerp(serverTrigger:GetPosition(), .5))
end
end)
loop.repeatCount = -1
serverPosition.childRemovedEvent:Connect(function(_, child)
if child == serverTrigger then
Task.Wait() -- parent is nil immediately following childRemovedEvent even if it was just the parent being changed
if Object.IsValid(serverPosition) and child.parent ~= serverPosition then
clientBall.parent = child.parent.parent:GetCustomProperty("ClientGroup"):WaitForObject()
end
end
end)
serverPosition.childAddedEvent:Connect(function(_, child)
if child == serverTrigger then
local paddleGroup = clientBall.parent
clientBall.parent = clientContext
ball.position = clientBall:GetWorldPosition()
ball.velocity = BallPhysics.GetThrowVelocity(ball, {position = paddleGroup:GetWorldPosition(), rotation = paddleGroup:GetWorldRotation()})
end
end)
ballObject.destroyEvent:Connect(function()
loop:Cancel()
end)
clientTrigger.beginOverlapEvent:Connect(function(_, trigger)
local brick = BrickController.brickLookup[trigger.parent]
if brick then
if brick.simulatedBallHit then return end
brick.simulatedBallHit = true -- brick was hit on the client
local collisionVFX = utils.PlayVFX("destroyBrickSparkVFX", brick.position)
local color = utils.TEAM_COLORS[brick.team]
local vfx = collisionVFX:FindChildByName("VFX")
vfx:SetSmartProperty("Color", color)
BallPhysics.BounceOffNearestEdge(ball, brick.position)
end
end)
end
return BallController
|
object_tangible_quest_quest_start_update_14_quest_comlink = object_tangible_quest_quest_start_shared_update_14_quest_comlink:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_quest_start_update_14_quest_comlink, "object/tangible/quest/quest_start/update_14_quest_comlink.iff")
|
-- Copyright 2006-2015 Mitchell mitchell.att.foicica.com. See LICENSE.
-- APDL LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'apdl'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, '!' * l.nonnewline^0)
-- Strings.
local string = token(l.STRING, l.delimited_range("'", true, true))
-- Numbers.
local number = token(l.NUMBER, l.float + l.integer)
-- Keywords.
local keyword = token(l.KEYWORD, word_match({
'*abbr', '*abb', '*afun', '*afu', '*ask', '*cfclos', '*cfc', '*cfopen',
'*cfo', '*cfwrite', '*cfw', '*create', '*cre', '*cycle', '*cyc', '*del',
'*dim', '*do', '*elseif', '*else', '*enddo', '*endif', '*end', '*eval',
'*eva', '*exit', '*exi', '*get', '*go', '*if', '*list', '*lis', '*mfouri',
'*mfo', '*mfun', '*mfu', '*mooney', '*moo', '*moper', '*mop', '*msg',
'*repeat', '*rep', '*set', '*status', '*sta', '*tread', '*tre', '*ulib',
'*uli', '*use', '*vabs', '*vab', '*vcol', '*vco', '*vcum', '*vcu', '*vedit',
'*ved', '*vfact', '*vfa', '*vfill', '*vfi', '*vfun', '*vfu', '*vget', '*vge',
'*vitrp', '*vit', '*vlen', '*vle', '*vmask', '*vma', '*voper', '*vop',
'*vplot', '*vpl', '*vput', '*vpu', '*vread', '*vre', '*vscfun', '*vsc',
'*vstat', '*vst', '*vwrite', '*vwr', '/anfile', '/anf', '/angle', '/ang',
'/annot', '/ann', '/anum', '/anu', '/assign', '/ass', '/auto', '/aut',
'/aux15', '/aux2', '/aux', '/axlab', '/axl', '/batch', '/bat', '/clabel',
'/cla', '/clear', '/cle', '/clog', '/clo', '/cmap', '/cma', '/color', '/col',
'/com', '/config', '/contour', '/con', '/copy', '/cop', '/cplane', '/cpl',
'/ctype', '/cty', '/cval', '/cva', '/delete', '/del', '/devdisp', '/device',
'/dev', '/dist', '/dis', '/dscale', '/dsc', '/dv3d', '/dv3', '/edge', '/edg',
'/efacet', '/efa', '/eof', '/erase', '/era', '/eshape', '/esh', '/exit',
'/exi', '/expand', '/exp', '/facet', '/fac', '/fdele', '/fde', '/filname',
'/fil', '/focus', '/foc', '/format', '/for', '/ftype', '/fty', '/gcmd',
'/gcm', '/gcolumn', '/gco', '/gfile', '/gfi', '/gformat', '/gfo', '/gline',
'/gli', '/gmarker', '/gma', '/golist', '/gol', '/gopr', '/gop', '/go',
'/graphics', '/gra', '/gresume', '/gre', '/grid', '/gri', '/gropt', '/gro',
'/grtyp', '/grt', '/gsave', '/gsa', '/gst', '/gthk', '/gth', '/gtype', '/gty',
'/header', '/hea', '/input', '/inp', '/larc', '/lar', '/light', '/lig',
'/line', '/lin', '/lspec', '/lsp', '/lsymbol', '/lsy', '/menu', '/men',
'/mplib', '/mpl', '/mrep', '/mre', '/mstart', '/mst', '/nerr', '/ner',
'/noerase', '/noe', '/nolist', '/nol', '/nopr', '/nop', '/normal', '/nor',
'/number', '/num', '/opt', '/output', '/out', '/page', '/pag', '/pbc', '/pbf',
'/pcircle', '/pci', '/pcopy', '/pco', '/plopts', '/plo', '/pmacro', '/pma',
'/pmeth', '/pme', '/pmore', '/pmo', '/pnum', '/pnu', '/polygon', '/pol',
'/post26', '/post1', '/pos', '/prep7', '/pre', '/psearch', '/pse', '/psf',
'/pspec', '/psp', '/pstatus', '/pst', '/psymb', '/psy', '/pwedge', '/pwe',
'/quit', '/qui', '/ratio', '/rat', '/rename', '/ren', '/replot', '/rep',
'/reset', '/res', '/rgb', '/runst', '/run', '/seclib', '/sec', '/seg',
'/shade', '/sha', '/showdisp', '/show', '/sho', '/shrink', '/shr', '/solu',
'/sol', '/sscale', '/ssc', '/status', '/sta', '/stitle', '/sti', '/syp',
'/sys', '/title', '/tit', '/tlabel', '/tla', '/triad', '/tri', '/trlcy',
'/trl', '/tspec', '/tsp', '/type', '/typ', '/ucmd', '/ucm', '/uis', '/ui',
'/units', '/uni', '/user', '/use', '/vcone', '/vco', '/view', '/vie',
'/vscale', '/vsc', '/vup', '/wait', '/wai', '/window', '/win', '/xrange',
'/xra', '/yrange', '/yra', '/zoom', '/zoo'
}, '*/', true))
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Functions.
local func = token(l.FUNCTION, l.delimited_range('%', true, true))
-- Operators.
local operator = token(l.OPERATOR, S('+-*/$=,;()'))
-- Labels.
local label = token(l.LABEL, l.starts_line(':') * l.word)
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'identifier', identifier},
{'string', string},
{'number', number},
{'function', func},
{'label', label},
{'comment', comment},
{'operator', operator},
}
M._foldsymbols = {
_patterns = {'%*[A-Za-z]+', '!'},
[l.KEYWORD] = {
['*if'] = 1, ['*IF'] = 1, ['*do'] = 1, ['*DO'] = 1, ['*dowhile'] = 1,
['*DOWHILE'] = 1,
['*endif'] = -1, ['*ENDIF'] = -1, ['*enddo'] = -1, ['*ENDDO'] = -1
},
[l.COMMENT] = {['!'] = l.fold_line_comments('!')}
}
return M
|
AddCSLuaFile()
if SERVER then
AddCSLuaFile("TR/cl_init.lua")
include("TR/sv_init.lua")
AddCSLuaFile("TR/sh_deprecated.lua")
include("TR/sh_deprecated.lua")
else
include("TR/cl_init.lua")
include("TR/sh_deprecated.lua")
end
|
ResetState = Class{__includes = BaseState}
function ResetState:init()
end
function ResetState:enter(params)
self.score = params.score
self.timer = params.timer
self.level = params.level
self.scoreGoal = params.goal
self.board = Board(GRID_START_X, GRID_START_Y, self.level)
Timer.after(2, function()
self.continue = true
end)
Timer.every(0.5, function()
self.blinkText = not self.blinkText
end)
end
function ResetState:update(dt)
if (love.keyboard.wasPressed('enter') or love.keyboard.wasPressed('return')) and self.continue then
gStateMachine:change('play', {
score = self.score,
timer = self.timer,
level = self.level,
board = self.board,
alpha = self.transitionAlpha,
})
end
Timer.update(dt)
end
function ResetState:render()
self.board:render()
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setColor(56, 56, 56, 234)
love.graphics.rectangle('fill', 16, 16, 186, 116, 4)
love.graphics.setColor(99, 155, 255, 255)
love.graphics.setFont(gFonts['medium'])
love.graphics.printf('Level: ' .. tostring(self.level), 20, 24, 182, 'center')
love.graphics.printf('Score: ' .. tostring(self.score), 20, 52, 182, 'center')
love.graphics.printf('Goal : ' .. tostring(self.scoreGoal), 20, 80, 182, 'center')
love.graphics.printf('Timer: ' .. tostring(self.timer), 20, 108, 182, 'center')
love.graphics.setFont(gFonts['max'])
love.graphics.setColor(56, 56, 56, 234)
love.graphics.rectangle('fill', VIRTUAL_WIDTH - 272, 16, 256, 256)
love.graphics.setColor(99, 155, 255, 255)
love.graphics.printf('BOARD\nRESET', VIRTUAL_WIDTH - 272, VIRTUAL_HEIGHT / 2 - 60, 272, 'center')
if self.continue then
if self.blinkText then
love.graphics.setColor(99, 155, 255, 255)
else
love.graphics.setColor(255, 255, 255, 255)
end
love.graphics.setFont(gFonts['medium'])
love.graphics.printf('Press Enter to Continue...', VIRTUAL_WIDTH - 272, VIRTUAL_HEIGHT / 2 + 52, 272, 'center')
end
end
|
--[[
Makes the player drop the prop they are holding to prevent prop surfing
--]]
local function DropProp( ply )
if IsValid(ply) && !ply:OnGround() then
ply:DropObject()
end
end
PlayerThink.hookAdd( "Player.DropProp", DropProp )
|
return {
{
name = "2016-12-09-132400_init_accesslimiting",
up = [[
CREATE TABLE IF NOT EXISTS accesslimiting_blacklist(
api_id uuid,
ip varchar(40),
PRIMARY KEY (api_id, ip)
);
create table if not exists accesslimiting_record(
api_id uuid,
ip varchar(40),
created_at timestamp
);
TRUNCATE TABLE accesslimiting_record;
CREATE INDEX IF NOT EXISTS ON accesslimiting_record(created_at);
]],
down = [[
DROP TABLE accesslimiting_blacklist;
DROP TABLE accesslimiting_record;
]]
}
}
|
return {'roijen','roijackers','roijakkers','roijers','roijmans'}
|
local util = require "irccd.util"
local thread = require "irccd.thread"
function onLoad()
thread.new(startLoop)
end
-- starts in new thread
function startLoop()
-- require it here because thread functions does not see global vars
local server = require "irccd.server"
local system = require "irccd.system"
local fs = require "irccd.fs"
local util = require "irccd.util"
-- configuration
local serverName = "wenet"
local channelName = "#nfk"
local fileCheckInterval = 30 -- in seconds check file modification
local fileSendInterval = 15*1000 -- 15 minutes (in milliseconds) interval from file modification to send message (youtube video should be ready)
local filename = "message.txt"
local messages = {}
local lastModTime = 0
while true do
system.usleep(fileCheckInterval)
local s = server.find(serverName)
local f = io.open(filename, "r")
local stat = fs.stat(filename)
if stat.mtime then
-- file modified time
local filemtime = stat.mtime:format("%H%M%S")
-- if file was modified
if not (lastModTime == filemtime) then
local content = f:read()
if content then
-- add new item to table
table.insert(messages, {sendtime = system.ticks()+fileSendInterval, text = content})
lastModTime = filemtime
end
end
end
-- iterate table to find expired messages
for k,v in pairs(messages) do
if (system.ticks() > v.sendtime) then
-- send a message
s:say(channelName, v.text)
-- remove item
table.remove(messages, k)
end
end
--print(system.ticks() .. " / " .. #messages)
end
end
|
local M = {}
-- pathes
M.PATH_OBJ = "."
M.PATH_COMP = "#"
M.PATH_RENDER = "@render:"
M.PATH_SYSTEM = "@system:"
M.PATH_TILES_FACTORY = "factories#tiles"
-- screens
M.SRC_GAME = hash("game_screen")
-- popups
-- custom events
-- defold events
-- objects
M.ENABLE = hash("enable")
M.DISABLE = hash("disable")
-- render_script
M.RENDER_WINDOW_RESIZED = hash("window_resized")
M.RENDER_CLEAR_COLOR = hash("clear_color")
M.RENDER_SET_VIEW_PROJECTION = hash("set_view_projection")
M.SRC_LANDSCAPE = hash("landscape")
M.SRC_PORTRAIT = hash("portrait")
--input
M.I_CLICK = hash("click")
local ADD_FOCUS = hash("acquire_input_focus")
local REMOVE_FOCUS = hash("release_input_focus")
function M.focus(self)
if not self.input_inited then
self.input_inited = true
msg.post(M.PATH_OBJ, ADD_FOCUS)
end
end
function M.remove(self)
if self.input_inited then
self.input_inited = nil
msg.post(M.PATH_OBJ, REMOVE_FOCUS)
end
end
return M
|
local _, Engine = ...
local Module = Engine:GetModule("ActionBars")
local ControllerWidget = Module:SetWidget("Controller: Stance")
local L = Engine:GetLocale()
-- Lua API
local pairs = pairs
local setmetatable = setmetatable
local tconcat, tinsert = table.concat, table.insert
-- WoW API
local GetNumShapeshiftForms = GetNumShapeshiftForms
ControllerWidget.OnEnable = function(self)
local config = Module.config
local control_config = Module.config.structure.controllers.stance
local button_config = Module.config.visuals.stance.button
local window_config = Module.config.visuals.stance.window
local UICenter = Engine:GetFrame()
local Main = Module:GetWidget("Controller: Main"):GetFrame()
local Side = Module:GetWidget("Controller: Side"):GetFrame()
local MenuButton = Module:GetWidget("Template: MenuButton")
local FlyoutBar = Module:GetWidget("Template: FlyoutBar")
local point = control_config.position.point
local anchor = control_config.position.anchor
local anchor_point = control_config.position.anchor_point
local xoffset = control_config.position.xoffset
local yoffset = control_config.position.yoffset
if anchor == "UICenter" then
anchor = UICenter
elseif anchor == "Main" then
anchor = Main
elseif anchor == "Side" then
anchor = Side
end
self.Controller = CreateFrame("Frame", nil, UICenter, "SecureHandlerAttributeTemplate")
self.Controller:SetFrameStrata("BACKGROUND")
self.Controller:SetPoint(point, anchor, anchor_point, xoffset, yoffset)
self.Controller:SetSize(unpack(control_config.size))
-- Main Button
---------------------------------------------
local StanceButton = MenuButton:New(self.Controller)
StanceButton:SetSize(unpack(button_config.size))
StanceButton:SetPoint(unpack(button_config.position))
StanceButton:SetFrameStrata("MEDIUM")
StanceButton:SetFrameLevel(50) -- get it above the actionbars
StanceButton.Normal = StanceButton:CreateTexture(nil, "BORDER")
StanceButton.Normal:ClearAllPoints()
StanceButton.Normal:SetPoint(unpack(button_config.texture_position))
StanceButton.Normal:SetSize(unpack(button_config.texture_size))
StanceButton.Normal:SetTexture(button_config.textures.normal)
StanceButton.Pushed = StanceButton:CreateTexture(nil, "BORDER")
StanceButton.Pushed:Hide()
StanceButton.Pushed:ClearAllPoints()
StanceButton.Pushed:SetPoint(unpack(button_config.texture_position))
StanceButton.Pushed:SetSize(unpack(button_config.texture_size))
StanceButton.Pushed:SetTexture(button_config.textures.pushed)
StanceButton.OnButtonState = function(self, state, lock)
if state == "PUSHED" then
self.Pushed:Show()
self.Normal:Hide()
else
self.Normal:Show()
self.Pushed:Hide()
end
end
hooksecurefunc(StanceButton, "SetButtonState", StanceButton.OnButtonState)
StanceButton.OnEnter = function(self)
if StanceButton:GetButtonState() == "PUSHED" then
GameTooltip:Hide()
return
end
GameTooltip_SetDefaultAnchor(GameTooltip, self)
GameTooltip:AddLine(L["Stances"]) -- different text based on class
GameTooltip:AddLine(L["<Left-click> to toggle stance bar."], 0, .7, 0)
GameTooltip:Show()
end
StanceButton:SetScript("OnEnter", StanceButton.OnEnter)
StanceButton:SetScript("OnLeave", function(self) GameTooltip:Hide() end)
StanceButton.OnClick = function(self, button)
if button == "LeftButton" then
self:OnEnter() -- update tooltips
end
end
StanceButton:RegisterForClicks("AnyDown")
StanceButton:SetHitRectInsets(0, 0, 0, 0)
StanceButton:OnButtonState(StanceButton:GetButtonState())
-- Stance Window
---------------------------------------------
local StanceWindow = FlyoutBar:New(StanceButton)
StanceWindow:AttachToButton(StanceButton)
StanceWindow:SetPoint(unpack(window_config.position))
StanceWindow:SetSize(unpack(window_config.size))
self.StanceButton = StanceButton
self.StanceWindow = StanceWindow
self:RegisterEvent("PLAYER_ENTERING_WORLD", "OnEvent")
self:RegisterEvent("UPDATE_BONUS_ACTIONBAR", "OnEvent")
self:RegisterEvent("UPDATE_VEHICLE_ACTIONBAR", "OnEvent")
self:RegisterEvent("UPDATE_OVERRIDE_ACTIONBAR", "OnEvent")
self:RegisterEvent("ACTIONBAR_PAGE_CHANGED", "OnEvent")
self:RegisterEvent("UPDATE_SHAPESHIFT_FORM", "OnEvent")
self:RegisterEvent("UPDATE_SHAPESHIFT_FORMS", "OnEvent")
self:RegisterEvent("UPDATE_SHAPESHIFT_USABLE", "OnEvent")
self:RegisterEvent("UPDATE_POSSESS_BAR", "OnEvent")
end
ControllerWidget.OnEvent = function(self, event, ...)
if event == "PLAYER_ENTERING_WORLD" then
self:UpdateBarArtwork() -- this is where we style the stancebuttons
self:UnregisterEvent("PLAYER_ENTERING_WORLD", "OnEvent") -- should only need it once
end
self:UpdateStanceButton()
end
ControllerWidget.UpdateStanceButton = Engine:Wrap(function(self)
local Controller = self.Controller
local num_forms = GetNumShapeshiftForms()
if num_forms == 0 then
UnregisterStateDriver(Controller, "visibility")
RegisterStateDriver(Controller, "visibility", "hide")
else
local driver = {}
if Engine:IsBuild("MoP") then -- also applies to WoD and (possibly) Legion
tinsert(driver, "[overridebar][possessbar][shapeshift]hide")
tinsert(driver, "[vehicleui]hide")
elseif Engine:IsBuild("WotLK") then -- also applies to Cata
tinsert(driver, "[bonusbar:5]hide")
tinsert(driver, "[vehicleui]hide")
end
tinsert(driver, "show")
UnregisterStateDriver(Controller, "visibility")
RegisterStateDriver(Controller, "visibility", tconcat(driver, "; "))
end
-- should be options somewhere for this
local Bar = Module:GetWidget("Bar: Stance"):GetFrame()
if Bar then
self.StanceWindow:SetSize(Bar:GetSize())
end
end)
-- Callback to update the actual stance bar's button artwork.
-- The bar and buttons are created later, so it can't be done on controller init.
ControllerWidget.UpdateBarArtwork = function(self)
local Bar = Module:GetWidget("Bar: Stance"):GetFrame()
if Bar then
Bar:UpdateStyle()
end
end
ControllerWidget.GetFrame = function(self)
return self.StanceWindow
end
|
while turtle.detectDown() do
turtle.refuel()
turtle.down()
end
|
local ReachedEnd = require(script.UnitDamage)
local TowerAttackParticle = require(script.Parent.Parent.TowerModule.TowerAttackModule.TowerAttackParticle)
local UnitDebuffs = require(script.Parent.UnitDebuffs)
local UnitHealth = require(script.Parent.UnitHealth)
local UnitDamage = require(script.UnitDamage)
local PhysicsService = game:GetService("PhysicsService")
function setPhysics(model,physics)
for i,v in pairs(model:GetDescendants()) do
if v:IsA("BasePart") then
PhysicsService:SetPartCollisionGroup(v,physics)
end
end
end
function setOwnerShip(unit)
for i,v in pairs(unit:GetChildren()) do
if v:IsA("BasePart") then
v:SetNetworkOwner(nil)
end
end
end
local debris = game:GetService("Debris")
function playSound(unit,sound)
if game.ServerStorage.TowerDefensePackages.Sounds[sound] then
if game.ServerStorage.TowerDefensePackages.Sounds[sound] then
local pSound = game.ServerStorage.TowerDefensePackages.Sounds[sound]:Clone()
pSound.Parent = unit.HumanoidRootPart
pSound:Play()
debris:AddItem(pSound,5)
end
end
end
local module = {}
function module:MoveToCoroutine(unit)
local goals = workspace.Ignore.Path
local atGoal = false
local destination =nil
setOwnerShip(unit)
local function moveTo()
local con2
local con3
local connection
if unit:FindFirstChild("Humanoid") then else return end
connection = unit.Humanoid.MoveToFinished:Connect(function(reached)
if not atGoal then
connection:Disconnect()
con2:Disconnect()
con3:Disconnect()
wait()
moveTo()
end
end)
con2 = unit.Location:GetAttributeChangedSignal("Backwards"):Connect(function()
if unit.Location:GetAttribute("Backwards") == true then
if unit.Location.Value ~= 0 then
connection:Disconnect()
con2:Disconnect()
con3:Disconnect()
wait()
destination = goals[tostring(unit.Location.Value-1)]
moveTo()
end
else
connection:Disconnect()
con2:Disconnect()
con3:Disconnect()
wait()
destination = goals[tostring(unit.Location.Value+1)]
moveTo()
end
end)
con3 = unit.Location:GetAttributeChangedSignal("Halt"):Connect(function()
if unit.Location:GetAttribute("Halt") == true then
unit.Location:SetAttribute("Halt",false)
connection:Disconnect()
con2:Disconnect()
con3:Disconnect()
wait()
destination = goals[tostring(unit.Location.Value)]
moveTo()
end
end)
if #goals:GetChildren() > unit.Location.Value then
if not destination then
destination = goals[tostring(unit.Location.Value)]
if goals[tostring(unit.Location.Value)]:IsA("Folder") then
destination = destination[math.random(1,#destination:GetChildren())]
end
end
if (unit.HumanoidRootPart.Position-destination.Position).Magnitude > .9+(unit.Humanoid.HipHeight) then
unit.Humanoid:MoveTo(destination.Position)
else
if unit.Location:GetAttribute("Backwards") == false then
unit.Location.Value +=1
else
if unit.Location.Value~= 0 then
unit.Location.Value-=1
end
end
if #goals:GetChildren() > unit.Location.Value then
if destination:GetAttribute("Teleport") then
local setTo = goals[tostring(unit.Location.Value)]
unit:SetPrimaryPartCFrame(setTo.CFrame+Vector3.new(0,unit.Humanoid.HipHeight,0))
end
destination = nil
con2:Disconnect()
con3:Disconnect()
connection:Disconnect()
wait()
moveTo()
else
atGoal = true
destination = nil
con2:Disconnect()
con3:Disconnect()
connection:Disconnect()
ReachedEnd:ReachedEnd(unit)
return
end
end
else
destination = nil
atGoal = true
con2:Disconnect()
con3:Disconnect()
connection:Disconnect()
ReachedEnd:ReachedEnd(unit)
return
end
end
moveTo()
end
function module:SmokeScreenCoroutine(unit)
while wait(math.random(4,23)) do
if unit and unit:FindFirstChild("HumanoidRootPart") then
TowerAttackParticle:CreateParticles(unit,unit.HumanoidRootPart.CFrame,nil,"SmokeScreen")
wait(.2)
if unit and unit:FindFirstChild("HumanoidRootPart") then
playSound(unit,"SmokeScreen")
unit:SetAttribute("Targetable",false)
for i,v in pairs(unit:GetDescendants()) do
if v:IsA("BasePart") and v.Name ~="HumanoidRootPart" then
v.Transparency = .8
end
end
end
wait(2)
if unit and unit:FindFirstChild("HumanoidRootPart") then
unit:SetAttribute("Targetable",true)
for i,v in pairs(unit:GetDescendants()) do
if v:IsA("BasePart") and v.Name~="HumanoidRootPart" then
v.Transparency = 0
end
end
end
else break
end
end
end
function module:Wraith(unit)
while wait(math.random(10,23)) do
if unit and unit:FindFirstChild("HumanoidRootPart") then
playSound(unit,"Wraith")
local debuff = Instance.new("IntValue")
debuff.Name = "Wraith"
debuff.Parent = unit.Debuffs
debris:AddItem(debuff,2)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies.Wraith.Wraith)
unit:SetAttribute("Targetable",false)
for i,v in pairs(unit:GetDescendants()) do
if v:IsA("BasePart") and v.Name ~="HumanoidRootPart" then
v.Material = Enum.Material.ForceField
elseif v:IsA("Trail") then
v.Enabled = true
end
end
wait(2)
if unit and unit:FindFirstChild("HumanoidRootPart") then
unit:SetAttribute("Targetable",true)
for i,v in pairs(unit:GetDescendants()) do
if v:IsA("BasePart") and v.Name~="HumanoidRootPart" then
v.Material = Enum.Material.Foil
elseif v:IsA("Trail") then
v.Enabled = false
end
end
end
else break
end
end
end
function module:Sprint(unit)
while wait(math.random(10,23)) do
if unit and unit:FindFirstChild("HumanoidRootPart") then
local debuff = Instance.new("IntValue")
debuff.Name = "Wraith"
debuff.Parent = unit.Debuffs
debris:AddItem(debuff,2)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies["Football Zombie"].Sprint)
unit.Head.Handle.Attachment.Core.Enabled = true
unit.Head.Handle.Attachment.Space.Enabled = true
wait(2)
if unit and unit:FindFirstChild("HumanoidRootPart") then
unit.Head.Handle.Attachment.Core.Enabled = false
unit.Head.Handle.Attachment.Space.Enabled = false
end
else break
end
end
end
function module:SetBossHP(unit)
unit.Head.EnemyDisplay.AlwaysOnTop = true
unit.Head.EnemyDisplay.EnemyName.TextColor3 = Color3.new(1,0,0)
unit.Head.EnemyDisplay.EnemyName.TextStrokeColor3 = Color3.fromRGB(0,0,0)
unit.Head.EnemyDisplay.Size = UDim2.new(5,0,.6,0)
unit.Head.EnemyDisplay.Frame.Frame.UIGradient.Color = ColorSequence.new(Color3.fromRGB(255,255,0),Color3.fromRGB(255,0,255))
end
function module:SummonUnits(unit,summonedUnit)
while unit do
wait(math.random(12,20))
if unit:FindFirstChild("Humanoid") then
local debuff = Instance.new("IntValue")
debuff.Name = "SummonBats"
debuff.Value = 1
debuff.Parent = unit.Debuffs
debris:AddItem(debuff,2)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies.Vampire.SummonBats)
for i=1,4 do
local Summon = game.ServerStorage.TowerDefensePackages.Enemies:FindFirstChild(summonedUnit):Clone()
Summon:SetPrimaryPartCFrame(unit.PrimaryPart.CFrame+Vector3.new(math.random(0,1)/10,0,math.random(0,10)/10))
Summon.Location.Value = unit.Location.Value
setPhysics(Summon,"Units")
Summon.Parent = workspace.Ignore.Enemies
setOwnerShip(Summon)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.FallingDown,false)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.PlatformStanding,false)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.Ragdoll,false)
UnitHealth:CreateUnitHealth(Summon)
local currentHealth = Summon.Humanoid.Health
Summon.Humanoid.HealthChanged:Connect(function(health)
UnitDamage:Damaged(math.abs(health),Summon,currentHealth)
end)
local Debuffs = Instance.new("Folder")
Debuffs.Name = "Debuffs"
Debuffs.Parent = Summon
Debuffs.ChildAdded:Connect(function(child) UnitDebuffs:DebuffAdded(child,Summon)end)
Debuffs.ChildRemoved:Connect(function(child) UnitDebuffs:DebuffRemoved(child,Summon)end)
local basicMove = function(Summon)
module:MoveToCoroutine(Summon)
end
local func = coroutine.create(basicMove)
coroutine.resume(func,Summon)
wait(.15)
end
else
return
end
end
end
local GuitarSoloEnemies = {
"Zombie Deliver",
"Zombie",
"Zombie Knight",
"Abomination",
"Fire Zombie",
}
function module:GuitarSolo(unit)
while unit do
wait(math.random(12,20))
if unit:FindFirstChild("Humanoid") then
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies["Rockstar Zombie"].Strum)
local sound = game.ServerStorage.TowerDefensePackages.Sounds.GuitarStrum:Clone()
sound.Parent = unit.PrimaryPart
sound:Play()
debris:AddItem(sound,5)
for i=1,math.random(2,5) do
wait(.5)
local summonedUnit = GuitarSoloEnemies[math.random(1,#GuitarSoloEnemies)]
local Summon = game.ServerStorage.TowerDefensePackages.Enemies:FindFirstChild(summonedUnit):Clone()
Summon:SetPrimaryPartCFrame(unit.PrimaryPart.CFrame+Vector3.new(math.random(-25,25)/10,0,math.random(-25,25)/10))
Summon.Location.Value = unit.Location.Value
setPhysics(Summon,"Units")
Summon.Parent = workspace.Ignore.Enemies
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(Summon.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies[summonedUnit].Idle)
setOwnerShip(Summon)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.FallingDown,false)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.PlatformStanding,false)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.Ragdoll,false)
UnitHealth:CreateUnitHealth(Summon)
local currentHealth = Summon.Humanoid.Health
Summon.Humanoid.HealthChanged:Connect(function(health)
UnitDamage:Damaged(math.abs(health),Summon,currentHealth)
end)
local Debuffs = Instance.new("Folder")
Debuffs.Name = "Debuffs"
Debuffs.Parent = Summon
Debuffs.ChildAdded:Connect(function(child) UnitDebuffs:DebuffAdded(child,Summon)end)
Debuffs.ChildRemoved:Connect(function(child) UnitDebuffs:DebuffRemoved(child,Summon)end)
local basicMove = function(Summon)
module:MoveToCoroutine(Summon)
end
local func = coroutine.create(basicMove)
coroutine.resume(func,Summon)
wait(.5)
end
else
return
end
end
end
local RadioEnemies = {
"Breacher",
"Spy",
"Soldier",
"Scout",
"Mercenary",
"Vanguard"
}
function module:RadioIn(unit)
while unit do
wait(math.random(12,20))
if unit:FindFirstChild("Humanoid") then
local summonedUnit = RadioEnemies[math.random(1,#RadioEnemies)]
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies.Commander.Radio)
for i=1,math.random(2,5) do
wait(.5)
local Summon = game.ServerStorage.TowerDefensePackages.Enemies:FindFirstChild(summonedUnit):Clone()
Summon:SetPrimaryPartCFrame(unit.PrimaryPart.CFrame+Vector3.new(math.random(-25,25)/10,0,math.random(-25,25)/10))
Summon.Location.Value = unit.Location.Value
setPhysics(Summon,"Units")
Summon.Parent = workspace.Ignore.Enemies
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(Summon.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies[summonedUnit].Idle)
setOwnerShip(Summon)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.FallingDown,false)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.PlatformStanding,false)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.Ragdoll,false)
UnitHealth:CreateUnitHealth(Summon)
local currentHealth = Summon.Humanoid.Health
Summon.Humanoid.HealthChanged:Connect(function(health)
UnitDamage:Damaged(math.abs(health),Summon,currentHealth)
end)
local Debuffs = Instance.new("Folder")
Debuffs.Name = "Debuffs"
Debuffs.Parent = Summon
Debuffs.ChildAdded:Connect(function(child) UnitDebuffs:DebuffAdded(child,Summon)end)
Debuffs.ChildRemoved:Connect(function(child) UnitDebuffs:DebuffRemoved(child,Summon)end)
local basicMove = function(Summon)
module:MoveToCoroutine(Summon)
end
local func = coroutine.create(basicMove)
coroutine.resume(func,Summon)
wait(.5)
end
else
return
end
end
end
function module:BlockImmune(unit)
while unit do
wait(math.random(5,20))
if unit:FindFirstChild("Humanoid") then
local debuff = Instance.new("IntValue")
unit:SetAttribute("Targetable",false)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Immune:FireAllClients(unit,3)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies["Crystal Commander"].Protect)
wait(3)
if unit then
if unit:FindFirstChild("Humanoid") then
unit:SetAttribute("Targetable",true)
end
end
else
return
end
end
end
function module:CrystalHeal(unit)
while unit do
wait(math.random(10,25))
if unit:FindFirstChild("Humanoid") then
local debuff = Instance.new("IntValue")
unit:SetAttribute("Targetable",false)
debuff.Name = "Crystallize"
debuff.Value = 1
debuff.Parent = unit.Debuffs
debris:AddItem(debuff,.8)
local effect = game.ServerStorage.TowerDefensePackages.Effects.CrystalQueen.Attachment:Clone()
effect.Parent = unit.UpperTorso
effect.WorldOrientation = Vector3.new(0,unit.HumanoidRootPart.Orientation.Y,0)
effect.Position = Vector3.new(0,0,-.7)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies["Crystal Queen"].Heal)
for i=1,20 do
unit.Humanoid.Health+=77
wait(.25)
if math.modf(i/5) == 0 then
for i,v in pairs(effect:GetChildren()) do
v.Enabled = true
end
end
if math.modf((i-1)/5) == 0 then
for i,v in pairs(effect:GetChildren()) do
v.Enabled = false
end
end
end
effect:Destroy()
if unit then
if unit:FindFirstChild("Humanoid") then
unit:SetAttribute("Targetable",true)
end
end
else
return
end
end
end
function module:Crystallize(unit)
while unit do
wait(math.random(10,25))
if unit:FindFirstChild("Humanoid") then
local debuff = Instance.new("IntValue")
unit:SetAttribute("Targetable",false)
debuff.Name = "Crystallize"
debuff.Value = 1
debuff.Parent = unit.Debuffs
debris:AddItem(debuff,7)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies["Crystal King"].Crystallize)
local crystal = game.ServerStorage.TowerDefensePackages.Effects.Crystal:Clone()
crystal.CFrame = unit.PrimaryPart.CFrame
crystal.Parent = workspace.Ignore
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Crystallize:FireAllClients(crystal)
debris:AddItem(crystal,7)
for i=1,5 do
wait(1)
if unit then
if unit:FindFirstChild("Humanoid") then
unit.Humanoid.Health += unit.Humanoid.MaxHealth*.05
end
end
end
wait(2)
if unit then
if unit:FindFirstChild("Humanoid") then
unit:SetAttribute("Targetable",true)
end
end
else
return
end
end
end
function module:CreateIcePortal(unit)
while unit do
wait(25)
if unit:FindFirstChild("Humanoid") then
local summonedUnit = game.ServerStorage.TowerDefensePackages.Enemies["Ice Angel"]
local portal = game.ServerStorage.TowerDefensePackages.Effects.IceKingSummon:Clone()
portal.CFrame = unit.HumanoidRootPart.CFrame*CFrame.new(0,3,0) *CFrame.Angles(0,math.rad(90),0)
portal.Parent = workspace.Ignore
debris:AddItem(portal,5)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies.Commander.Radio)
for i=1,5 do
wait(.5)
local Summon = summonedUnit:Clone()
Summon:SetPrimaryPartCFrame(portal.CFrame*CFrame.Angles(0,-math.rad(90),0))
Summon.Location.Value = unit.Location.Value
setPhysics(Summon,"Units")
Summon.Parent = workspace.Ignore.Enemies
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(Summon.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies[Summon.Name].Idle)
setOwnerShip(Summon)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.FallingDown,false)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.PlatformStanding,false)
Summon.Humanoid:SetStateEnabled(Enum.HumanoidStateType.Ragdoll,false)
UnitHealth:CreateUnitHealth(Summon)
local currentHealth = Summon.Humanoid.Health
Summon.Humanoid.HealthChanged:Connect(function(health)
UnitDamage:Damaged(math.abs(health),Summon,currentHealth)
end)
local Debuffs = Instance.new("Folder")
Debuffs.Name = "Debuffs"
Debuffs.Parent = Summon
Debuffs.ChildAdded:Connect(function(child) UnitDebuffs:DebuffAdded(child,Summon)end)
Debuffs.ChildRemoved:Connect(function(child) UnitDebuffs:DebuffRemoved(child,Summon)end)
local basicMove = function(Summon)
module:MoveToCoroutine(Summon)
end
local func = coroutine.create(basicMove)
coroutine.resume(func,Summon)
wait(.5)
end
else
return
end
end
end
function module:FreezeAoe(unit)
while unit do
wait(18)
if unit:FindFirstChild("Humanoid") then
local debuff = Instance.new("IntValue")
debuff.Name = "Crystallize"
debuff.Value = 2
debuff.Parent = unit.Debuffs
debris:AddItem(debuff,2)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies["Ice King"].Freeze)
wait(1.5)
if unit then
if unit:FindFirstChild("HumanoidRootPart") then
local sound = game.ServerStorage.TowerDefensePackages.Sounds.Freeze:Clone()
sound.Parent = unit.HumanoidRootPart
sound:Play()
wait(.5)
if unit then
for i,v in pairs(workspace.Ignore.Towers:GetChildren()) do
local dist = (v.Hitbox.Position - unit.HumanoidRootPart.Position).magnitude
if dist <= 20 then
local tower_Debuff = Instance.new("IntValue")
tower_Debuff.Name = "Frozen"
tower_Debuff.Value = 4
tower_Debuff.Parent = v.Stats
local frozenSound = game.ServerStorage.TowerDefensePackages.Sounds.Frozen:Clone()
frozenSound.Parent = v.Hitbox
frozenSound:Play()
debris:AddItem(frozenSound,2)
end
end
end
end
end
else
return
end
end
end
function module:FreezeRay(unit)
while unit do
wait(math.random(5,10))
if unit:FindFirstChild("Humanoid") then
if unit then
if unit:FindFirstChild("HumanoidRootPart") then
local unitsToFreeze = {}
if unit then
for i,v in pairs(workspace.Ignore.Towers:GetChildren()) do
local dist = (v.Hitbox.Position - unit.HumanoidRootPart.Position).magnitude
if dist <= 20 then
table.insert(unitsToFreeze,v)
end
end
end
if #unitsToFreeze > 0 then
local unitFrozen = unitsToFreeze[math.random(1,#unitsToFreeze)]
if unitFrozen:FindFirstChild("Hitbox") then
local debuff = Instance.new("IntValue")
debuff.Name = "Crystallize"
debuff.Value = 1
debuff.Parent = unit.Debuffs
debris:AddItem(debuff,1)
local sound = game.ServerStorage.TowerDefensePackages.Sounds.FreezeRay:Clone()
sound.Parent = unit.HumanoidRootPart
sound:Play()
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Animate:FireAllClients(unit.Humanoid,game.ReplicatedStorage.TowerDefenseLocalPackages.Animations.Enemies["Lab Scientist"].Shoot)
game.ReplicatedStorage.TowerDefenseLocalPackages.Events.Bullet:FireAllClients(unit.RightHand.Handle.Attachment,unitFrozen.Hitbox.Position,nil,"IceRay")
unit:SetPrimaryPartCFrame(CFrame.new(unit.PrimaryPart.Position, Vector3.new(unitFrozen.PrimaryPart.Position.X,unitFrozen.PrimaryPart.Position.Y,unitFrozen.PrimaryPart.Position.Z)))
local frozenSound = game.ServerStorage.TowerDefensePackages.Sounds.Frozen:Clone()
frozenSound.Parent = unitFrozen.Hitbox
frozenSound:Play()
debris:AddItem(frozenSound,2)
local tower_Debuff = Instance.new("IntValue")
tower_Debuff.Name = "Frozen"
tower_Debuff.Value = 4
tower_Debuff.Parent = unitFrozen.Stats
end
end
end
end
else
return
end
end
end
return module
|
-----------------------------------------
-- ID: 5936
-- Mog Missile
-----------------------------------------
function onItemCheck(target)
return 0
end
function onItemUse(target)
end
|
local dbg = include("debugger")
-- namespace AutoscalerPlayer
AutoscalerPlayer = {}
AutoscalerPlayer.testValue = 0
function AutoscalerPlayer.invokedFunction(invokedFunctionArg1)
dbg() -- always break
end
function AutoscalerPlayer.invokedFunctionConditionalDebug(invokedFunctionArg2)
local see, me, printed = {3, 4, 5}, {6, 7, 8}, {"Avorion", "is", "awesome"}
dbg(invokedFunctionArg2.testValue < 75) -- breakpoint if false
end
function AutoscalerPlayer.getUpdateInterval()
return 10
end
function AutoscalerPlayer.secure()
local save = {}
save.testValue = AutoscalerPlayer.testValue
Player():sendChatMessage("", 1, "Saving test value.")
AutoscalerPlayer.invokedFunction(save)
AutoscalerPlayer.invokedFunctionConditionalDebug(save)
return save
end
function AutoscalerPlayer.restore(values)
AutoscalerPlayer.testValue = values.testValue
end
function AutoscalerPlayer.updateServer(timeStep)
AutoscalerPlayer.testValue = AutoscalerPlayer.testValue + 1
end
return AutoscalerPlayer
|
local project_workbench = {}
local utils = require('workbench.utils')
-- create a global bufnr
project_workbench_bufnr = vim.api.nvim_create_buf(false, true)
project_workbench_initialized = false
function project_workbench.filepath()
return utils.workbench_path() .. "/" .. "workbench.md"
end
function project_workbench.initialize()
--Get the current UI
ui = vim.api.nvim_list_uis()[1]
local width = round(ui.width * 0.5)
local height = round(ui.height * 0.5)
project_workbench_initialized = true
local win_id = vim.api.nvim_open_win(project_workbench_bufnr, true, utils.window_config(width, height))
open_file_cmd = "e " .. project_workbench.filepath()
vim.api.nvim_command(open_file_cmd)
end
function project_workbench.toggle()
-- early return if not a git repo
if utils.is_git_repo() ~= "true" then
return vim.api.nvim_err_writeln("Sorry, Workbench only works in a Git Repo")
end
if utils.directory_not_exist(utils.workbench_path()) then
utils.create_directory()
end
-- override ui every time toggle is called
ui = vim.api.nvim_list_uis()[1]
local buf_hidden = 0
local buf_info = vim.api.nvim_call_function('getbufinfo', {project_workbench.filepath()})[1]
if buf_info then
buf_hidden = buf_info.hidden
end
local current_bufnr = vim.api.nvim_win_get_buf(0)
if not project_workbench_initialized then
project_workbench.initialize()
elseif current_bufnr == project_workbench_bufnr then
utils.hide_workbench()
elseif buf_hidden == 0 and buf_info.windows[1] then
vim.api.nvim_set_current_win(buf_info.windows[1])
else
utils.show_workbench(project_workbench_bufnr)
end
end
return project_workbench
|
nut.flag.add("p", "Physgun access.", function(client, isGiven)
if (isGiven) then
client:Give("weapon_physgun")
client:SelectWeapon("weapon_physgun")
else
client:StripWeapon("weapon_physgun")
end
end)
nut.flag.add("t", "Access to the toolgun", function(client, isGiven)
if (isGiven) then
client:Give("gmod_tool")
client:SelectWeapon("gmod_tool")
else
client:StripWeapon("gmod_tool")
end
end)
nut.flag.add("M", "Access to apothecary.")
nut.flag.add("A", "Access to Advert commands")
nut.flag.add("G", "Access to GM commands")
nut.flag.add("V", "Access to HQ commands")
|
require "underscore/underscore"
function change_ui_state(self, new_state_name)
local old_state, new_state
old_state_name = self.current_state_name
old_state = self.state_graph[old_state_name]
new_state = self.state_graph[new_state_name]
if old_state == nil or old_state.to == nil or not _.include(old_state.to, new_state_name) then error("Invalid state change") end
for n,m in pairs(old_state) do
love[n] = nil
end
-- Note: This does incorrectly copy to, to_* and from_* into love as weird broken functions.
for n,m in pairs(new_state) do
love[n] = function(...)
new_state[n](new_state,...)
end
end
(old_state['to_'..new_state_name] or _.identity)(old_state)
self.current_state_name = new_state_name;
(new_state['from_'..old_state_name] or _.identity)(new_state)
end
-- "constructor"
function init_ui_graph(state_graph, first_state_name)
local ui_state_manager = {
state_graph = state_graph,
change_ui_state = change_ui_state,
current_state_name = first_state_name
}
local new_state = state_graph[first_state_name]
-- Install state into 'love'...
for n,m in pairs(new_state) do
love[n] = function(...)
new_state[n](new_state,...)
end
end
-- Install a change_ui_state method in each state for convenience...
for n,m in pairs(state_graph) do
function m:change_ui_state(s)
ui_state_manager:change_ui_state(s)
end
end
return ui_state_manager
end
-- A trio of functions for building dazzlingly bad UIs right in the state graph literal.
function show_text(text, height)
love.graphics.setColor(unpack(SETTINGS and SETTINGS.foreground or {255,100,100,255}))
love.graphics.printf(text, 0, height, love.graphics.getWidth(), "center")
end
function state_thunk(s)
return function(self)
self:change_ui_state(s)
end
end
function keymap_method(map)
return function(s, key, unicode)
(map[key] or _.identity)(s)
end
end
|
-- creates blue box, once its clicked, plays sounds and destroys box
b = BinooAPI
id = "bluebox"
b:CreateBox(id,1,1,1,2,2,2)
b:SetColor(id,0,0,255)
b:MoveObject(id,-5,0,-5)
b:AddBoxCollider(id, 0, 0, 0, 1,1,1)
b:AddGazeTarget(id)
b:AddEvent(id,"CLICK","MyClick",100)
b:ShowStaticMessage("Tap the box to continue")
function MyClick(sender,params)
b:PlaySound("tadaa_trumpet")
b:Destroy(tostring(sender))
b:HideStaticMessage()
end
|
--[[
--MIT License
--
--Copyright (c) 2019 manilarome
--Copyright (c) 2020 Tom Meyers
--
--Permission is hereby granted, free of charge, to any person obtaining a copy
--of this software and associated documentation files (the "Software"), to deal
--in the Software without restriction, including without limitation the rights
--to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
--copies of the Software, and to permit persons to whom the Software is
--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 Software.
--
--THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
--SOFTWARE.
]]
-- The one that generates notification in right-panel
--
--
local naughty = require("naughty")
local wibox = require("wibox")
local gears = require("gears")
local dpi = require("beautiful").xresources.apply_dpi
local theme = require("theme.icons.dark-light")
local lgi = require("lgi")
local Pango = lgi.Pango
local beautiful = require("beautiful")
local PATH_TO_ICONS = "/etc/xdg/tde/widget/notification-center/icons/"
local notif_layout = wibox.layout.fixed.vertical(reverse)
notif_layout.spacing = dpi(5)
-- useful variable to check the notification's content
_G.notification_firstime = true
local notif_icon = function(ico_image)
local noti_icon =
wibox.widget {
{
id = "icon",
resize = true,
forced_height = dpi(45),
forced_width = dpi(45),
widget = wibox.widget.imagebox
},
layout = wibox.layout.fixed.horizontal
}
noti_icon.icon:set_image(ico_image)
return noti_icon
end
local notif_title = function(title)
return wibox.widget {
markup = gears.string.xml_escape(title),
font = "SFNS Display Bold 12",
align = "center",
valign = "center",
widget = wibox.widget.textbox
}
end
local notif_message = function(msg)
return wibox.widget {
markup = msg,
font = "SFNS Display Regular 12",
align = "center",
valign = "center",
widget = wibox.widget.textbox
}
end
-- Empty content
local empty_title = i18n.translate("Spooky...")
local empty_message = i18n.translate("There's nothing in here... Come back later.")
-- The function that generates notifications in right-panel
local function notif_generate(title, message, icon, noti)
-- make sure the message is valid, otherwise we escape it
local attr, _ = Pango.parse_markup(message, -1, 0)
if not attr then
message = gears.string.xml_escape(message)
end
-- naughty.list.actions
local notif_actions =
wibox.widget {
notification = noti,
base_layout = wibox.widget {
spacing = dpi(5),
layout = wibox.layout.flex.vertical
},
widget_template = {
{
{
{
id = "text_role",
font = "SFNS Display Regular 10",
widget = wibox.widget.textbox
},
widget = wibox.container.place
},
bg = beautiful.bg_modal,
shape = gears.shape.rounded_rect,
forced_height = 30,
widget = wibox.container.background
},
margins = 4,
widget = wibox.container.margin
},
widget = naughty.list.actions
}
-- The layout of notification to be generated
local notif_template =
wibox.widget {
id = "notif_template",
expand = "none",
layout = wibox.layout.fixed.vertical,
{
{
expand = "none",
layout = wibox.layout.align.horizontal,
{
nil,
layout = wibox.layout.fixed.horizontal
},
{
wibox.container.margin(notif_title(title), dpi(0), dpi(0), dpi(4), dpi(4)),
layout = wibox.layout.fixed.horizontal
}
-- {
-- gen_button(notif_del_button),
-- layout = wibox.layout.fixed.horizontal,
-- },
},
bg = beautiful.bg_modal_title,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(cr, width, height, true, true, false, false, 6)
end,
widget = wibox.container.background
},
{
{
expand = "none",
layout = wibox.layout.fixed.horizontal,
{
wibox.widget {
notif_icon(icon),
margins = dpi(4),
widget = wibox.container.margin
},
margins = dpi(5),
widget = wibox.container.margin
},
{
wibox.widget {
notif_message(message),
margins = dpi(4),
widget = wibox.container.margin
},
layout = wibox.layout.flex.horizontal
}
},
bg = beautiful.bg_modal,
widget = wibox.container.background
},
{
wibox.widget {
{
notif_actions,
margins = dpi(4),
widget = wibox.container.margin
},
bg = beautiful.bg_modal,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(cr, width, height, false, false, true, true, 6)
end,
widget = wibox.container.background
},
layout = wibox.layout.flex.horizontal
}
}
-- Delete notification if naughty.list.actions was pressed
notif_actions:connect_signal(
"button::press",
function(_, _, _, _)
-- Don't let the user make the notification center null
if #notif_layout.children == 1 then
notif_layout:reset(notif_layout)
_G.notification_firstime = true
notif_layout:insert(1, notif_generate(empty_title, empty_message, theme(PATH_TO_ICONS .. "boo" .. ".svg")))
else
notif_layout:remove_widgets(notif_template, true)
end
end
)
-- Delete notification if the generated notification was pressed
notif_template:connect_signal(
"button::press",
function(_, _, _, _)
-- Don't let the user make the notification center null
if #notif_layout.children == 1 then
notif_layout:reset(notif_layout)
_G.notification_firstime = true
notif_layout:insert(1, notif_generate(empty_title, empty_message, theme(PATH_TO_ICONS .. "boo" .. ".svg")))
else
notif_layout:remove_widgets(notif_template, true)
end
end
)
--return template to generate
return notif_template
end
-- add a message to an empty notification center
local function add_empty()
notif_layout:insert(1, notif_generate(empty_title, empty_message, theme(PATH_TO_ICONS .. "boo" .. ".svg")))
end
-- Add empty message on startup
add_empty()
-- Clear all. Will be called in right-panel
local function clear_all()
-- Clear all notification
notif_layout:reset(notif_layout)
add_empty()
end
_G.notification_clear_all = clear_all
-- Check signal
naughty.connect_signal(
"request::display",
function(n)
if _G.notification_firstime then
-- Delete empty message if the 1st notification is generated
notif_layout:remove(1)
_G.notification_firstime = false
end
-- Check and set icon to the notification message in panel
-- Then generate a widget based on naughty.notify data
if n.icon == nil then
-- if naughty sends a signal without an icon then use this instead
notif_layout:insert(1, notif_generate(n.title, n.message, theme(PATH_TO_ICONS .. "new-notif" .. ".svg"), n))
else
-- Use the notification's icon
notif_layout:insert(1, notif_generate(n.title, n.message, n.icon, n))
end
end
)
-- Return notif_layout to right-panel.lua to display it
return notif_layout
|
local kiwi = require("kiwi")
local ffi = require("ffi")
ffi.cdef[[
typedef long time_t;
typedef struct timeval {
time_t tv_sec;
time_t tv_usec;
} timeval;
int gettimeofday(struct timeval* t, void* tzp);
]]
local function now()
local t = ffi.new("timeval")
ffi.C.gettimeofday(t, nil)
return tonumber(t.tv_sec) + tonumber(t.tv_usec) / 1e6
end
--------------------------------------------------------------------------------
-- full functionality test
local script = [[
vars x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20
x1 >= 1
x2 >= 1 + x1
x3 >= 1 + x2
x4 >= 1 + x3
x5 >= 1 + x4
x6 >= 1 + x5
x7 >= 1 + x6
x8 >= 1 + x7
x9 >= 1 + x8
x10 >= 1 + x9
x11 >= 1 + x10
x12 >= 1 + x11
x13 >= 1 + x12
x14 >= 1 + x13
x15 >= 1 + x14
x16 >= 1 + x15
x17 >= 1 + x16
x18 >= 1 + x17
x19 >= 1 + x18
x20 <= 1 + x19
]]
function string.startswith(str1, str2)
return string.sub(str1, 1, string.len(str2)) == str2
end
local vars = {}
local cns = {}
local solver = kiwi.solver()
-- parse 'script'
for line in script:gmatch("([^\n]+)") do
if line:startswith("vars ") then
local parts = {}
line:gsub("([^ \t\f]+)", function (c) parts[#parts+1] = c end)
for i = 2, #parts, 1 do
local var = kiwi.variable(parts[i])
vars[#vars+1] = var
vars[parts[i]] = var
end
else
cns[#cns+1] = kiwi.parse_constraint(vars, line)
end
end
for i, cn in ipairs(cns) do
solver:add_constraint(cn)
end
solver:add_edit_variable(vars.x1, kiwi.strength.medium)
n = 10000
print(('starting benchmark (%d iterations)'):format(n))
local start = now()
local j = 1
for i = 1, n, 1 do
solver:suggest_value(vars.x1, i)
solver:update_variables()
end
local stop = now()
print(('finished in %f seconds'):format(stop-start))
|
--[[
Normalized Lua API for Lua 5.1, 5.2 & 5.3
Copyright (C) 2014-2018 std.normalize authors
]]
--[[--
Depending on whether `std.strict` is installed, and the value of
`std._debug.strict`, return a function for setting up a strict lexical
environment for the caller.
@module std.normalize._strict
]]
local setfenv = rawget(_G, 'setfenv') or function() end
local _ENV = {
_debug = require 'std._debug',
pcall = pcall,
require = require,
setmetatable = setmetatable,
}
setfenv(1, _ENV)
--[[ =============== ]]--
--[[ Implementation. ]]--
--[[ =============== ]]--
-- If strict mode is required, use 'std.strict' if we have it.
local strict
if _debug.strict then
-- `require 'std.strict'` will get the old stdlib implementation of
-- strict, which doesn't support environment tables :(
ok, strict = pcall(require, 'std.strict.init')
if not ok then
strict = false
end
end
--[[ ================= ]]--
--[[ Public Interface. ]]--
--[[ ================= ]]--
return setmetatable({
--- Set a module environment, using std.strict if available.
--
-- Either 'std.strict' when available, otherwise a(Lua 5.1 compatible)
-- function to set the specified module environment.
-- @function strict
-- @tparam table env module environment table
-- @treturn table *env*, which must be assigned to `_ENV`
-- @usage
-- local _ENV = require 'std.normalize._strict'.strict {}
strict = strict or function(env)
return env
end,
}, {
--- Module Metamethods
-- @section modulemetamethods
--- Set a module environment, using std.strict if available.
-- @function strict:__call
-- @tparam table env module environment table
-- @tparam[opt=1] int level stack level for `setfenv`, 1 means set
-- caller's environment
-- @treturn table *env*, which must be assigned to `_ENV`
-- @usage
-- local _ENV = require 'std.normalize._strict' {}
__call = function(self, env, level)
env = self.strict(env)
setfenv(1+(level or 1), env)
return env
end,
})
|
add_rules("mode.debug", "mode.release")
-- set cross-compliation platform
set_plat("cross")
set_arch("arm")
-- add library packages
add_requires("zlib", "libplist", {system = false})
-- add toolchains package
add_requires("muslcc")
-- set global toolchains for target and packages
set_toolchains("@muslcc")
target("test")
set_kind("binary")
add_files("src/*.c")
add_packages("zlib", "libplist")
|
require 'torch'
require 'nn'
require 'LSTM'
local gradcheck = require 'util.gradcheck'
local tests = {}
local tester = torch.Tester()
local function check_size(x, dims)
tester:assert(x:dim() == #dims)
for i, d in ipairs(dims) do
tester:assert(x:size(i) == d)
end
end
function tests.testForward()
local N, T, D, H = 3, 4, 5, 6
local h0 = torch.randn(N, H)
local c0 = torch.randn(N, H)
local x = torch.randn(N, T, D)
local lstm = nn.LSTM(D, H)
local h = lstm:forward{c0, h0, x}
-- Do a naive forward pass
local naive_h = torch.Tensor(N, T, H)
local naive_c = torch.Tensor(N, T, H)
-- Unpack weight, bias for each gate
local Wxi = lstm.weight[{{1, D}, {1, H}}]
local Wxf = lstm.weight[{{1, D}, {H + 1, 2 * H}}]
local Wxo = lstm.weight[{{1, D}, {2 * H + 1, 3 * H}}]
local Wxg = lstm.weight[{{1, D}, {3 * H + 1, 4 * H}}]
local Whi = lstm.weight[{{D + 1, D + H}, {1, H}}]
local Whf = lstm.weight[{{D + 1, D + H}, {H + 1, 2 * H}}]
local Who = lstm.weight[{{D + 1, D + H}, {2 * H + 1, 3 * H}}]
local Whg = lstm.weight[{{D + 1, D + H}, {3 * H + 1, 4 * H}}]
local bi = lstm.bias[{{1, H}}]:view(1, H):expand(N, H)
local bf = lstm.bias[{{H + 1, 2 * H}}]:view(1, H):expand(N, H)
local bo = lstm.bias[{{2 * H + 1, 3 * H}}]:view(1, H):expand(N, H)
local bg = lstm.bias[{{3 * H + 1, 4 * H}}]:view(1, H):expand(N, H)
local prev_h, prev_c = h0:clone(), c0:clone()
for t = 1, T do
local xt = x[{{}, t}]
local i = torch.sigmoid(torch.mm(xt, Wxi) + torch.mm(prev_h, Whi) + bi)
local f = torch.sigmoid(torch.mm(xt, Wxf) + torch.mm(prev_h, Whf) + bf)
local o = torch.sigmoid(torch.mm(xt, Wxo) + torch.mm(prev_h, Who) + bo)
local g = torch.tanh(torch.mm(xt, Wxg) + torch.mm(prev_h, Whg) + bg)
local next_c = torch.cmul(prev_c, f) + torch.cmul(i, g)
local next_h = torch.cmul(o, torch.tanh(next_c))
naive_h[{{}, t}] = next_h
naive_c[{{}, t}] = next_c
prev_h, prev_c = next_h, next_c
end
tester:assertTensorEq(naive_h, h, 1e-10)
end
function tests.gradcheck()
local N, T, D, H = 2, 3, 4, 5
local x = torch.randn(N, T, D)
local h0 = torch.randn(N, H)
local c0 = torch.randn(N, H)
local lstm = nn.LSTM(D, H)
local h = lstm:forward{c0, h0, x}
local dh = torch.randn(#h)
lstm:zeroGradParameters()
local dc0, dh0, dx = unpack(lstm:backward({c0, h0, x}, dh))
local dw = lstm.gradWeight:clone()
local db = lstm.gradBias:clone()
local function fx(x) return lstm:forward{c0, h0, x} end
local function fh0(h0) return lstm:forward{c0, h0, x} end
local function fc0(c0) return lstm:forward{c0, h0, x} end
local function fw(w)
local old_w = lstm.weight
lstm.weight = w
local out = lstm:forward{c0, h0, x}
lstm.weight = old_w
return out
end
local function fb(b)
local old_b = lstm.bias
lstm.bias = b
local out = lstm:forward{c0, h0, x}
lstm.bias = old_b
return out
end
local dx_num = gradcheck.numeric_gradient(fx, x, dh)
local dh0_num = gradcheck.numeric_gradient(fh0, h0, dh)
local dc0_num = gradcheck.numeric_gradient(fc0, c0, dh)
local dw_num = gradcheck.numeric_gradient(fw, lstm.weight, dh)
local db_num = gradcheck.numeric_gradient(fb, lstm.bias, dh)
local dx_error = gradcheck.relative_error(dx_num, dx)
local dh0_error = gradcheck.relative_error(dh0_num, dh0)
local dc0_error = gradcheck.relative_error(dc0_num, dc0)
local dw_error = gradcheck.relative_error(dw_num, dw)
local db_error = gradcheck.relative_error(db_num, db)
tester:assertle(dh0_error, 1e-4)
tester:assertle(dc0_error, 1e-5)
tester:assertle(dx_error, 1e-5)
tester:assertle(dw_error, 1e-4)
tester:assertle(db_error, 1e-5)
end
-- Make sure that everything works correctly when we don't pass an initial cell
-- state; in this case we do pass an initial hidden state and an input sequence
function tests.noCellTest()
local N, T, D, H = 4, 5, 6, 7
local lstm = nn.LSTM(D, H)
for t = 1, 3 do
local x = torch.randn(N, T, D)
local h0 = torch.randn(N, H)
local dout = torch.randn(N, T, H)
local out = lstm:forward{h0, x}
local din = lstm:backward({h0, x}, dout)
tester:assert(torch.type(din) == 'table')
tester:assert(#din == 2)
check_size(din[1], {N, H})
check_size(din[2], {N, T, D})
-- Make sure the initial cell state got reset to zero
tester:assertTensorEq(lstm.c0, torch.zeros(N, H), 0)
end
end
-- Make sure that everything works when we don't pass initial hidden or initial
-- cell state; in this case we only pass input sequence of vectors
function tests.noHiddenTest()
local N, T, D, H = 4, 5, 6, 7
local lstm = nn.LSTM(D, H)
for t = 1, 3 do
local x = torch.randn(N, T, D)
local dout = torch.randn(N, T, H)
local out = lstm:forward(x)
local din = lstm:backward(x, dout)
tester:assert(torch.isTensor(din))
check_size(din, {N, T, D})
-- Make sure the initial cell state and initial hidden state are zero
tester:assertTensorEq(lstm.c0, torch.zeros(N, H), 0)
tester:assertTensorEq(lstm.h0, torch.zeros(N, H), 0)
end
end
function tests.rememberStatesTest()
local N, T, D, H = 5, 6, 7, 8
local lstm = nn.LSTM(D, H)
lstm.remember_states = true
local final_h, final_c = nil, nil
for t = 1, 4 do
local x = torch.randn(N, T, D)
local dout = torch.randn(N, T, H)
local out = lstm:forward(x)
local din = lstm:backward(x, dout)
if t == 1 then
tester:assertTensorEq(lstm.c0, torch.zeros(N, H), 0)
tester:assertTensorEq(lstm.h0, torch.zeros(N, H), 0)
elseif t > 1 then
tester:assertTensorEq(lstm.c0, final_c, 0)
tester:assertTensorEq(lstm.h0, final_h, 0)
end
final_c = lstm.cell[{{}, T}]:clone()
final_h = out[{{}, T}]:clone()
end
-- Initial states should reset to zero after we call resetStates
lstm:resetStates()
local x = torch.randn(N, T, D)
local dout = torch.randn(N, T, H)
lstm:forward(x)
lstm:backward(x, dout)
tester:assertTensorEq(lstm.c0, torch.zeros(N, H), 0)
tester:assertTensorEq(lstm.h0, torch.zeros(N, H), 0)
end
tester:add(tests)
tester:run()
|
-- --------------------
-- TellMeWhen
-- Originally by Nephthys of Hyjal <lieandswell@yahoo.com>
-- Other contributions by:
-- Sweetmms of Blackrock, Oozebull of Twisting Nether, Oodyboo of Mug'thol,
-- Banjankri of Blackrock, Predeter of Proudmoore, Xenyr of Aszune
-- Currently maintained by
-- Cybeloras of Aerie Peak
-- --------------------
if not TMW then return end
local TMW = TMW
local L = TMW.L
local print = TMW.print
TMW.CONST.STATE.DEFAULT_STACKSFAILED = 101
local STATE = TMW.CONST.STATE.DEFAULT_STACKSFAILED
local floor = floor
local Hook = TMW.Classes.IconDataProcessorHook:New("STATE_STACKREQ", "STACK")
Hook:RegisterConfigPanel_XMLTemplate(225, "TellMeWhen_StackRequirements")
Hook:RegisterIconDefaults{
StackMin = 0,
StackMax = 0,
StackMinEnabled = false,
StackMaxEnabled = false,
}
TMW:RegisterUpgrade(80013, {
icon = function(self, ics)
ics.States[STATE].Alpha = ics.StackAlpha or 0
ics.StackAlpha = nil
end,
})
TMW:RegisterUpgrade(60000, {
icon = function(self, ics)
ics.StackMin = floor(tonumber(ics.StackMin)) or 0
ics.StackMax = floor(tonumber(ics.StackMax)) or 0
end,
})
TMW:RegisterUpgrade(23000, {
icon = function(self, ics)
if ics.StackMin ~= TMW.Icon_Defaults.StackMin then
ics.StackMinEnabled = true
end
if ics.StackMax ~= TMW.Icon_Defaults.StackMax then
ics.StackMaxEnabled = true
end
end,
})
TMW:RegisterUpgrade(60010, {
icon = function(self, ics)
ics.StackAlpha = ics.ConditionAlpha
end,
})
-- Create an IconDataProcessor that will store the result of the stack test
local Processor = TMW.Classes.IconDataProcessor:New("STATE_STACKSFAILED", "state_stackFailed")
Processor.dontInherit = true
Processor:RegisterAsStateArbitrator(30, Hook, false, function(icon)
local ics = icon:GetSettings()
if not ics.StackMinEnabled and not ics.StackMaxEnabled then
return nil
end
local text = ""
if ics.StackMinEnabled then
text = L["STACKS"] .. " < " .. ics.StackMin
end
if ics.StackMaxEnabled then
if ics.StackMinEnabled then
text = text .. " " .. L["CONDITIONPANEL_OR"]:lower() .. " "
end
text = text .. L["STACKS"] .. " > " .. ics.StackMax
end
return {
[STATE] = { text = text, tooltipText = L["STACKALPHA_DESC"]},
}
end)
Hook:DeclareUpValue("STATE_DEFAULT_STACKSFAILED", STATE)
Hook:RegisterCompileFunctionSegmentHook("post", function(Processor, t)
-- GLOBALS: stack
t[#t+1] = [[
local state_stackFailed = nil
if
stack and ((icon.StackMinEnabled and icon.StackMin > stack) or (icon.StackMaxEnabled and stack > icon.StackMax))
then
state_stackFailed = icon.States[STATE_DEFAULT_STACKSFAILED]
end
if attributes.state_stackFailed ~= state_stackFailed then
icon:SetInfo_INTERNAL("state_stackFailed", state_stackFailed)
doFireIconUpdated = true
end
--]]
end)
|
function filter_tags_dates(keyvalues, nokeys)
filter = 0
tagcount = 0
if nokeys == 0 then
filter = 1
return filter, keyvalues
end
start_date_int = "-Infinity"
end_date_int = "Infinity"
if (keyvalues["start_date"] ~= nil ) or (keyvalues["end_date"] ~= nil ) then
keyvalues["start_date_int"] = start_date_int
keyvalues["end_date_int"] = end_date_int
end
if (keyvalues["start_date"] ~= nil ) then
year,month,day = nil
year = string.match(keyvalues["start_date"], "^(-?%d+%d%d%d)")
if (year ~= nil) then
y, month = string.match(keyvalues["start_date"], "^(-?%d+%d%d%d)-(%d%d)")
if (month == nil) then
month = "00"
day = "00"
else
y, m, day = string.match(keyvalues["start_date"], "^(-?%d+%d%d%d)-(%d%d)-(%d%d)")
if (day == nil) then
day = "00"
end
end
year = string.sub(year, 0, 4)
month = string.sub(month, 0, 2)
day = string.sub(day, 0, 2)
start_date_int = year..month..day
keyvalues["start_date_int"] = start_date_int
else
keyvalues["start_date_int"] = "-Infinity"
end
end
if (keyvalues["end_date"] ~= nil ) then
year,month,day = nil
year = string.match(keyvalues["end_date"], "^(-?%d+%d%d%d)")
if (year ~= nil) then
y, month = string.match(keyvalues["end_date"], "^(-?%d+%d%d%d)-(%d%d)")
if (month == nil) then
month = "00"
day = "00"
else
y, m, day = string.match(keyvalues["end_date"], "^(-?%d+%d%d%d)-(%d%d)-(%d%d)")
if (day == nil) then
day = "00"
end
end
year = string.sub(year, 0, 4)
month = string.sub(month, 0, 2)
day = string.sub(day, 0, 2)
end_date_int = year..month..day
keyvalues["end_date_int"] = end_date_int
else
keyvalues["end_date_int"] = "Infinity"
end
end
return filter, keyvalues
end
-- Filtering on nodes
-- we just want place, name
function filter_tags_node (tags, numberofkeys)
filters, tags = filter_tags_dates(tags, numberofkeys)
local filter = 0
if not tags['place'] then filter = 1 end
return filter, tags
end
-- Filtering on relations: just multipolygons
-- (note that the current dataset doesn't have any multipolygons)
function filter_basic_tags_rel (tags, numberofkeys)
filter, tags = filter_tags_dates(tags, numberofkeys)
if tags["type"] ~= "multipolygon" then return 1, tags end
return 0, tags
end
-- Filtering on ways
-- Columns in planet_osm_polygon:
-- - building (amenity | building | industrial | shop | tourism)
-- - type (i.e. shop type, religion type)
-- - landuse (landuse | leisure) <--- note that we shouldn't set landuse if there's a building tag
-- - name
-- Columns in planet_osm_line:
-- - highway
-- - natural (=coastline)
function filter_tags_way (tags, numberofkeys)
local filter = 0 -- Will object be filtered out?
local polygon = 0 -- Will object be treated as polygon?
local roads = 0 -- Will object be added to planet_osm_roads?
local type = nil
local landuse = nil
filter, tags = filter_tags_dates(tags, numberofkeys)
-- Collapse into building/landuse tags
local building = tags["amenity"] or tags["industrial"] or tags["tourism"] or tags["building"]
if tags["shop"] then building="shop"; type=tags["shop"] end
if not building then landuse = tags["landuse"] or tags["leisure"] end
tags['type'] = type or tags["religion"]
if building or landuse then
tags["building"] = building
tags["landuse"] = landuse
return 0, tags, 1, 0
end
-- Otherwise, is it a highway or a coastline?
if tags["highway"] or tags["natural"] == "coastline" then
return 0, tags, 0, 0
end
if tags["natural"] == "water" then
return 0, tags, 1, 0
end
-- Not something we recognise
return 1, tags, 0, 0
end
function filter_tags_relation_member (tags, keyvaluemembers, roles, membercount)
filter = 0 -- Will object be filtered out?
linestring = 0 -- Will object be treated as linestring?
polygon = 0 -- Will object be treated as polygon?
roads = 0 -- Will object be added to planet_osm_roads?
membersuperseded = {}
for i = 1, membercount do
membersuperseded[i] = 0
end
type = tags["type"]
-- Remove type key
tags["type"] = nil
-- Relations with type=boundary are treated as linestring
if (type == "boundary") then
linestring = 1
end
-- Relations with type=multipolygon and boundary=* are treated as linestring
if ((type == "multipolygon") and tags["boundary"]) then
linestring = 1
-- For multipolygons...
elseif (type == "multipolygon") then
-- Treat as polygon
polygon = 1
end
return filter, tags, membersuperseded, linestring, polygon, roads
end
|
--***********************************************************
--** THE INDIE STONE **
--***********************************************************
require "TimedActions/ISBaseTimedAction"
---@class ISUnlockVehicleDoor : ISBaseTimedAction
ISUnlockVehicleDoor = ISBaseTimedAction:derive("ISUnlockVehicleDoor")
function ISUnlockVehicleDoor:isValid()
--print("ISUnlockVehicleDoor:isValid()")
--print(self.part:getDoor() and self.part:getDoor():isLocked())
return self.part:getDoor() and (self.forceValid or self.part:getDoor():isLocked())
end
function ISUnlockVehicleDoor:update()
if not self.character:getVehicle() then
self.character:faceThisObject(self.vehicle)
end
--print("ISUnlockVehicleDoor:update()")
-- TODO: drunk/panic = fumble
end
function ISUnlockVehicleDoor:start()
if not self.character:getVehicle() then
self.character:faceThisObject(self.vehicle)
end
self.vehicle:toggleLockedDoor(self.part, self.character, false)
if self.part:getDoor():isLocked() then
if self.part:getDoor():isLockBroken() then
self.character:Say(getText("IGUI_PlayerText_VehicleLockIsBroken"))
end
self.vehicle:playSound("VehicleDoorIsLocked");
self:forceStop();
return;
end
self.character:getEmitter():playSound("UnlockVehicleDoor")
if isClient() then
local args = { vehicle = self.vehicle:getId(), part = self.part:getId(), locked = false }
sendClientCommand(self.character, 'vehicle', 'setDoorLocked', args)
end
-- isValid() will return false since the door isn't locked now
self.forceValid = true
self:forceComplete()
end
function ISUnlockVehicleDoor:stop()
ISBaseTimedAction.stop(self)
end
function ISUnlockVehicleDoor:perform()
-- needed to remove from queue / start next.
ISBaseTimedAction.perform(self)
end
function ISUnlockVehicleDoor:new(character, part, seat)
local o = {}
setmetatable(o, self)
self.__index = self
o.character = character
o.vehicle = part:getVehicle()
o.part = part
o.seat = seat
o.forceValid = false
o.maxTime = -1
return o
end
|
local skynet = require "skynet"
local mc = require "skynet.multicast.core"
local datacenter = require "skynet.datacenter"
local harbor_id = skynet.harbor(skynet.self())
local command = {}
local channel = {}
local channel_n = {}
local channel_remote = {}
local channel_id = harbor_id
local NORET = {}
local function get_address(t, id)
local v = assert(datacenter.get("multicast", id))
t[id] = v
return v
end
local node_address = setmetatable({}, { __index = get_address })
-- new LOCAL channel , The low 8bit is the same with harbor_id
function command.NEW()
while channel[channel_id] do
channel_id = mc.nextid(channel_id)
end
channel[channel_id] = {}
channel_n[channel_id] = 0
local ret = channel_id
channel_id = mc.nextid(channel_id)
return ret
end
-- MUST call by the owner node of channel, delete a remote channel
function command.DELR(source, c)
channel[c] = nil
channel_n[c] = nil
return NORET
end
-- delete a channel, if the channel is remote, forward the command to the owner node
-- otherwise, delete the channel, and call all the remote node, DELR
function command.DEL(source, c)
local node = c % 256
if node ~= harbor_id then
skynet.send(node_address[node], "lua", "DEL", c)
return NORET
end
local remote = channel_remote[c]
channel[c] = nil
channel_n[c] = nil
channel_remote[c] = nil
if remote then
for node in pairs(remote) do
skynet.send(node_address[node], "lua", "DELR", c)
end
end
return NORET
end
-- forward multicast message to a node (channel id use the session field)
local function remote_publish(node, channel, source, ...)
skynet.redirect(node_address[node], source, "multicast", channel, ...)
end
-- publish a message, for local node, use the message pointer (call mc.bind to add the reference)
-- for remote node, call remote_publish. (call mc.unpack and skynet.tostring to convert message pointer to string)
local function publish(c , source, pack, size)
local remote = channel_remote[c]
if remote then
-- remote publish should unpack the pack, because we should not publish the pointer out.
local _, msg, sz = mc.unpack(pack, size)
local msg = skynet.tostring(msg,sz)
for node in pairs(remote) do
remote_publish(node, c, source, msg)
end
end
local group = channel[c]
if group == nil or next(group) == nil then
-- dead channel, delete the pack. mc.bind returns the pointer in pack and free the pack (struct mc_package **)
local pack = mc.bind(pack, 1)
mc.close(pack)
return
end
local msg = skynet.tostring(pack, size) -- copy (pack,size) to a string
mc.bind(pack, channel_n[c]) -- mc.bind will free the pack(struct mc_package **)
for k in pairs(group) do
-- the msg is a pointer to the real message, publish pointer in local is ok.
skynet.redirect(k, source, "multicast", c , msg)
end
end
skynet.register_protocol {
name = "multicast",
id = skynet.PTYPE_MULTICAST,
unpack = function(msg, sz)
return mc.packremote(msg, sz)
end,
dispatch = function (...)
skynet.ignoreret()
publish(...)
end,
}
-- publish a message, if the caller is remote, forward the message to the owner node (by remote_publish)
-- If the caller is local, call publish
function command.PUB(source, c, pack, size)
assert(skynet.harbor(source) == harbor_id)
local node = c % 256
if node ~= harbor_id then
-- remote publish
remote_publish(node, c, source, mc.remote(pack))
else
publish(c, source, pack,size)
end
end
-- the node (source) subscribe a channel
-- MUST call by channel owner node (assert source is not local and channel is create by self)
-- If channel is not exist, return true
-- Else set channel_remote[channel] true
function command.SUBR(source, c)
local node = skynet.harbor(source)
if not channel[c] then
-- channel none exist
return true
end
assert(node ~= harbor_id and c % 256 == harbor_id)
local group = channel_remote[c]
if group == nil then
group = {}
channel_remote[c] = group
end
group[node] = true
end
-- the service (source) subscribe a channel
-- If the channel is remote, node subscribe it by send a SUBR to the owner .
function command.SUB(source, c)
local node = c % 256
if node ~= harbor_id then
-- remote group
if channel[c] == nil then
if skynet.call(node_address[node], "lua", "SUBR", c) then
return
end
if channel[c] == nil then
-- double check, because skynet.call whould yield, other SUB may occur.
channel[c] = {}
channel_n[c] = 0
end
end
end
local group = channel[c]
if group and not group[source] then
channel_n[c] = channel_n[c] + 1
group[source] = true
end
end
-- MUST call by a node, unsubscribe a channel
function command.USUBR(source, c)
local node = skynet.harbor(source)
assert(node ~= harbor_id)
local group = assert(channel_remote[c])
group[node] = nil
return NORET
end
-- Unsubscribe a channel, if the subscriber is empty and the channel is remote, send USUBR to the channel owner
function command.USUB(source, c)
local group = assert(channel[c])
if group[source] then
group[source] = nil
channel_n[c] = channel_n[c] - 1
if channel_n[c] == 0 then
local node = c % 256
if node ~= harbor_id then
-- remote group
channel[c] = nil
channel_n[c] = nil
skynet.send(node_address[node], "lua", "USUBR", c)
end
end
end
return NORET
end
skynet.start(function()
skynet.dispatch("lua", function(_,source, cmd, ...)
local f = assert(command[cmd])
local result = f(source, ...)
if result ~= NORET then
skynet.ret(skynet.pack(result))
end
end)
local self = skynet.self()
local id = skynet.harbor(self)
assert(datacenter.set("multicast", id, self) == nil)
end)
|
function wax.autoload(...)
for i, folder in ipairs({...}) do
local files = wax.filesystem.search(wax.root(folder), "lua$")
for i, file in ipairs(files) do
local requireString = file:match(wax.root() .. "/(.*)%.lua$")
requireString = requireString:gsub("/", ".")
require(requireString)
end
end
end
|
-- Released under the MIT License (https://raw.githubusercontent.com/foeb/cranberry.lua/master/LICENSE)
local cb = {}
-- TODO: find a way to access lua_createtable in order to avoid triggering
-- rehashes when initializing arrays. decide if this is important or necessary
-- TODO: include a submodule of pre-curried functions
-- library functions made local for efficiency
local min = math.min
local max = math.max
local random = math.random
local floor = math.floor
local remove = table.remove
local insert = table.insert
local concat = table.concat
local unpack = unpack or table.unpack -- 5.1, 5.2, and 5.3 compatibility
-- push_(a, v): destructively append v to an array a
function cb.push_(a, v)
a[#a + 1] = v
return a
end
-- pop_(a): destructively remove the last element of an array a and
-- return it
function cb.pop_(a)
local v = a[#a]
a[#a] = nil
return v
end
-- shift_(a): destructively remove the first element of an array a and
-- return it
function cb.shift_(a)
return remove(a, 1)
end
-- unshift_(a, v): destructively insert v at the beginning of a
function cb.unshift_(a, v)
return insert(a, 1, v)
end
-- map(f, a): apply a function f to every member of the array a
function cb.map(f, a)
if not cb.is_table(a) then
return f(a)
end
local na = {}
for i = 1, #a do
na[i] = f(a[i])
end
return na
end
-- map_(f, a): destructively apply a function f to every member of the
-- array a
function cb.map_(f, a)
if not cb.is_table(a) then
a = f(a)
return a
end
for i = 1, #a do
a[i] = f(a[i])
end
return a
end
-- each(f, a): apply a function f to every member of the array a without
-- storing or returning the results.
function cb.each(f, a)
if not cb.is_table(a) then
f(a)
end
for i = 1, #a do
f(a[i])
end
end
-- foldr(f, a0, a): reduce the array a from right to left using a0 as the
-- starting value
function cb.foldr(f, a0, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = a0
local len = #a
for i = 1, len do
r = f(a[len + 1 - i], r)
end
return r
end
-- foldl(f, a0, a): reduce the array a from left to right using a0 as the
-- starting value
function cb.foldl(f, a0, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = a0
for i = 1, #a do
r = f(r, a[i])
end
return r
end
-- foldr1(f, a): reduce the array a from right to left
function cb.foldr1(f, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
if a[1] == nil then
return nil, cb.errors.empty
end
local len = #a
if len == 1 then return a[1] end
local r = a[len]
for i = 2, len do
r = f(a[len + 1 - i], r)
end
return r
end
-- foldl1(f, a): reduce the array a from left to right
function cb.foldl1(f, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
if a[1] == nil then
return nil, cb.errors.empty
end
local r = a[1]
local len = #a
if len == 1 then return r end
for i = 2, len do
r = f(r, a[i])
end
return r
end
--[[
-- filter(f, a): return an array containing all elements of an array a that
-- are true under the function f(v)
function cb.filter(f, a)
local function g(_, v) return f(v) end
return cb.filteri(g, a)
end
--]]
-- filter(f, a): return an array containing all elements of an array a that
-- are true under the function f(i, v)
function cb.filter(f, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = {}
local j = 1
for i = 1, #a do
if f(i, a[i]) then
r[j] = a[i]
j = j + 1
end
end
return r
end
-- filterObject(f, t): similar to filter, except it operates on the entire
-- table using a function f(k, v)
function cb.filterObject(f, t)
if not cb.is_table(t) then
return nil, cb.errors.not_table
end
local r = {}
for k, v in pairs(t) do
if f(k, v) then
r[k] = v
end
end
return r
end
-- elem(e, a): return true if element e is in an array a and false otherwise
function cb.elem(e, a)
if not cb.is_table(a) then return false end
for i = 1, #a do
if e == a[i] then return true end
end
return false
end
-- curry(f, n = 2): curry f for the first n arguments so that
-- curry(f, n)(x1)(x2)(..)(xn, ...) = f(x1, x2, .., xn, ...).
function cb.curry(f, n)
n = n or 2
local function g(args, m)
if m < 1 then
return f(unpack(args))
else
local function h(...)
cb.append_(args, { ... })
return g(args, m - 1)
end
return h
end
end
return g({}, n)
end
-- uncurry(f, n = 2): the inverse of curry(f, n),
-- i.e. uncurry(curry(f, m), n) = f iff m = n. Results are unpredicatble
-- when m ~= n.
function cb.uncurry(f, n)
n = n or 2
local function g(...)
local args = { ... }
local r = f
local len = min(n, #args)
for i = 1, len do
r = r(args[i])
end
return r -- use up the rest of the arguments
end
return g
end
-- max(a): return the max of the elements of a
function cb.max(a)
return cb.foldl1(max, a)
end
-- min(a): return the min of the elements of a
function cb.min(a)
return cb.foldl1(min, a)
end
-- sum(a): return the sum of the elements of a
function cb.sum(a)
local function f(x, y) return x + y end
return cb.foldl(f, 0, a) -- an empty sum is by convention 0
end
-- product(a): return the product of the elements of a
function cb.product(a)
local function f(x, y) return x * y end
return cb.foldl(f, 1, a) -- an empty product is by convention 1
end
-- all(p, a): return true if p(a[i]) is true for every element a[i] of a
function cb.all(p, a)
for i = 1, #a do
if not p(a[i]) then return false end
end
return true
end
-- any(p, a): return true if p(a[i]) is true for any element a[i] of a
function cb.any(p, a)
for i = 1, #a do
if p(a[i]) then return true end
end
return false
end
-- none(p, a): return true if p(a[i]) is false for every element a[i] of a
function cb.none(p, a)
return not cb.any(p, a)
end
-- id(v): return v
function cb.id(v) return v end
-- const(v): return a function that always returns v
function cb.const(v)
local function f(_) return v end
return f
end
-- flip(f): return a function that takes its first two arguments in the
-- reverse order of f
function cb.flip(f)
local function g(a, b, ...)
return f(b, a, ...)
end
return g
end
-- applyUntil(p, f, a): apply f to each element of a until p returns true
function cb.applyUntil(p, f, a)
if cb.is_table(a) then
local r = {}
for i = 1, #a do
if p(a[i]) then return r end
r[i] = f(a[i])
end
return r
else
if p(a) then return a else return f(a) end
end
end
-- _append(a1, a2): return a1 appended by a2
local function _append(a1, a2)
if not cb.is_table(a1) or not cb.is_table(a2) then
return nil, cb.errors.not_table
end
local r = {}
local len1 = #a1
local len2 = #a2
for i = 1, len1 do
r[i] = a1[i]
end
for i = 1, len2 do
r[i + len1] = a2[i]
end
return r
end
-- append(...): append all of the arguments
function cb.append(...)
local args = { ... }
if not cb.all(cb.is_table, args) then
return nil, cb.errors.not_table
end
return cb.foldr(_append, {}, args)
end
-- _append_(a1, a2): destructively append a1 by a2
local function _append_(a1, a2)
if not cb.is_table(a1) or not cb.is_table(a2) then
return nil, cb.errors.not_table
end
local len1 = #a1
local len2 = #a2
for i = 1, len2 do
a1[i + len1] = a2[i]
end
return a1
end
-- append_(...): destructively append all of the arguments
function cb.append_(...)
local args = { ... }
if not cb.all(cb.is_table, args) then
return nil, cb.errors.not_table
end
return cb.foldr(_append_, {}, args)
end
-- head(a, n = 1): return the first n elements of a in an array.
-- If n == 1, then return the first element
function cb.head(a, n)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
if not n then return a[1] end -- n defaults to 1
local r = {}
local len = min(#a, n)
for i = 1, len do
r[i] = a[i]
end
return r
end
-- last(a, n = 1): return the last n elements of a.
-- If n == 1, then return the last element
function cb.last(a, n)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local len = #a
if not n then return a[len] end -- n defaults to 1
local r = {}
local m = min(len, n)
for i = 1, m do
r[i] = a[i + len - m]
end
return r
end
-- tail(a, n = 1): return the elements of a after skipping n
function cb.tail(a, n)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
n = n or 1
local r = {}
local len = #a
if len <= n then return {} end
for i = n + 1, len do
r[i - n] = a[i]
end
return r
end
-- init(a): return all but the last element of a
function cb.init(a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
return cb.head(a, #a - 1)
end
-- reverse(a): reverses an array a
function cb.reverse(a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = {}
local len = #a
for i = 1, len do r[i] = nil end -- to ensure elements don't go into the hash
local n = floor(len/2)
for i = 1, n do
r[i], r[len - i + 1] = a[len - i + 1], a[i]
end
if len % 2 == 1 then r[n + 1] = a[n + 1] end
return r
end
-- reverse_(a): destructively reverses an array in place
function cb.reverse_(a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local len = #a
for i = 1, floor(len/2) do
a[i], a[len - i + 1] = a[len - i + 1], a[i]
end
return a
end
-- concat(as): concatenate all of the elements of as
function cb.concat(as)
return cb.append(unpack(as))
end
-- scanl(f, a0, a): is similar to foldl, except it returns a list
-- containing each of the intermediate steps
function cb.scanl(f, a0, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = { a0 }
for i = 1, #a do
r[i + 1] = f(r[i], a[i])
end
return r
end
-- scanl1(f, a): is similar to foldl1, except it returns a list
-- containing each of the intermediate steps
function cb.scanl1(f, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = { a[1] }
for i = 1, #a - 1 do
r[i + 1] = f(r[i], a[i + 1])
end
return r
end
-- scanr(f, a0, a): is similar to foldr, except it returns a list
-- containing each of the intermediate steps
function cb.scanr(f, a0, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = { a0 }
local len = #a
for i = 1, len do
r[i + 1] = f(a[len + 1 - i], r[i])
end
return r
end
-- scanr1(f, a): is similar to foldr1, except it returns a list
-- containing each of the intermediate steps
function cb.scanr1(f, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local len = #a
local r = { a[len] }
for i = 1, len - 1 do
r[i + 1] = f(a[len - i], r[i])
end
return r
end
-- take(n, a): flip(head)
cb.take = cb.flip(cb.head)
-- drop(n, a): flip(tail)
cb.drop = cb.flip(cb.tail)
-- splitAt(n, a): return { take(n, a), drop(n, a) }
function cb.splitAt(n, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
if n < 1 or #a < n then
return nil, cb.errors.outOfBounds
end
return { cb.take(n, a), cb.drop(n, a) }
end
-- takeWhile(p, a): return the longest prefix of a that all satisfy p
function cb.takeWhile(p, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = {}
for i = 1, #a do
if not p(a[i]) then return r end
r[i] = a[i]
end
return r
end
-- dropWhile(p, a): return the elements remaining after takeWhile(p, a)
function cb.dropWhile(p, a)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local r = {}
local s
for i = 1, #a do
if not s and not p(a[i]) then s = i end
if s then r[i - s + 1] = a[i] end
end
return r
end
-- span(p, a): return { takeWhile(p, a), dropWhile(p, a) }
function cb.span(p, a)
return { cb.takeWhile(p, a), cb.dropWhile(p, a) }
end
-- TODO: replace the zip functions with functions of the form zip(...), zipWith(f, ...)
-- zip(a, b): return an array of corresponding pairs of elements from
-- a and b. If one array is short, then the remaining elements of the
-- longer array are discarded
function cb.zip(a, b)
if not cb.is_table(a) or not cb.is_table(b) then
return nil, cb.errors.not_table
end
local r = {}
for i = 1, min(#a, #b) do
r[i] = { a[i], b[i] }
end
return r
end
-- zip3(a, b, c): similar to zip, except it takes three arrays instead of two
function cb.zip3(a, b, c)
if not cb.is_table(a) or not cb.is_table(b) or not cb.is_table(c) then
return nil, cb.errors.not_table
end
local r = {}
for i = 1, min(#a, #b, #c) do
r[i] = { a[i], b[i], c[i] }
end
return r
end
-- zipWith(f, a, b): return an array of the function f applied to
-- corresponding pairs of elements from a and b. If one array is short,
-- then the remaining elements of the longer array are discarded
function cb.zipWith(f, a, b)
if not cb.is_table(a) or not cb.is_table(b) then
return nil, cb.errors.not_table
end
local r = {}
for i = 1, min(#a, #b) do
r[i] = f(a[i], b[i])
end
return r
end
-- zipWith3(f, a, b, c): similar to zipWith, except it takes three arrays
-- instead of two
function cb.zipWith3(f, a, b, c)
if not cb.is_table(a) or not cb.is_table(b) or not cb.is_table(c) then
return nil, cb.errors.not_table
end
local r = {}
for i = 1, min(#a, #b, #c) do
r[i] = f(a[i], b[i], c[i])
end
return r
end
-- unzip(ps): take an array of pairs and return an pair of arrays
function cb.unzip(ps)
if not cb.is_table(ps) then
return nil, cb.errors.not_table
end
local r = { {}, {} }
for i = 1, #ps do
if not cb.is_table(ps[i]) then
return nil, cb.errors.not_table
end
r[1][i] = ps[i][1]
r[2][i] = ps[i][2]
end
return r
end
-- unzip3(ts): similar to unzip, except it takes an array of triples
-- instead of pairs
function cb.unzip3(ts)
if not cb.is_table(ts) then
return nil, cb.errors.not_table
end
local r = { {}, {}, {} }
for i = 1, #ts do
if not cb.is_table(ts[i]) then
return nil, cb.errors.not_table
end
r[1][i] = ts[i][1]
r[2][i] = ts[i][2]
r[3][i] = ts[i][3]
end
return r
end
-- lines(s): return an array of all lines in s. Does not work register
-- \r characters.
function cb.lines(s)
if not cb.is_string(s) then
return nil, cb.errors.not_string
end
local r = {}
local ri = 1
local prev = 1
for si = 1, s:len() do
if s:sub(si, si) == '\n' then
r[ri] = s:sub(prev, si - 1)
prev = si + 1
ri = ri + 1
end
end
r[ri] = s:sub(prev, -1)
if r[ri] == '' then r[ri] = nil end -- following Haskell's example
return r -- TODO: make sure that each line doesn't include the newline character
end
-- unlines(as): concatenate all of the strings in as, separated by a newline
function cb.unlines(as)
return concat(as, '\n')
end
-- words(s): return an array of all words in s that are separated by
-- whitespace
-- Credit to http://lua-users.org/wiki/StringRecipes
function cb.words(s)
if not cb.is_string(s) then
return nil, cb.errors.not_string
end
local r = {}
local i = 1
for word in s:gmatch("%S+") do
r[i] = word
i = i + 1
end
return r
end
-- unwords(as): concatenate all of the strings in as, separated by a space
function cb.unwords(as)
return concat(as, ' ')
end
-- wrap(f, w): wrap f in w, i.e return bind(w, f), so that wrap(f, w)(...) = w(f, ...)
function cb.wrap(f, w)
return cb.bind(w, f)
end
-- uniq(a): return an array containing all of a's unique values in the order
-- that they appear
function cb.uniq(a)
if not cb.is_table(a) then return a end
local r = {}
local ri = 1
for i = 1, #a do
if not cb.elem(a[i], r) then
r[ri] = a[i]
ri = ri + 1
end
end
return r
end
-- negate(p): return a function q such that q(v) = not p(v)
function cb.negate(p)
local function q(v)
return not p(v)
end
return q
end
-- TODO: replace bind with bindn
-- bind(f, v): return a function g(...) = f(v, ...)
function cb.bind(f, v)
local function g(...)
return f(v, ...)
end
return g
end
-- bindn(f, ...): return a function g(...2) = f(v, ..., ...2)
function cb.bindn(f, ...)
return cb.foldl(cb.bind, f, { ... })
end
-- result(m, o, ...): return o:m(...)
function cb.result(m, o, ...)
return m(o, ...)
end
-- defaults(d, o): like defaults_, except it returns a new table
function cb.defaults(d, o)
local r = {}
for k, v in pairs(d) do
r[k] = v
end
for k, v in pairs(o) do
r[k] = v
end
return r
end
-- defaults_(d, o): for each key k in d, if o[k] == nil, then o[k] = d[k].
-- Return the resulting object (destructive)
function cb.defaults_(d, o)
for k, v in pairs(d) do
if o[k] == nil then
o[k] = v
end
end
return o
end
-- trycatch(f, errors, ?finally): wrap f in a function such that, when it is
-- called, if f returns nil for its first value, then the wrapper checks
-- errors using the second value returned for a function. If it finds one,
-- it calls it with the original arguments and returns its result. The
-- optional finally function is called with the original arguments after
-- either of these happens.
function cb.trycatch(f, errors, finally)
finally = finally or cb.id
local function wrap(...)
local res = { f(...) }
if res[1] == nil then
if res[2] and errors[res[2]] then
local nres = { errors[res[2]](...) }
finally(...)
return unpack(nres)
end
end
finally(...)
return res[1]
end
return wrap
end
-- errors: a table of common error strings
cb.errors = {
not_string = 'Not a string',
not_table = 'Not a table',
not_number = 'Not a number',
not_bool = 'Not a bool',
not_function = 'Not a function',
not_callable = 'Not callable',
immut = 'Can\'t modify an immutable table',
outOfBounds = 'Variable is out of bounds',
empty = 'Array is empty'
}
-- is_same(t1, t2): return true if t1 and t2 are 'essentially' equal, not
-- including functions that return the same things.
function cb.is_same(t1, t2)
if not cb.is_table(t1) or not cb.is_table(t2) then
return t1 == t2
end
for k, v in pairs(t1) do
if not cb.is_same(v, t2[k]) then
return false
end
end
return cb.is_same(getmetatable(t1), getmetatable(t2))
end
-- pluck(t, ks): extract a list of property values
function cb.pluck(t, k)
local function f(s)
return cb.is_table(s) and s[k]
end
return cb.map(f, t)
end
-- shuffle(a): return a shuffled copy of a using the Fisher-Yates shuffle.
-- (Note: make sure to seed the random number generator first, such as
-- calling math.randomseed(os.time()).)
function cb.shuffle(a)
if not cb.is_table(a) then
return a -- already shuffled :P
end
local r = {}
local j
local i = 1
while a[i] ~= nil do -- this algorithm doesn't need to know the length of a
j = random(i)
if j == i then
cb.push_(r, a[i])
else
cb.push_(r, r[j])
r[j] = a[i]
end
i = i + 1
end
return r
end
-- shuffle_(a): destructively shuffle a using the Fisher-Yates shuffle.
-- (Note: make sure to seed the random number generator first, such as
-- calling math.randomseed(os.time()).)
function cb.shuffle_(a)
if not cb.is_table(a) then
return a -- already shuffled :P
end
local len = #a
local j
for i = 1, len do
j = (i == len and 0) or random(len-i)
a[i], a[i+j] = a[i+j], a[i]
end
return a
end
-- merge(a, b, comp = op.lt): merge the arrays a and b into a new array
function cb.merge(a, b, comp)
if not cb.is_table(a) or not cb.is_table(b) then
return nil, cb.errors.not_table
end
comp = comp or cb.op.lt
local r = {}
while not cb.is_empty(a) and not cb.is_empty(b) do
if comp(a[1], b[1]) then
cb.push_(r, a[1])
a = cb.tail(a)
else
cb.push_(r, b[1])
b = cb.tail(b)
end
end
while not cb.is_empty(a) do
cb.push_(r, a[1])
a = cb.tail(a)
end
while not cb.is_empty(b) do
cb.push_(r, b[1])
b = cb.tail(b)
end
return r
end
-- mergesort(a, comp = op.lt): stably sort an array a
function cb.mergesort(a, comp)
if not cb.is_table(a) then
return a
end
comp = comp or cb.op.lt
local len = #a
if len <= 1 then
return a
end
local left = {}
local right = {}
for i = 1, len do
if i % 2 == 1 then
cb.push_(left, a[i])
else
cb.push_(right, a[i])
end
end
left = cb.mergesort(left, comp)
right = cb.mergesort(right, comp)
return cb.merge(left, right, comp)
end
-- sort(a, comp = op.lt): shallowcopy a and then calls table.sort
function cb.sort(a, comp)
local na = cb.shallowcopy(a)
return table.sort(na, comp)
end
-- sort_(a, comp = op.lt): alias for table.sort
cb.sort_ = table.sort
-- sortBy(a, f, comp = op.lt): return a stably sorted copy of a, ranked in
-- ascending order by the results of running each value through f. If f
-- isn't a function, it ranks each element of a[i] by a[i][f]
function cb.sortBy(a, f, comp)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local g = f
if not cb.is_function(f) then
g = function(v)
return v[f]
end
end
comp = comp or cb.op.lt
local ncomp = function(x, y)
return comp(g(x), g(y))
end
return cb.mergesort(a, ncomp)
end
-- groupBy(a, f): group an array a by the results of running its elements
-- through f. If f isn't a function, it groups each element of a[i] by a[i][f]
function cb.groupBy(a, f)
if not cb.is_table(a) then
return nil, cb.errors.not_table
end
local g = f
if not cb.is_function(f) then
g = function(v)
return v[f]
end
end
local r = {}
local k
for i = 1, #a do
k = g(a[i])
if r[k] == nil then
r[k] = { a[i] }
else
cb.push_(r[k], a[i])
end
end
return r
end
-- countBy(a, f): sort an array a into groups according to f and return a
-- count for the number of objects in each group.
function cb.countBy(a, f)
local r = cb.groupBy(a, f)
if r == nil then
return nil, cb.errors.not_table
end
cb.mapObject_(cb.op.len, r)
return r
end
-- op: a table of functions that allow you to call operators by name
cb.op = {
add = function(a, b) return a + b end,
sub = function(a, b) return a - b end,
mul = function(a, b) return a * b end,
div = function(a, b) return a / b end,
mod = function(a, b) return a % b end,
unm = function(a) return -a end,
concat = function(a, b) return a .. b end,
len = function(a) return #a end,
eq = function(a, b) return a == b end,
neq = function(a, b) return a ~= b end,
lt = function(a, b) return a < b end,
gt = function(a, b) return a > b end,
le = function(a, b) return a <= b end,
ge = function(a, b) return a >= b end,
opAnd = function(a, b) return a and b end,
opOr = function(a, b) return a or b end,
opNot = function(a) return not a end,
newtable = function(...) return { ... } end,
funcall = function(f, ...) return f(...) end,
index = function(t, k) return t[k] end,
newindex = function(t, k, v) t[k] = v end
}
-- once(f): return a function that only returns a value the first time it
-- is called
function cb.once(f)
return cb.before(f, 1)
end
-- after(f, n = 1): return a function that only returns a value after the
-- first n times it is called
function cb.after(f, n)
n = n or 1
local i = 1
local function g(...)
if i > n then
return f(...)
end
i = i + 1
end
return g
end
-- before(f, n = 1): return a function that only returns a value before
-- the first n times it is called
function cb.before(f, n)
n = n or 1
local i = 1
local function g(...)
if i <= n then
i = i + 1
return f(...)
end
end
return g
end
-- compose(f, ...): return a function g(args) = f(f1(f2(..(fn(args)))))
-- where { f1, f2, .., fn } = { ... }
function cb.compose(f, ...)
local function _compose(a, b)
local function g(...)
return a(b(...))
end
return g
end
return cb.foldr1(_compose, { f, ... })
end
-- takei(n, it): return an iterator that returns only the first n values of it
cb.takei = cb.flip(cb.before)
-- dropi(n, it): return an iterator that skips the first n values of it
cb.dropi = cb.flip(cb.after)
-- iterate(f, x): return an iterator that applies f to the previous value in an endless loop
function cb.iterate(f, x)
local prev = x
local function it()
local old = prev
prev = f(prev)
return old
end
return it
end
-- replicate(n, x): return an array containing x n times
function cb.replicate(n, x)
return cb.iterlist(cb.takei(n, cb.const(x)))
end
-- cycle(a): return an iterator that cycles through an array a in an endless loop
function cb.cycle(a)
local len = #a
local i = 0
local function it()
if i >= len then i = 0 end
i = i + 1
return a[i]
end
return it
end
-- takeWhilei(p, it): analagous to takeWhile, except takes an iterator and
-- returns an iterator
function cb.takeWhilei(p, it)
local continue = true
local v
local function nit()
if continue then
v = it()
continue = p(v)
if continue then return v end
end
end
return nit
end
-- dropWhilei(p, it): analagous to dropWhile, except takes an iterator and
-- returns an iterator
function cb.dropWhilei(p, it)
local drop = true
local v
local function nit()
v = it()
if drop then
drop = p(v)
end
if not drop then
return v
end
end
return nit
end
-- iterlist(it): return an array containing all of the values of the iterator it
function cb.iterlist(it)
local r = {}
local i = 1
local v
while true do
v = it()
if not v then return r end
r[i] = v
i = i + 1
end
end
-- inc(i): return i + 1 (utility)
function cb.inc(i) return i + 1 end
-- dec(i): return i - 1 (utility)
function cb.dec(i) return i - 1 end
-- clone(o, ?_type): return an instance of o as a prototype
local function clone(o, _type)
if not cb.is_table(o) then return o end
local t = { _proto = o, _type = _type or o._type }
setmetatable(t, { __index = o })
return t
end
-- object:isa(t, o): return true if t descends from o
local function isa(t, o)
local function getProtoIter(s)
local v = s
return function()
if v then
v = v._proto
return v
end
end
end
if t == o then return true end
for p in getProtoIter(t) do
if p == o then return true end
end
return false
end
-- object: base prototype to inherit from
cb.object = { _type = 'object' }
-- object:duplicate(): return a copy of this object without copying its
-- prototype
function cb.object:duplicate()
local _proto = self._proto
self._proto = nil -- make sure that _proto still points to the same object
local o = cb.copy(self)
o._proto = _proto
self._proto = _proto -- restore self._proto
return o
end
-- object:new(): return an instance of object as a prototype and initialize it
function cb.object:new(...)
local o = self:clone()
if self.init then
self.init(o, ...)
end
return o
end
-- object:init(): used to initialize a new object. This instance does nothing.
function cb.object.init() end
-- object:clone(?_type): return an instance of object as a prototype
cb.object.clone = clone
-- object:isa(o): return true if self descends from o
cb.object.isa = isa
--[[
-- object:setmeta(t): set the metatable of object while preserving
-- inheritance. (Note: you cannot modify __index using this method)
-- TODO: allow modification to __index by using a wrapper function
function cb.object:setmeta(mt)
if not cb.is_table(t) then return nil, cb.errors.not_table end
local function windex(f, t, k)
local v = f(t, k)
if v then return v end
return t._proto[k]
end
nmt = cb.shallowcopy(mt)
nmt.__index = cb.wrap(mt.__index, windex)
setmetatable(self, nmt)
return self
end
--]]
-- keys(t): return all of the non-integer keys of t
function cb.keys(t)
if not cb.is_table(t) then
return nil, cb.errors.not_table
end
local r = {}
local ri = 1
for k, _ in pairs(t) do
if not cb.is_number(k) then
r[ri] = k
ri = ri + 1
end
end
return r
end
-- allKeys(t): return all of the non-integer keys of t and its prototypes
function cb.allKeys(t)
if not cb.is_table(t) then
return nil, cb.errors.not_table
end
local prev = t
local function it() -- iterate across the prototypes
local p = prev
prev = prev and prev._proto
return p
end
local r = {}
for v in it do
r = cb.defaults(v, r)
end
return cb.keys(r)
end
-- setKeys_(o, t): set o[k] to t[k] for each k in keys(t)
function cb.setKeys_(o, t)
local ks = cb.keys(t)
for _,k in ipairs(ks) do
o[k] = t[k]
end
return o
end
-- values(t): return the values of all of the non-integer keys of t
function cb.values(t)
-- TODO: make more efficient
local function f(k) return t[k] end
return cb.map(f, cb.keys(t))
end
-- allValues(t): return the values of all of the non-integer keys of t and
-- its prototypes
function cb.allValues(t)
-- TODO: make more efficient
local function f(k) return t[k] end
return cb.map(f, cb.allKeys(t))
end
-- mapObject_(f, t): like map but destructively iterates over all of the
-- keys of o
function cb.mapObject_(f, o)
for k,v in pairs(o) do
o[k] = f(v)
end
return o
end
-- mapObject(f, t): like map but iterates over all of the keys of o
function cb.mapObject(f, o)
local ks = cb.keys(o)
local r = {}
for _, k in ipairs(ks) do
r[k] = f(o[k])
end
for i, _ in ipairs(o) do
r[i] = f(o[i])
end
return r
end
-- copy(t): return a deep copy of t
-- Credit to @tylerneylon
-- Source: https://gist.github.com/tylerneylon/81333721109155b2d244
function cb.copy(o, seen)
-- Handle non-tables and previously-seen tables.
if type(o) ~= 'table' then return o end
if seen and seen[o] then return seen[o] end
-- New table; mark it as seen an copy recursively.
local s = seen or {}
local res = setmetatable({}, getmetatable(o))
s[o] = res
for k, v in pairs(o) do res[cb.copy(k, s)] = cb.copy(v, s) end
return res
end
-- shallowcopy(t): return a shallow copy of t
-- Credit to @MihailJP
-- Source: https://gist.github.com/MihailJP/3931841
function cb.shallowcopy(t)
if type(t) ~= "table" then return t end
local meta = getmetatable(t)
local target = {}
for k, v in pairs(t) do target[k] = v end
setmetatable(target, meta)
return target
end
-- immut(t): return a read-only link to t
function cb.immut(t)
if not cb.is_table(t) then return t end
local nt = { _immut = true, _orig = t }
local function _fi(_, k) return cb.immut(t[k]) end
local function _fni () return nil, cb.errors.immut end
setmetatable(nt, {
__index = _fi,
__newindex = _fni
})
return nt
end
-- is_immut(t): return true if t was made immutable through immut
function cb.is_immut(t)
return t._immut
end
-- fromimmut(t): return a mutable version of t
function cb.from_immut(t)
if not cb.is_table(t) then return t end
if not t._immut then return t end
return t._orig
end
-- is_empty(t): return true if t is empty
function cb.is_empty(t)
return next(t) == nil
end
-- is_table(o): return true if o is a table
function cb.is_table(o)
return type(o) == 'table'
end
-- is_string(o): return true if o is a string
function cb.is_string(o)
return type(o) == 'string'
end
-- is_number(o): return true if o is a number
function cb.is_number(o)
return type(o) == 'number'
end
-- is_function(o): return true if o is a function
function cb.is_function(o)
return type(o) == 'function'
end
-- is_boolean(o): return true if o is a boolean
function cb.is_boolean(o)
return type(o) == 'boolean'
end
-- is_nil(o): return true if o is nil
function cb.is_nil(o)
return o == nil
end
-- is_userdata(o): return true if o is userdata. Untested
function cb.is_userdata(o)
return type(o) == 'userdata'
end
-- is_thread(o): return true if o is a thread. Untested
function cb.is_thread(o)
return type(o) == 'thread'
end
-- is_callable(o): return true if o can be called like a function. Untested
function cb.is_callable(o)
return cb.is_function or (getmetatable(o) and getmetatable(o).__call ~= nil)
end
return cb
-- References and inspirations:
-- https://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html
-- http://underscorejs.org
-- https://github.com/Yonaba/Moses
-- http://bolinfest.com/javascript/inheritance.php
|
--!A cross-platform build utility based on Lua
--
-- 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
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_mbedtls.lua
--
-- imports
import("package.manager.find_package")
-- find mbedtls
--
-- @param opt the package options. e.g. see the options of find_package()
--
-- @return see the return value of find_package()
--
function main(opt)
opt.links = {"mbedtls", "mbedcrypto", "mbedx509"}
return opt.find_package("mbedtls", opt)
end
|
local api = {}
local macro = {}
local function readfile(filename)
local f = assert(io.open(filename))
local str = f:read "a"
f:close()
return str
end
local function dump(filename)
local str = readfile(filename)
for w in str:gmatch "#define[%s]+(luaL?_[%w_]+)" do
macro[w] = true
end
for w in str:gmatch "luaL?_[%w_]+" do
api[w] = true
end
for w in str:gmatch "luaopen_[%w_]+" do
api[w] = true
end
end
dump "3rd/bee.lua/3rd/lua/src/lua.h"
dump "3rd/bee.lua/3rd/lua/src/lualib.h"
dump "3rd/bee.lua/3rd/lua/src/lauxlib.h"
api.lua_Integer = true
api.lua_Unsigned = true
api.lua_Number = true
local t1 = {}
for w in pairs(api) do
if not macro[w] then
t1[#t1+1] = w
end
end
table.sort(t1)
for _, w in ipairs(t1) do
print(("#define %s rlua%s"):format(w, w:sub(4)))
end
print("")
print("#endif")
print("")
print("#else")
print("")
print("#include <lua.hpp>")
print("")
local t2 = {}
for w in pairs(api) do
t2[#t2+1] = w
end
table.sort(t2)
for _, w in ipairs(t2) do
print(("#define rlua%s %s"):format(w:sub(4), w))
end
print("")
print("#endif")
|
local model={}
function model:Initial(params)
self.params=params;
self.map=nn.Sequential()
self.map:add(nn.Linear(self.params.dimension,self.params.dimension))
self.map:add(nn.Tanh())
self.map:add(nn.Linear(self.params.dimension,self.params.dimension))
self.map:add(nn.Tanh())
self.map:add(nn.Linear(self.params.dimension,1))
self.map=self.map:cuda()
self.mse = nn.MSECriterion()
self.mse=self.mse:cuda()
if self.params.readSequenceModel then
self.forward_model=torch.reload("../../Decode/decode_model")
local open_=torch.DiskFile(params.forward_params_file,"r"):binary();
self.forward_model.params=open_:readObject()
self.forward_model.params.dictPath="../../data/movie_25000"
--self.forward_model.params.batch_size=self.params.batch_size
self.forward_model.params.model_file=params.forward_model_file
self.forward_model:DecoderInitial(self.forward_model.params_file)
self.forward_model.mode="test"
self.backward_model=torch.reload("../../Decode/decode_model")
local open_=torch.DiskFile(params.backward_params_file,"r"):binary();
self.backward_model.params=open_:readObject()
--self.backward_model.params.batch_size=self.params.batch_size
self.backward_model.params.dictPath="../../data/movie_25000"
self.backward_model.params.model_file=params.backward_model_file
self.backward_model:DecoderInitial()
self.backward_model.mode="test"
end
if self.params.readFutureModel then
local parameter,_=self.map:parameters()
local file=torch.DiskFile(self.params.FuturePredictorModelFile,"r"):binary();
local read_params=file:readObject();
for j=1,#parameter do
parameter[j]:copy(read_params[j]);
end
end
print("read data done")
end
function model:model_forward()
local total_Error=0;
local instance=0;
for t=1,self.forward_model.Word_t:size(2)-1 do
local representation_left=self.forward_model.store_t[t][2*self.backward_model.params.layers-1]:index(1,self.forward_model.Left_t[t])
local predict_left=self.backward_score:index(1,self.forward_model.Left_t[t])
self.map:zeroGradParameters()
local pred=self.map:forward(representation_left)
local Error=self.mse:forward(pred,predict_left)
if self.mode=="train" then
self.mse:backward(pred,predict_left)
self.map:backward(representation_left,self.mse.gradInput)
self.map:updateParameters(self.params.alpha)
end
total_Error=total_Error+Error*representation_left:size(1)
instance=instance+representation_left:size(1)
end
return total_Error,instance
end
function model:test()
local open_train_file=io.open(self.params.test_file,"r")
local End,Word_s,Word_t,Mask_s,Mask_t;
local End=0;
local batch_n=1;
local total_Error=0;
local n_instance=0;
local aver_ppl=0;
local sen_num=0
while End==0 do
batch_n=batch_n+1;
End,self.forward_model.Word_s,self.forward_model.Word_t,self.forward_model.Mask_s,self.forward_model.Mask_t,self.forward_model.Left_s,self.forward_model.Left_t,self.forward_model.Padding_s,self.forward_model.Padding_t,self.forward_model.Source,self.forward_model.Target=self.forward_model.Data:read_train(open_train_file)
if End==1 then
break;
end
self.forward_model:model_forward()
self.backward_model.Source={}
self.backward_model.Target={}
for i=1,#self.forward_model.Source do
self.backward_model.Source[i]=self.forward_model.Target[i]:sub(1,-1,2,self.forward_model.Target[i]:size(2)-1);
self.backward_model.Target[i]=torch.cat(torch.Tensor({{self.backward_model.Data.EOS}}),torch.cat(self.forward_model.Source[i],torch.Tensor({self.backward_model.Data.EOT})))
end
self.backward_model.Word_s,self.backward_model.Mask_s,self.backward_model.Left_s,self.backward_model.Padding_s=self.backward_model.Data:get_batch(self.backward_model.Source,true)
self.backward_model.Word_t,self.backward_model.Mask_t,self.backward_model.Left_t,self.backward_model.Padding_t=self.backward_model.Data:get_batch(self.backward_model.Target,false)
self.backward_model:model_forward()
self.backward_score=self.backward_model:SentencePpl()
aver_ppl=aver_ppl+self.backward_score:sum();
sen_num=sen_num+self.backward_score:size(1)
self.mode="test"
Batch_error,Batch_instance=self:model_forward()
total_Error=total_Error+Batch_error
n_instance=n_instance+Batch_instance
end
print(total_Error/n_instance)
end
function model:save(batch_n)
local params,_=self.map:parameters()
local file=torch.DiskFile(self.params.save_model_path.."/"..batch_n,"w"):binary();
file:writeObject(params);
file:close()
end
function model:train()
local timer=torch.Timer();
local End,Word_s,Word_t,Mask_s,Mask_t;
local End=0;
local batch_n=1;
self.iter=0;
self:test()
while true do
End=0
self.iter=self.iter+1
local open_train_file=io.open(self.params.train_file,"r")
while End==0 do
batch_n=batch_n+1;
if batch_n%5000==0 then
print("batch_n "..batch_n)
self:test()
self:save(batch_n)
end
local time1=timer:time().real;
End,self.forward_model.Word_s,self.forward_model.Word_t,self.forward_model.Mask_s,self.forward_model.Mask_t,self.forward_model.Left_s,self.forward_model.Left_t,self.forward_model.Padding_s,self.forward_model.Padding_t,self.forward_model.Source,self.forward_model.Target=self.forward_model.Data:read_train(open_train_file)
if End==1 then
break;
end
self.forward_model:model_forward()
self.backward_model.Source={}
self.backward_model.Target={}
for i=1,#self.forward_model.Source do
self.backward_model.Source[i]=self.forward_model.Target[i]:sub(1,-1,2,self.forward_model.Target[i]:size(2)-1);
self.backward_model.Target[i]=torch.cat(torch.Tensor({{self.backward_model.Data.EOS}}),torch.cat(self.forward_model.Source[i],torch.Tensor({self.backward_model.Data.EOT})))
end
self.backward_model.Word_s,self.backward_model.Mask_s,self.backward_model.Left_s,self.backward_model.Padding_s=self.backward_model.Data:get_batch(self.backward_model.Source,true)
self.backward_model.Word_t,self.backward_model.Mask_t,self.backward_model.Left_t,self.backward_model.Padding_t=self.backward_model.Data:get_batch(self.backward_model.Target,false)
self.backward_model:model_forward()
self.backward_score=self.backward_model:SentencePpl()
self.mode="train"
self:model_forward()
local time2=timer:time().real;
end
self:save(batch_n)
self:test()
--break
end
end
return model
|
local io = require("io")
local component = require("component")
local data
for d in component.list("data") do
d = component.proxy(d)
if d.generateKeyPair ~= nil then
data = d
end
end
if data == nil then
print("You need a T3 data card for secure boot!")
return
end
print("generating keypair")
local pub, priv = data.generateKeyPair(256)
print("saving public key to /home/pubkey")
local f, err = io.open("/home/pubkey","wb")
if f ~= nil then
f:write(pub.serialize())
f:close()
else
print("could not save the keys: "..err)
return
end
print("saving private key to /home/privkey")
f, err = io.open("/home/privkey","wb")
if f ~= nil then
f:write(priv.serialize())
f:close()
else
print("could not save the keys: "..err)
return
end
|
--ownerdraw: Owner-draw control functions
setfenv(1, require'winapi')
require'winapi.window'
require'winapi.wingdi'
ffi.cdef [[
typedef struct tagDRAWITEMSTRUCT {
UINT CtlType;
UINT CtlID;
UINT itemID;
UINT itemAction;
UINT itemState;
HWND hwndItem;
HDC hDC;
RECT rcItem;
ULONG_PTR itemData;
} DRAWITEMSTRUCT, *LPDRAWITEMSTRUCT;
]]
|
game.ReplicatedStorage.Remotes.KickPlayer.OnServerEvent:connect(function(player, playerToKick, reason)
game.Players:FindFirstChild(playerToKick):Kick(reason)
end)
|
--[[
The contents of this file are subject to the Common Public Attribution
License Version 1.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://ultimate-empire-at-war.com/cpal. The License is based on the Mozilla
Public License Version 1.1 but Sections 14 and 15 have been added to cover
use of software over a computer network and provide for limited attribution
for the Original Developer. In addition, Exhibit A has been modified to be
consistent with Exhibit B.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is Ultimate Empire at War.
The Original Developer is the Initial Developer. The Initial Developer of the
Original Code is the Ultimate Empire at War team. All portions of the code
written by the Ultimate Empire at War team are Copyright (c) 2012.
All Rights Reserved. ]]
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/TurboAttackLocation.lua#2 $
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- (C) Petroglyph Games, Inc.
--
--
-- ***** ** * *
-- * ** * * *
-- * * * * *
-- * * * * * * * *
-- * * *** ****** * ** **** *** * * * ***** * ***
-- * ** * * * ** * ** ** * * * * ** ** ** *
-- *** ***** * * * * * * * * ** * * * *
-- * * * * * * * * * * * * * * *
-- * * * * * * * * * * ** * * * *
-- * ** * * ** * ** * * ** * * * *
-- ** **** ** * **** ***** * ** *** * *
-- * * *
-- * * *
-- * * *
-- * * * *
-- **** * *
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
-- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/TurboAttackLocation.lua $
--
-- Original Author: James Yarrow
--
-- $Author: Andre_Arsenault $
--
-- $Change: 55814 $
--
-- $DateTime: 2006/10/02 16:55:52 $
--
-- $Revision: #2 $
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
require("pgevents")
--
-- Plan for corvettes to exploit their anti-fighter capabilities while using turbo or power to weapons.
--
function Definitions()
DebugMessage("%s -- In Definitions", tostring(Script))
Category = "Turbo_Attack_Location"
TaskForce = {
-- First Task Force
{
"MainForce"
,"DenyHeroAttach"
,"OR_FORAY_CLASS | R_VICTORY_FRIGATE | RA_CORELLIAN_CORVETTE | NR_CORELLIAN_CORVETTE | C_MISSILE_FRIGATE | E_IPV_PATROL_CRAFT | E_TARTAN_CRUISER | IR_TARTAN_CRUISER | IR_LANCER_FRIGATE = 1, 3"
}
}
IgnoreTarget = true
AllowEngagedUnits = true
needs_turbo = false
was_attacked = false
DebugMessage("%s -- Done Definitions", tostring(Script))
end
function MainForce_Thread()
BlockOnCommand(MainForce.Produce_Force());
QuickReinforce(PlayerObject, AITarget, MainForce)
MainForce.Enable_Attack_Positioning(false)
-- Move into position while avoiding threat and without stopping for attacks on the way
needs_turbo = true
Try_Ability(MainForce, "Turbo")
BlockOnCommand(MainForce.Move_To(AITarget))
MainForce.Activate_Ability("Turbo", false)
needs_turbo = false
-- Clear out the area, while it remains favorable for this type of attack.
MainForce.Set_As_Goal_System_Removable(false)
while (EvaluatePerception("Good_Turbo_Attack_Location_Opportunity", PlayerObject, AITarget) > 0) do
enemy = Find_Nearest(MainForce, "SmallShip", PlayerObject, false)
--enemy = Find_Nearest(MainForce, "Fighter", PlayerObject, false)
if TestValid(enemy) then -- FIX and (MainForce.Get_Distance(enemy) < 1000) then
BlockOnCommand(MainForce.Attack_Target(enemy))
else
break
end
end
-- Try to flee to a safe spot after the tactical strike
if was_attacked then
escape_loc = FindTarget(MainForce, "Space_Area_Is_Hidden", "Tactical_Location", 1.0, 5000.0)
if escape_loc then
needs_turbo = true
MainForce.Activate_Ability("Turbo", true)
BlockOnCommand(MainForce.Move_To(escape_loc))
end
end
ScriptExit()
end
-- Make sure that units don't sit idle at the end of their move order, waiting for others
function MainForce_Unit_Move_Finished(tf, unit)
if Attacking and not unit.Has_Attack_Target() then
DebugMessage("%s -- %s reached end of move, giving new order", tostring(Script), tostring(unit))
-- Assist the tf with whatever is holding it up
kill_target = FindDeadlyEnemy(tf)
if TestValid(kill_target) then
unit.Attack_Target(kill_target)
else
unit.Attack_Move(tf)
end
end
end
-- Try to recover use of turbo or power to weapons if it was lost while we were trying to use it.
function MainForce_Unit_Ability_Ready(tf, unit, ability)
--MessageBox("%s -- Recovering %s for %s!", tostring(Script), ability, tostring(unit))
if ability == "Turbo" and needs_turbo then
unit.Activate_Ability("Turbo", true)
end
-- Default handler behavior is still desired
Default_Unit_Ability_Ready(tf, unit, ability)
end
-- Register if we were attacked, and use default behavior as well.
function MainForce_Unit_Damaged(tf, unit, attacker, deliberate)
if deliberate then
was_attacked = true
end
-- Default handler behavior is still desired
Default_Unit_Damaged(tf, unit, attacker, deliberate)
end
|
--
-- Called when we've received a call from a client who wants to edit
-- a particular entity.
--
function GM:VariableEdited( ent, ply, key, val, editor )
if ( !IsValid( ent ) ) then return end
if ( !IsValid( ply ) ) then return end
--
-- Check with the gamemode that we can edit the entity
--
local CanEdit = hook.Run( "CanEditVariable", ent, ply, key, val, editor )
if ( !CanEdit ) then return end
--
-- Actually apply the edited value
--
ent:EditValue( key, val )
end
--
-- Your gamemode should use this hook to allow/dissallow editing
-- By default only admins can edit entities.
--
function GM:CanEditVariable( ent, ply, key, val, editor )
return ply:IsAdmin()
end
|
local LifeBar = {}
function LifeBar:load()
self.texture = "/assets/LifeBar.png"
self.lifebar_texture = love.graphics.newImage(self.texture)
self.w = 75
self.h = 18
end
function LifeBar:draw()
love.graphics.draw(self.lifebar_texture, 230, 60, 0, 3, 3, self.w, self.h)
end
return LifeBar
|
-- =====================================================
-- wlog: an example of lua logger
--
-- author: di carlo walter
--
-- date: july/august 2016
--
-- wlog.set_level( <level> ) -- set level of all modules to <level>
-- wlog.<mod>.<level> ( <msg> ) -- log <msg> if <level> is active
-- wlog.<mod>.<level>.writer = wlog.writers.<writer> -- set single writer
-- wlog.<mod>.<level>.writer = { wlog.writers.<writer1>, wlog.writers.<writer2>, ...} -- set group of writers
-- wlog.<mod>.<level> ( ) -- true if <level> is active, otherwise false
-- wlog.<mod> ( <level> ) -- set <mod>'s level to <level>
-- wlog.<mod> ( ) -- get <mod>'s level
-- wlog.<level> () -- is equivalent to wlog.GEN.<level> ()
-- wlog.<mod>.<level> ( wlog.<mod>.<level>() and <msg> ) -- log <msg> if <level> is active
-- wlog.<mod> ( wlog.<mod>.<level>() and <msg> ) -- log <msg> if <level> is active
-- if wlog.<mod>.<level>() then wlog.<mod>(<msg1>); wlog.<mod>(<msg2>); end -- log set of messages using contextual level
-- if wlog.<mod>.<level>{"tag1",...} then wlog.<mod>(<msg1>); wlog.<mod>(<msg2>); end -- log set of messages using contextual level
-- wlog.<mod> ( wlog.<mod>.<level>{"tag1",...} and <msg> ) -- log <msg> if <level> is active
-- wlog.<mod>.<level> ( msg, "tag" ) .. single tag
-- wlog.<mod>.<level> ( msg, {"tag1","tag2", ...} ) -- tags in or expression
-- wlog.<mod>.<level> {"tag1","tag2", ...} -- tags in or expression
-- wlog() -- equivalent to wlog.GEN() which return level of GEN module
-- wlog(<level>) -- equivalent to wlog.GEN(<level>)
-- wlog.tags{<tag1>,...} -- start logging section associated to <tag1>,...
-- wlog.tags() -- get logging section's tags
-- wlog.tags{} -- stop logging section with associated tags <tag1>,...
-- wlog.config{<config>} -- set configuration
-- wlog.config() -- get configuration
-- wlog.plugin(<plugin>) -- set wlog plugin
-- wlog.fromlevel(<internal_level) -- get external representation of level
-- wlog.tolevel (<external_level) -- get internal representation of level
-- wlog.frommodule(<internal_module) -- get external representation of module
-- wlog.tomodule (<external_module) -- get internal representation of module
--
-- TODO:
-- wlog.<mod>.set_level ( level )
-- wlog.<mod>.<level> ( msg, "tag expression" )
-- wlog.<mod>.<level> { tags="tag expression", msg }
-- =====================================================
local ok,dbg = pcall(require,"debugger")
if not ok then
dbg = function() end
end
dbg = function() end -- disable debugger
local debug = false
local _plugin = nil
local function prequire(m)
local ok, res = pcall(require, m)
if not ok then return nil, res end -- return error
return res
end
local core = prequire("wlog.core")
local inspect = prequire("inspect")
local tostring = inspect and function (arg)
if type(arg) == "table" then return inspect(arg) end
return tostring(arg)
end or tostring
if core == nil then
core = {
enums = {
WLOG_LEVELS = {
LOG_ERR = 1,
LOG_WARN = 2,
LOG_INFO = 3,
LOG_TRACE = 4,
LOG_DEBUG = 5,
},
WLOG_FUNCTS = {
LOG_GEN = 1,
LOG_ALM = 2,
LOG_SYS = 3,
LOG_SQL = 4,
LOG_GUI = 5,
LOG_SRV = 6,
LOG_WEB = 7,
}
}
}
end
local defaults = {
module = "GEN",
level = "INFO",
writer = "con",
}
local wlog = {}
local ctags = {} -- contextual tags
local levels = {}
local modules = {}
local writers = {}
local function is_level( level )
for k,v in pairs(levels) do
if v == level then return true end
end
return false
end
local function is_module(module)
return modules[module] ~= nil
end
local function add_module(module)
assert(type(module) == "string")
local max = 0
for k,v in pairs(modules) do
if k == module then
return modules[module]
end
if v.id > max then max = v.id end
end
modules[module] = {
id = max + 1,
name = module
}
if debug then print("Added module: "..tostring(modules[module])) end
return modules[module]
end
local fromlevel = function (level)
assert(type(level)=="string","Wrong level")
return string.sub(level,5)
end
local tolevel = function (level)
assert(type(level)=="string","Wrong level")
return "LOG_"..level
end
local frommodule = function (module)
assert(type(module)=="string","Wrong module")
return string.sub(module,5)
end
local tomodule = function (module)
assert(type(module)=="string","Wrong module")
return "LOG_"..module
end
local function is_in(tags,tag)
assert(type(tags) == "table")
assert(type(tag) == "string")
for _,t in ipairs(tags) do
if t == tag then return true end
end
return false
end
local con = function (txt)
if txt and type(txt) == "string" then
print("con: "..txt)
end
end
local ram = function (txt)
if txt and type(txt) == "string" then
print("ram: "..txt)
end
end
---------------------------------------------------------------------------
-- sto is a wlog writer that rolls over the logfile
-- once it has reached a certain size limit. It also mantains a
-- maximum number of log files.
--
-- sto is based on code present in the module rollfile
--
-- @author Tiago Cesar Katcipis (tiagokatcipis@gmail.com)
--
-- @copyright 2004-2013 Kepler Project
---------------------------------------------------------------------------
--
local rollfile = {
config = {
filename = "log.txt",
maxSize = 50000,
maxIndex = 5
}
}
local function openFile(self)
if self.file then
return nil, string.format("file `%s' is already open", self.filename)
end
self.file = io.open(self.filename, "a")
if not self.file then
return nil, string.format("file `%s' could not be opened for writing", self.filename)
end
self.file:setvbuf ("line")
return self.file
end
local rollOver = function (self)
for i = self.maxIndex - 1, 1, -1 do
-- files may not exist yet, lets ignore the possible errors.
os.rename(self.filename.."."..i, self.filename.."."..i+1)
end
self.file:close()
self.file = nil
local _, msg = os.rename(self.filename, self.filename..".".."1")
if msg then
return nil, string.format("error %s on log rollover", msg)
end
return openFile(self)
end
local openRollingFileLogger = function (self)
if not self.file then
return openFile(self)
end
local filesize = self.file:seek("end", 0)
if (filesize < self.maxSize) then
return self.file
end
return rollOver(self)
end
local sto = function (txt)
local f, err = openRollingFileLogger(rollfile.config)
if not f then
print("ERROR: "..err)
return nil
end
if txt and type(txt) == "string" then
f:write("sto: "..txt.."\n")
end
end
---------------------------------------------------------------------------
--
local nul = function (txt)
end
local function is_writer(func)
for name,writer in pairs(writers) do
if func == writer then return true end
end
return false
end
local eval = function (module,level,tags,modules,context)
if module.level.value >= level.value then
local wrt = rawget(context,"_writer")
return true, wrt
end
local res = false
local writer = nil
if tags then
for _,tag in ipairs(tags) do
-- if any tag has level lower than the current one then the text can be logged
--if modules[tag].level.value <= module.level.value then
if modules[tag].level.value >= level.value then
res = true
writer = rawget(context,"_writer")
break
end
end
end
return res, writer
end
local level_mt = {
__call = function(self,...)
rawset(self.module,"_last",self.level)
rawset(self.module,"_last_tags",nil)
local n = select("#",...)
if n == 0 then
local eval_res, eval_writer = eval(self.module,self.level,nil,wlog,self)
return eval_res
end
local tags = nil
local ntags = 0
if n == 1 then
local par = select(1,...)
local tpar = type(par)
if tpar == "table" then
-- add modules
ntags = 0
tags = {}
for _,tag in ipairs(par) do
if tags == nil then tags = {} end
add_module(tag)
if is_in(tags,tag) == false then
tags[#tags + 1] = tag
ntags = ntags + 1
end
end
end
elseif n > 1 then
tags = select(2,...)
local ttags = type(tags)
if ttags == "string" then
-- add module
ntags = 1
add_module(tags)
tags = { tags } -- put in an array
elseif ttags == "table" then
-- add modules
ntags = 0
for _,tag in ipairs(tags) do
add_module(tag)
ntags = ntags + 1
end
end
end
if ctags and #ctags > 0 then
for _,tag in ipairs(ctags) do
add_module(tag)
if tags == nil then tags = {} end
if is_in(tags,tag) == false then
tags[#tags + 1] = tag
ntags = ntags + 1
end
end
end
if tags then
rawset(self.module,"_last_tags",tags)
end
-- evaluate status considering also the tags
local eval_res, eval_writer = eval(self.module,self.level,tags,wlog,self)
if eval_res == false then
return false
end
-- ok, the text can be logged
local par = select(1,...)
local tpar = type(par)
if tpar == "string" then
local msg = self.module.name..": level="..self.level.name.." msg="..par
if ntags > 0 then
for _,tag in ipairs(tags) do
msg = msg .. " #"..tag
end
end
-- use writers of the module
local writer = rawget(self,"_writer")
local writer = eval_writer
if type(writer) == "function" then
writer(msg)
elseif type(writer) == "table" then
for _,out in ipairs(writer) do
if out then out(msg)
end
end
end
return true
elseif tpar == "boolean" then
return par
elseif tpar == "table" and ntags > 0 then
return true
end
return false
end,
__index = function(self,key)
--assert(writers[key] or key == "writer","Wrong writer: "..key)
if key == "writer" and rawget(self,"_writer") == nil then
rawset(self,"_writer",writers[defaults.writer])
end
--return self._writer
local writer = rawget(self,"_writer") -- self._writer
if type(writer) == "table" then
writer = writer[1]
end
return writer
end,
__newindex = function(self,key,val)
assert(type(key)=="string","Wrong key: "..tostring(key))
assert(key=="module" or key=="writer" or key=="level","Wrong key: "..tostring(key))
--assert(val~=nil,"Wrong value: nil")
if key=="writer" then
local wt = type(val)
--assert(wt=="function" or wt=="table")
assert(wt=="function" or wt=="table" or wt=="nil")
-- check it is a valid writer
if wt == "function" then
assert(is_writer(val),"Wrong writer")
elseif wt == "table" then
for _,w in ipairs(val) do
assert(type(w) == "function", "Wrong writer")
assert(is_writer(w), "Wrong writer")
end
--else
-- assert(false,"Wrong writer type")
end
rawset(self,"_writer", val)
return
end
if debug then print("key="..tostring(key).. " val="..tostring(val)) end
rawset(self,key,val)
end
}
local module_mt = {
__call = function(self,...)
local n = select("#",...)
if debug then print("Module: "..self.name.." Level: "..tostring(self.level)) end
if n == 0 then
return self.level
end
local par = select(1,...)
local tpar = type(par)
if tpar == "table" then
assert( is_level(par), "wrong level: "..tostring(par))
self.level = par
elseif tpar == "string" then
-- message to log using the last level/tags
local level = rawget(self,"_last")
local tags = rawget(self,"_last_tags")
if level == nil then return end -- no know message level
local lvl = fromlevel(level.name)
if tags then
self[lvl](par,tags)
else
self[lvl](par)
end
return self.level
end
end,
__index = function(self,key)
assert(type(key)=="string","Wrong key type for: "..tostring(key))
assert(levels[key]~=nil,"Wrong level: "..tostring(key))
self[key] = setmetatable({}, level_mt)
self[key].level = levels[key]
--self[key].writer = writers[defaults.writer]
self[key].writer = nil
self[key].module = self
return self[key]
end,
}
local wlog_mt = {
__call = function(self,...)
local n = select("#",...)
if n == 0 then
return rawget(self[defaults.module],"level")
end
local par = select(1,...)
return self[defaults.module](par)
end,
__index = function(self,key)
assert(type(key)=="string","Wrong key type for: "..tostring(key))
if is_module(key) == false then
add_module(key)
end
self[key] = setmetatable({}, module_mt)
self[key].level = levels[defaults.level]
self[key].name = key
self[key].id = modules[key]["id"]
return self[key]
end,
}
local function is_ctag(tag)
for _,t in ipairs(ctags) do
if t == tag then return true end
end
return false
end
local function tags(list)
assert(list == nil or type(list)=="table","Wrong list of tags")
if list == nil then
return ctags
end
if #list == 0 then
ctags = {}
return ctags
end
-- check if list of modules need to be updated
for _,tag in ipairs(list) do
if is_ctag(tag) == false then
ctags[#ctags+1] = tag
end
end
end
local function set_level(level)
assert(type(level) == "table","Wrong level: "..tostring(level))
assert(level.name,"Missing level's name")
assert(level.value,"Missing level's value")
assert(core.enums.WLOG_LEVELS[level.name],"Unknown level")
assert(core.enums.WLOG_LEVELS[level.name] == level.value,
"Wrong level - expected "..core.enums.WLOG_LEVELS[level.name].." got "..level.value)
rawset(wlog,"level",level)
if debug then print("wlog.level = "..wlog.level.name) end
for k,v in pairs(wlog.modules)
do
--local mod = frommodule(k)
--if wlog[mod] then
-- rawset(wlog[mod],"level",level)
--end
if wlog[k] then
rawset(wlog[k],"level",level)
end
end
end
local _reset = function()
ctags = {} -- contextual tags
levels = {}
modules = {}
writers = {}
for k,v in pairs(wlog) do
if type(v) == "table" then
rawset(wlog,k,nil)
end
end
end
local function _init_enums()
-- levels defaults
for k,v in pairs(core.enums.WLOG_LEVELS)
do
local lvl = fromlevel(k)
dbg("k = "..tostring(k).." lvl = "..tostring(lvl))
levels[lvl] = {
name = k,
value = v,
}
end
if debug then print("levels:\n",tostring(levels)) end
-- modules defaults
for k,v in pairs(core.enums.WLOG_FUNCTS)
do
local mod = frommodule(k)
modules[mod] = {
id = v,
name = k
}
end
if debug then print("modules:\n",tostring(modules)) end
end
local function _init_writers()
writers.con = con
writers.ram = ram
writers.sto = sto
writers.nul = nul
if debug then print("writers:\n",tostring(writers)) end
end
local function plugin(wlog_plugin)
dbg("begin of wlog_plugin")
if wlog_plugin == nil then return _plugin end
assert(wlog_plugin and type(wlog_plugin)=="table","Wrong plugin")
assert(wlog_plugin.is_wlog_plugin,"Wrong plugin")
assert(wlog_plugin.wlog_plugin_name,"Wrong plugin")
_reset()
--if wlog_plugin.setup then wlog_plugin.setup(wlog) end
if wlog_plugin.enums then
assert(wlog_plugin.enums.WLOG_FUNCTS,"Wrong enums")
assert(wlog_plugin.enums.WLOG_LEVELS,"Wrong enums")
core.enums = wlog_plugin.enums
dbg("after enums setup")
end
if wlog_plugin.fromlevel then fromlevel = wlog_plugin.fromlevel end
if wlog_plugin.tolevel then tolevel = wlog_plugin.tolevel end
if wlog_plugin.frommodule then frommodule = wlog_plugin.frommodule end
if wlog_plugin.tomodule then tomodule = wlog_plugin.tomodule end
wlog.fromlevel = fromlevel
wlog.tolevel = tolevel
wlog.frommodule = frommodule
wlog.tomodule = tomodule
dbg("before _init_enums")
_init_enums()
dbg("before _init_writers")
_init_writers()
if wlog_plugin.con then writers.con = wlog_plugin.con end
if wlog_plugin.ram then writers.ram = wlog_plugin.ram end
if wlog_plugin.sto then writers.sto = wlog_plugin.sto end
--if wlog_plugin.setup then wlog_plugin.setup() end
if wlog_plugin.config then config = wlog_plugin.config end
if wlog_plugin.defaults then
local defs = wlog_plugin.defaults
if defs.module then defaults.module = defs.module end
if defs.level then defaults.level = defs.level end
if defs.writer then defaults.writer = defs.writer end
end
if wlog_plugin.eval then eval = wlog_plugin.eval end
_plugin = wlog_plugin
wlog.writers = writers
wlog.levels = levels
wlog.modules = modules
wlog.tags = tags
wlog.config = config
dbg("before set_level")
set_level(levels[defaults.level])
for k,v in pairs(core.enums.WLOG_LEVELS)
do
local lvl = fromlevel(k)
wlog[lvl] = wlog[defaults.module][lvl]
end
if wlog_plugin.setup then wlog_plugin.setup(wlog) end
if debug then print("wlog: pluged-in: "..wlog_plugin.wlog_plugin_name) end
return true
end
local config = function (cfg)
-- {
-- enums = <wlog enums>,
-- defaults = <wlog defaults>,
-- }
if cfg then
assert(type(cfg) == "table", "Wrong config: "..tostring(cfg))
_reset()
if cfg.defaults then defaults = cfg.defaults end -- TODO: assert defaults struct
if cfg.enums then core.enums = cfg.enums end -- TODO: assert enums struct
_init_enums()
_init_writers()
wlog.writers = writers
wlog.levels = levels
wlog.modules = modules
wlog.tags = tags
for k,v in pairs(core.enums.WLOG_LEVELS)
do
local lvl = fromlevel(k)
wlog[lvl] = wlog[defaults.module][lvl]
end
set_level(levels[defaults.level])
else
local cfg = {}
cfg.defaults = defaults
cfg.enums = core.enums
return cfg
end
end
local function _init()
wlog = {}
_init_enums()
_init_writers()
wlog = setmetatable(wlog,wlog_mt)
wlog._VERSION = "1.0"
wlog.set_level = set_level
wlog.writers = writers
wlog.levels = levels
wlog.modules = modules
wlog.tags = tags
wlog.plugin = plugin
wlog.config = config
wlog.fromlevel = fromlevel
wlog.tolevel = tolevel
wlog.frommodule = frommodule
wlog.tomodule = tomodule
wlog.is_module = is_module
wlog.is_writer = is_writer
wlog.add_module = add_module
set_level(levels[defaults.level])
for k,v in pairs(core.enums.WLOG_LEVELS)
do
local lvl = fromlevel(k)
wlog[lvl] = wlog[defaults.module][lvl]
end
end
_init()
return wlog
|
--ベアルクティ-メガタナス
--Scripted by mallu11
function c100416031.initial_effect(c)
--spsummon
local e1=aux.AddUrsarcticSpSummonEffect(c)
e1:SetDescription(aux.Stringid(100416031,0))
e1:SetCountLimit(1,100416031)
--position
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(100416031,1))
e2:SetCategory(CATEGORY_POSITION)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,100416031+100)
e2:SetCondition(c100416031.poscon)
e2:SetTarget(c100416031.postg)
e2:SetOperation(c100416031.posop)
c:RegisterEffect(e2)
end
if Auxiliary.AddUrsarcticSpSummonEffect==nil then
--Ursarctic common summon from hand effect
function Auxiliary.AddUrsarcticSpSummonEffect(c)
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_HAND)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_MAIN_END)
e1:SetCondition(Auxiliary.UrsarcticSpSummonCondition)
e1:SetCost(Auxiliary.UrsarcticSpSummonCost)
e1:SetTarget(Auxiliary.UrsarcticSpSummonTarget)
e1:SetOperation(Auxiliary.UrsarcticSpSummonOperation)
c:RegisterEffect(e1)
return e1
end
function Auxiliary.UrsarcticSpSummonCondition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()==PHASE_MAIN1 or Duel.GetCurrentPhase()==PHASE_MAIN2
end
function Auxiliary.UrsarcticReleaseFilter(c,tp)
return c:IsLevelAbove(7) and (c:IsControler(tp) and c:IsLocation(LOCATION_HAND) or c:IsFaceup() and c:IsControler(1-tp))
end
function Auxiliary.UrsarcticExCostFilter(c,tp)
return c:IsAbleToRemoveAsCost() and (c:IsHasEffect(100416036,tp) or c:IsHasEffect(100416038,tp))
end
function Auxiliary.UrsarcticSpSummonCost(e,tp,eg,ep,ev,re,r,rp,chk)
local g1=Duel.GetReleaseGroup(tp,true):Filter(Auxiliary.UrsarcticReleaseFilter,e:GetHandler(),tp)
local g2=Duel.GetMatchingGroup(Auxiliary.UrsarcticExCostFilter,tp,LOCATION_GRAVE,0,nil,tp)
g1:Merge(g2)
if chk==0 then return g1:GetCount()>0 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE)
local tc=g1:Select(tp,1,1,nil):GetFirst()
local te=tc:IsHasEffect(100416036,tp) or tc:IsHasEffect(100416038,tp)
if te then
te:UseCountLimit(tp)
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT+REASON_REPLACE)
else
Duel.Release(tc,REASON_COST)
end
end
function Auxiliary.UrsarcticSpSummonTarget(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function Auxiliary.UrsarcticSpSummonOperation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetTargetRange(1,0)
e1:SetTarget(Auxiliary.UrsarcticSpSummonLimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function Auxiliary.UrsarcticSpSummonLimit(e,c)
return c:IsLevel(0)
end
end
function c100416031.confilter(c)
return c:IsFaceup() and c:IsSetCard(0x261)
end
function c100416031.poscon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c100416031.confilter,tp,LOCATION_MZONE,0,1,e:GetHandler())
end
function c100416031.posfilter(c)
return c:IsFaceup() and c:IsCanTurnSet()
end
function c100416031.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c100416031.posfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c100416031.posfilter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_POSCHANGE)
local g=Duel.SelectTarget(tp,c100416031.posfilter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0)
end
function c100416031.posop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.ChangePosition(tc,POS_FACEDOWN_DEFENSE)
end
end
|
package.path = "../../lualib/?.lua;"..package.path
local utils = require "utils"
local mjlib = require "mjlib"
local split_table = {
{min = 1, max = 9, chi = true},
{min = 10, max = 18, chi = true},
{min = 19, max = 27, chi = true},
{min = 28, max = 34, chi = false}
}
local check_table = {
[0] = require "no_gui_table",
[1] = require "one_gui_table",
[2] = require "two_gui_table",
[3] = require "three_gui_table",
[4] = require "four_gui_table"
}
local check_eye_table = {
[0] = require "no_gui_eye_table",
[1] = require "one_gui_eye_table",
[2] = require "two_gui_eye_table",
[3] = require "three_gui_eye_table",
[4] = require "four_gui_eye_table"
}
local check_feng_table = {
[0] = require "no_gui_feng_table",
[1] = require "one_gui_feng_table",
[2] = require "two_gui_feng_table",
[3] = require "three_gui_feng_table",
[4] = require "four_gui_feng_table"
}
local check_feng_eye_table = {
[0] = require "no_gui_feng_eye_table",
[1] = require "one_gui_feng_eye_table",
[2] = require "two_gui_feng_eye_table",
[3] = require "three_gui_feng_eye_table",
[4] = require "three_gui_feng_eye_table",
}
local M = {}
function M.check_7dui(hand_cards, waves)
if #waves > 0 then return false end
for _,c in ipairs(hand_cards) do
if c % 2 ~= 0 then
return false
end
end
return true
end
function M.check_pengpeng()
end
function M.get_hu_info(hand_cards, waves, gui_index)
local hand_cards_tmp = {}
for i,v in ipairs(hand_cards) do
hand_cards_tmp[i] = v
end
local gui_num = hand_cards_tmp[gui_index]
hand_cards_tmp[gui_index] = 0
local splited_tbl = M.split_info(hand_cards_tmp, gui_num)
if not splited_tbl then
return false
end
return M.check_probability(splited_tbl, gui_num)
end
function M.check_table(key, gui_num, eye, chi)
local tbl
if chi then
if eye then
tbl = check_eye_table[gui_num]
else
tbl = check_table[gui_num]
end
else
if eye then
tbl = check_feng_eye_table[gui_num]
else
tbl = check_feng_table[gui_num]
end
end
if tbl then
return tbl[key]
end
end
function M.list_probability(gui_num, num, key, chi)
--nprint("gui_num", gui_num, "num",num, "key", key)
local t = {}
for i=0, gui_num do
local yu = (num + i)%3
if yu == 0 then
if M.check_table(key, i, false, chi) then
table.insert(t, {eye = false, gui_num = i})
end
elseif yu == 2 then
if M.check_table(key, i, true, chi) then
table.insert(t, {eye = true, gui_num = i})
end
end
end
--utils.print_array(t)
return t
end
-- 根据花色切分
function M.split_info(t, gui_num)
local ret = {}
for _,v in ipairs(split_table) do
local key = 0
local num = 0
for i=v.min,v.max do
key = key*10 + t[i]
num = num + t[i]
end
if num > 0 then
local t = M.list_probability(gui_num, num, key, v.chi)
if #t == 0 then
return false
end
table.insert(ret, t)
end
end
--utils.print_array(ret)
return ret
end
function M.check_probability_sub(splited_table, info, level)
for _,v in ipairs(splited_table[level]) do
repeat
if info.eye and v.eye then
break
end
if info.gui_num < v.gui_num then
break
end
if level < info.c then
info.gui_num = info.gui_num - v.gui_num
local old_eye = info.eye
info.eye = old_eye or v.eye
if M.check_probability_sub(splited_table, info, level + 1) then
return true
end
info.eye = old_eye
info.gui_num = info.gui_num + v.gui_num
break
end
if not info.eye and not v.eye and info.gui_num < 2 + v.gui_num then
break
end
return true
until(true)
end
return false
end
function M.check_probability(splited_table, gui_num)
local c = #splited_table
-- 全是鬼牌
if c == 0 then
return true
end
-- 只有一种花色的牌和鬼牌
if c == 1 then
return true
end
-- 组合花色间的组合,如果能满足组合条件,则胡
for i,v in ipairs(splited_table[1]) do
local info = {
eye = v.eye,
gui_num = gui_num - v.gui_num,
c = c
}
local ret = M.check_probability_sub(splited_table, info, 2)
if ret then
return true
end
end
return false
end
return M
|
---
-- FDMM Facility Module.
-- @module FDMM_Facility
env.info("---FDMM_Facility Start---")
--- FDMM facility module.
fdmm.facility = {}
do -- FDMMFacility
--- Facility base class that manages a facility in a territory.
-- @type FDMMFacility
FDMMFacility = {}
FDMMFacility.__index = FDMMFacility
setmetatable(FDMMFacility, {
__call = function (cls, ...)
return cls.new(...)
end
})
--- Facility constructor.
-- @param #string name Facility name.
-- @param DCS#Vec2 centerPoint Center point of facility.
-- @param #string territoryName Territory name this facility belongs to.
-- @return #FDMMFacility New instance of #FDMMFacility.
function FDMMFacility.new(name, centerPoint, territoryName)
local self = setmetatable({}, FDMMFacility)
self.name = name
self.centerPoint = centerPoint
self.territoryName = territoryName
return self
end
function FDMMFacility:serialize(encoder)
-- TODO: me.
end
function FDMMFacility:deserialize(decoder)
-- TOD: me.
end
--- Builds facility from initial placement of map elements nearby according to setup parameters.
function FDMMFacility:buildFacility()
-- meant to be overridden by derived classes
end
--- Gets facility type of facility.
-- @return #Enums.FacilityType Facility type.
function FDMMFacility:getFacilityType()
-- meant to be overridden by derived classes
return nil
end
end -- /FDMMFacility
env.info("---FDMM_Facility End---")
|
local meta = require "bluegate.meta"
local pretty = require 'pl.pretty'
local lapp = [[
Usage: bluegate version [OPTIONS]
Print Bluegate's version. With the -a option, will print
the version of all underlying dependencies.
Options:
-a,--all get version of all dependencies
]]
local str = [[
Bluegate: %s
ngx_lua: v0.10.11 released
nginx: 1.13.8
Lua: 5.1
]]
local function execute(args)
if args.all then
print(string.format(str,
meta._VERSION
))
else
print(meta._VERSION)
end
end
return {
lapp = lapp,
execute = execute
}
|
#!/usr/bin/env texlua
-- Build script for fduthesis.
module = "fduthesis"
checkengines = {"xetex", "luatex"}
checkopts = "-interaction=batchmode"
sourcefiles = {"source/*.dtx"}
installfiles = {"*.cls", "*.sty", "*.def"}
-- typesetdeps = {"source/latexmkrc."}
typesetexe = "xelatex"
typesetfiles = {"fduthesis.dtx"}
unpackfiles = {"fduthesis.dtx"}
unpackexe = "xetex"
|
local fs = require("filesystem")
local shell = require("shell")
local term = require("term")
local dirsArg, ops = shell.parse(...)
if #dirsArg == 0 then
table.insert(dirsArg, ".")
end
if ops.help then
print([[Usage: ls [OPTION]... [FILE]...
-a, --all do not ignore entries starting with .
--full-time with -l, print time in full iso format
-h, --human-readable with -l and/or -s, print human readable sizes
--si likewise, but use powers of 1000 not 1024
-l use a long listing format
-r, --reverse reverse order while sorting
-R, --recursive list subdirectories recursively
-S sort by file size
-t sort by modification time, newest first
-X sort alphabetically by entry extension
-1 list one file per line
-p append / indicator to directories
-M display Microsoft-style file and directory count after listing
--no-color Do not colorize the output (default colorized)
--help display this help and exit
For more info run: man ls]])
return 0
end
local ec = 0
local gpu = term.gpu()
local fOut = term.isAvailable() and io.output().tty
local function perr(msg) io.stderr:write(msg,"\n") ec = 2 end
local function _path(n,i) return n[i]:sub(1, 1) == '/' and "" or n.path end
local function _name(n,i) return ops.p and n[i] or n[i]:gsub("/+$", "") end
local function _sort_name(n,i) return _name(n,i):gsub("^%.","") end
local function _fullPath(n,i) return fs.concat(_path(n,i),_name(n,i)) end
local function _isLink(n,i) return (fs.isLink(_fullPath(n,i))) end
local function _linkPath(n,i) return select(2,fs.isLink(_fullPath(n,i))) end
local function _isDir(n,i) return fs.isDirectory(_fullPath(n,i)) end
local function _size(n,i) return _isLink(n,i) and 0 or fs.size(_fullPath(n,i)) end
local function _time(n,i) return fs.lastModified(_fullPath(n,i)) end
local function _ext(n,i) return _name(n,i):match("(%.[^.]+)$") or "" end
local function toArray(i) local r={} for n in i do r[#r+1]=n end return r end
local restore_color = function() end
local set_color = function() end
local prev_color
local function colorize(n,i) return prev_color end
if fOut and not ops["no-color"] then
local LSC = os.getenv("LS_COLORS")
if type(LSC) == "string" then
LSC = require("serialization").unserialize(LSC)
end
if not LSC then
perr("ls: unparsable value for LS_COLORS environment variable")
else
prev_color = gpu.getForeground()
restore_color = function() gpu.setForeground(prev_color) end
colorize=function(n,i) return
_isLink(n,i) and LSC.LINK or
_isDir(n,i) and LSC.DIR or
LSC['*'.._ext(n,i)] or LSC.FILE or prev_color
end
set_color=function(c)
if gpu.getForeground() ~= c then
io.stdout:flush()
gpu.setForeground(c)
end
end
end
end
local msft={reports=0,proxies={}}
function msft.report(files, dirs, used, proxy)
local free = proxy.spaceTotal() - proxy.spaceUsed()
restore_color()
local pattern = "%5i File(s) %11i bytes\n%5i Dir(s) %11s bytes free\n"
io.write(string.format(pattern, files, used, dirs, tostring(free)))
end
function msft.tail(n)
local x = fs.get(n.path)
if not x then return end
local u,f,d=0,0,0
for i=1,#n do
if _isDir(n,i) then d=d+1
else f=f+1;u=u+_size(n,i) end
end
msft.report(f,d,u,x)
local ps=msft.proxies
ps[x]=ps[x]or{files=0,dirs=0,used=0}
local p=ps[x]
p.files=p.files+f
p.dirs=p.dirs+d
p.used=p.used+u
msft.reports=msft.reports+1
end
function msft.final()
if msft.reports < 2 then return end
local g = {}
for p,r in pairs(msft.proxies) do g[#g+1]={proxy=p,report=r} end
restore_color()
print("Total Files Listed:")
for _,p in ipairs(g) do
if #g>1 then print("As pertaining to: "..p.proxy.address) end
msft.report(p.report.files, p.report.dirs, p.report.used, p.proxy)
end
end
if not ops.M then
msft.tail=function()end
msft.final=function()end
end
local function nod(n)
return n and (tostring(n):gsub("(%.[0-9]+)0+$","%1")) or "0"
end
local function formatSize(size)
if not ops.h and not ops['human-readable'] and not ops.si then
return tostring(size)
end
local sizes = {"", "K", "M", "G"}
local unit = 1
local power = ops.si and 1000 or 1024
while size > power and unit < #sizes do
unit = unit + 1
size = size / power
end
return nod(math.floor(size*10)/10)..sizes[unit]
end
local function pad(txt)
txt = tostring(txt)
return #txt >= 2 and txt or "0"..txt
end
local day_names={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday",
"Saturday"}
local month_names={"January","February","March","April","May","June","July",
"August","September","October","November","December"}
local function formatDate(epochms)
local d = os.date("*t", epochms)
return ops['full-time'] and
string.format("%s-%s-%s %s:%s:%s",d.year,pad(nod(d.month)),pad(nod(d.day)),pad(nod(d.hour)),pad(nod(d.min)),pad(nod(d.sec))) or
string.format("%s %+2s %+2s:%+2s",month_names[d.month]:sub(1,3),nod(d.day),pad(nod(d.hour)),pad(nod(d.min)))
end
local function filter(n)
if ops.a then return n end
local s = {path=n.path}
for i,x in ipairs(n) do
if fs.name(_name(n,i)):sub(1,1) ~= "." then s[#s+1]=x end
end
return s
end
local function sort(n)
local once=false
local function ni(v) for i=1,#n do if n[i]==v then return i end end end
local function sorter(_fp)
once=true table.sort(n,function(a,b)return _fp(n,ni(a))>_fp(n,ni(b))end)
end
local rev = ops.r or ops.reverse
if ops.t then sorter(_time) end
if ops.X then sorter(_ext) end
if ops.S then sorter(_size) end
if not once then sorter(_sort_name) rev=not rev end
if rev then
for i=1,#n/2 do n[i],n[#n-i+1]=n[#n-i+1],n[i] end
end
return n
end
local function dig(n, dirs, dir)
if ops.R then
local di = 1
for i=1,#n do
if _isDir(n,i) then
local p=dir..(dir:sub(-1) == "/" and "" or "/")
table.insert(dirs,di,p.._name(n,i))
di=di+1
end
end
end
return n
end
local function wide(n,i)
local t = _isLink(n,i) and 'l' or _isDir(n,i) and 'd' or 'f'
local link_target = _isLink(n,i) and
string.format(" -> %s",_linkPath(n,i)..(_isDir(n,i)and"/"or""))or""
local w = fs.get(_fullPath(n,i)).isReadOnly() and '-' or 'w'
local size = formatSize(_size(n,i))
local modDate = formatDate(_time(n,i))
return string.format("%s-r%s %+7s %s ",t,w,size,modDate),_name(n,i)..link_target
end
local first_display = true
local function display(n)
local mt={}
local lines=setmetatable({},mt)
if ops.l then
lines.n=#n
mt.__index=function(tbl,index)local m,l=wide(n,index)return{{color=prev_color,name=m},{color=colorize(n,index),name=l}}end
elseif ops["1"] or not fOut then
lines.n=#n
mt.__index=function(tbl,index)local m,l=wide(n,index)return{{color=colorize(n,index),name=_name(n,index)}}end
else -- columns
local cols,d,w=0,0,select(3,term.getGlobalArea())-1
local function real(x, y)
local index = y + ((x-1) * d)
return index <= #n and index or nil
end
local function max_name(ci)
local max=0 -- return the width of the max element in ci
for r=1,d do
local ri=real(ci,r)
if not ri then break end
max=math.max(max,_name(n,ri):len())
end
return max
end
local function measure(_cols)
local t=0
for c=1,_cols do t=t+max_name(c)+(c>1 and 2 or 0) end
return t
end
while d<#n do d=d+1 cols=math.ceil(#n/d) if measure(cols)<w then break end end
lines.n=d
mt.__index=function(tbl,di)return setmetatable({},{
__len=function()return cols end,
__index=function(tbl,ci)
local ri=real(ci, di)
if not ri then return end
local nm=_name(n,ri)
return{
color=colorize(n,ri),
name=nm..string.rep(' ',max_name(ci)-#nm+(ci<cols and 2 or 0))
}end})end
end
for li=1,lines.n do
local l=lines[li]
for ei=1,#l do
local e=l[ei]
if not e then break end
first_display = false
set_color(e.color)
io.write(e.name)
end
print()
end
msft.tail(n)
end
local header = function() end
if #dirsArg > 1 or ops.R then
header = function(path)
if not first_display then print() end
restore_color()
io.write(path,":\n")
end
end
local function splitDirsFromFileArgs(dirs)
local trimmed = {}
local files = {}
for _,dir in ipairs(dirs) do
local path = shell.resolve(dir)
if not fs.exists(path) then
perr("cannot access " .. tostring(path) .. ": No such file or directory")
elseif fs.isDirectory(path) then
table.insert(trimmed, dir)
else -- file or link
table.insert(files, dir)
end
end
return files, trimmed
end
local function displayDirList(dirs)
while #dirs > 0 do
local dir = table.remove(dirs, 1)
header(dir)
local path = shell.resolve(dir)
local list, reason = fs.list(path)
if not list then
perr(reason)
else
local n=toArray(list)
n.path=path
display(dig(sort(filter(n)),dirs,dir))
end
end
end
local tr,cp={},{path=os.getenv("PWD")}
for _,dir in ipairs(dirsArg) do
local path = shell.resolve(dir)
if not fs.exists(path) then
perr("cannot access " .. tostring(path) .. ": No such file or directory")
elseif fs.isDirectory(path) then
tr[#tr+1]=dir
else -- file or link
cp[#cp+1]=dir
end
end
io.output():setvbuf("line")
if #cp > 0 then display(sort(cp)) end
displayDirList(tr)
msft.final()
io.output():flush()
io.output():setvbuf("no")
restore_color()
return ec
|
local PANEL = {}
function PANEL:Init()
self.Colour = Color(60,255,105,150)
self.Name = "Connecting..."
self.Ping = 0
self:SetCursor("hand")
self:SetTooltip("Left click to open info card. Right click to copy SteamID.")
end
function PANEL:SetPlayer(player)
self.Colour = team.GetColor(player:Team()) -- Store colour and name micro optomization, other things can be calculated on the go.
self.Name = player:Nick()
self.Player = player
self.Badges = {}
for v,k in pairs(impulse.Badges) do
if k[3](player) then
self.Badges[v] = k
end
end
self.modelIcon = vgui.Create("impulseSpawnIcon", self)
self.modelIcon:SetPos(10,4)
self.modelIcon:SetSize(52,52)
self.modelIcon:SetModel(player:GetModel(), player:GetSkin())
self.modelIcon:SetTooltip(false)
self.modelIcon:SetDisabled(true)
timer.Simple(0, function()
if not IsValid(self) then
return
end
local ent = self.modelIcon.Entity
if IsValid(ent) and IsValid(self.Player) then
for v,k in pairs(self.Player:GetBodyGroups()) do
ent:SetBodygroup(k.id, self.Player:GetBodygroup(k.id))
end
end
end)
function self.modelIcon:PaintOver() -- remove that mouse hover effect
return false
end
end
local gradient = Material("vgui/gradient-l")
local gradientr = Material("vgui/gradient-r")
local outlineCol = Color(190,190,190,240)
local darkCol = Color(30,30,30,200)
function PANEL:Paint(w,h)
if not IsValid(self.Player) then return end
-- Frame
surface.SetDrawColor(outlineCol)
surface.DrawOutlinedRect(0,0,w, h)
surface.SetDrawColor(self.Colour)
surface.SetMaterial(gradient)
surface.DrawTexturedRect(1,1,w-1,h-2)
if self.Player == LocalPlayer() or self.Player:GetFriendStatus() == "friend" then
surface.SetDrawColor(255, 255, 255, (50 + math.sin(RealTime() * 2) * 50) * .4)
surface.SetMaterial(gradientr)
surface.DrawTexturedRect(w - 210, 1, 210-1, h-1)
end
surface.SetMaterial(gradient)
surface.SetDrawColor(darkCol)
surface.DrawTexturedRect(1,1,w-1,h-2)
-- OOC/IC name
surface.SetFont(HIGH_RES("Impulse-Elements20-Shadow", "Impulse-Elements20A-Shadow"))
surface.SetTextColor(color_white)
surface.SetTextPos(65,10)
local icName = ""
if LocalPlayer():IsAdmin() then
icName = " ("..self.Player:Name()..")"
local rpGroup = self.Player:GetSyncVar(SYNC_GROUP_NAME, nil)
if impulse.GetSetting("admin_showgroup") and rpGroup then
icName = icName.." ("..rpGroup..")"
end
end
surface.DrawText(self.Player:SteamName()..icName)
-- Ping
surface.SetTextPos(w-30,10)
surface.DrawText(self.Player:Ping())
-- Team name
surface.SetFont(HIGH_RES("Impulse-Elements18-Shadow", "Impulse-Elements19-Shadow"))
surface.SetTextPos(65,30)
surface.DrawText(team.GetName(self.Player:Team()))
-- Badges
surface.SetDrawColor(color_white)
local xShift = 0
for badgeName, badgeData in pairs(self.Badges) do
surface.SetMaterial(badgeData[1])
surface.DrawTexturedRect(w-34-xShift,30,16,16)
xShift = xShift + 20
end
end
function PANEL:OnMousePressed(key)
if not IsValid(self.Player) then
return false
end
if key == MOUSE_RIGHT then
LocalPlayer():Notify("You have copied "..self.Player:SteamName().."'s Steam ID.")
SetClipboardText(self.Player:SteamID())
else
if impulse_infoCard and IsValid(impulse_infoCard) then
impulse_infoCard:Remove()
end
impulse_infoCard = vgui.Create("impulsePlayerInfoCard")
impulse_infoCard:SetPlayer(self.Player, self.Badges)
end
end
vgui.Register("impulseScoreboardCard", PANEL, "DPanel")
|
-- --- --- --
-- Header --
-- --- --- --
-- Fields
local seed = 0 -- Incremental seed, to be sure that the randomization will always be different
-- Methods
local
createFile,
deleteFile,
toList, -- Function to change a table{...} into table{table{...}} (to always use "for" to traverse what is returned)
shuffle -- Shuffle a table, @see https://gist.github.com/Uradamus/10323382
-- --- --- --
-- Code --
-- --- --- --
createFile = function(path, content)
local file = vlc.io.open(path, 'w')
file:write(content)
file:close()
end
deleteFile = function(path)
vlc.io.unlink(path)
end
toList = function(tbl)
if tbl[1] == nil then
tbl = { tbl }
end
return tbl
end
shuffle = function(tbl)
seed = seed + 1
math.randomseed(os.time() + seed)
for index = #tbl, 2, -1 do
local random = math.random(index)
tbl[index], tbl[random] = tbl[random], tbl[index]
end
return tbl
end
-- --- --- --
-- Exports --
-- --- --- --
return {
createFile = createFile,
deleteFile = deleteFile,
toList = toList,
shuffle = shuffle
}
|
local hook = hook
local player = player
local pairs = pairs
local Msg = Msg
local ErrorNoHalt = ErrorNoHalt
local baseclass = baseclass
local setmetatable = setmetatable
local SERVER = SERVER
local util = util
module( "player_manager" )
-- Stores a table of valid player models
local ModelList = {}
local HandNames = {}
--[[---------------------------------------------------------
Utility to add models to the acceptable model list
-----------------------------------------------------------]]
function AddValidModel( name, model )
ModelList[ name ] = model
end
--
-- Valid hands
--
function AddValidHands( name, model, skin, body )
HandNames[ name ] = { model = model, skin = skin, body = body }
end
--[[---------------------------------------------------------
Return list of all valid player models
-----------------------------------------------------------]]
function AllValidModels( )
return ModelList
end
--[[---------------------------------------------------------
Translate the simple name of a model
into the full model name
-----------------------------------------------------------]]
function TranslatePlayerModel( name )
if ( ModelList[ name ] != nil ) then
return ModelList[ name ]
end
return "models/player/kleiner.mdl"
end
--
-- Translate hands based on model
--
function TranslatePlayerHands( name )
if ( HandNames[ name ] != nil ) then
return HandNames[ name ]
end
return { model = "models/weapons/c_arms_citizen.mdl", skin = 0, body = "100000000" }
end
--[[---------------------------------------------------------
Compile a list of valid player models
-----------------------------------------------------------]]
AddValidModel( "alyx", "models/player/alyx.mdl" )
AddValidHands( "alyx", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "barney", "models/player/barney.mdl" )
AddValidHands( "barney", "models/weapons/c_arms_combine.mdl", 0, "0000000" )
AddValidModel( "breen", "models/player/breen.mdl" )
AddValidHands( "breen", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "charple", "models/player/charple.mdl" )
AddValidHands( "charple", "models/weapons/c_arms_citizen.mdl", 2, "0000000" )
AddValidModel( "chell", "models/player/chell.mdl" )
AddValidHands( "chell", "models/weapons/c_arms_chell.mdl", 0, "0000000" )
AddValidModel( "corpse", "models/player/corpse1.mdl" )
AddValidHands( "corpse", "models/weapons/c_arms_citizen.mdl", 2, "0000000" )
AddValidModel( "combine", "models/player/combine_soldier.mdl" )
AddValidHands( "combine", "models/weapons/c_arms_combine.mdl", 0, "0000000" )
AddValidModel( "combineprison", "models/player/combine_soldier_prisonguard.mdl" )
AddValidHands( "combineprison", "models/weapons/c_arms_combine.mdl", 0, "0000000" )
AddValidModel( "combineelite", "models/player/combine_super_soldier.mdl" )
AddValidHands( "combineelite", "models/weapons/c_arms_combine.mdl", 0, "0000000" )
AddValidModel( "eli", "models/player/eli.mdl" )
AddValidHands( "eli", "models/weapons/c_arms_citizen.mdl", 1, "0000000" )
AddValidModel( "gman", "models/player/gman_high.mdl" )
AddValidHands( "gman", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "kleiner", "models/player/kleiner.mdl" )
AddValidHands( "kleiner", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "monk", "models/player/monk.mdl" )
AddValidHands( "monk", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "mossman", "models/player/mossman.mdl" )
AddValidHands( "mossman", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "mossmanarctic", "models/player/mossman_arctic.mdl" )
AddValidHands( "mossmanarctic", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "odessa", "models/player/odessa.mdl" )
AddValidHands( "odessa", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "police", "models/player/police.mdl" )
AddValidHands( "police", "models/weapons/c_arms_combine.mdl", 0, "0000000" )
AddValidModel( "policefem", "models/player/police_fem.mdl" )
AddValidHands( "policefem", "models/weapons/c_arms_combine.mdl", 0, "0000000" )
AddValidModel( "magnusson", "models/player/magnusson.mdl" )
AddValidHands( "magnusson", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "stripped", "models/player/soldier_stripped.mdl" )
AddValidHands( "stripped", "models/weapons/c_arms_hev.mdl", 2, "0000000" )
AddValidModel( "zombie", "models/player/zombie_classic.mdl" )
AddValidHands( "zombie", "models/weapons/c_arms_citizen.mdl", 2, "0000000" )
AddValidModel( "zombiefast", "models/player/zombie_fast.mdl" )
AddValidHands( "zombiefast", "models/weapons/c_arms_citizen.mdl", 2, "0000000" )
AddValidModel( "female01", "models/player/Group01/female_01.mdl" )
AddValidHands( "female01", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "female02", "models/player/Group01/female_02.mdl" )
AddValidHands( "female02", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "female03", "models/player/Group01/female_03.mdl" )
AddValidHands( "female03", "models/weapons/c_arms_citizen.mdl", 1, "0000000" )
AddValidModel( "female04", "models/player/Group01/female_04.mdl" )
AddValidHands( "female04", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "female05", "models/player/Group01/female_05.mdl" )
AddValidHands( "female05", "models/weapons/c_arms_citizen.mdl", 1, "0000000" )
AddValidModel( "female06", "models/player/Group01/female_06.mdl" )
AddValidHands( "female06", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "female07", "models/player/Group03/female_01.mdl" )
AddValidHands( "female07", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "female08", "models/player/Group03/female_02.mdl" )
AddValidHands( "female08", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "female09", "models/player/Group03/female_03.mdl" )
AddValidHands( "female09", "models/weapons/c_arms_refugee.mdl", 1, "0100000" )
AddValidModel( "female10", "models/player/Group03/female_04.mdl" )
AddValidHands( "female10", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "female11", "models/player/Group03/female_05.mdl" )
AddValidHands( "female11", "models/weapons/c_arms_refugee.mdl", 1, "0100000" )
AddValidModel( "female12", "models/player/Group03/female_06.mdl" )
AddValidHands( "female12", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "male01", "models/player/Group01/male_01.mdl" )
AddValidHands( "male01", "models/weapons/c_arms_citizen.mdl", 1, "0000000" )
AddValidModel( "male02", "models/player/Group01/male_02.mdl" )
AddValidHands( "male02", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "male03", "models/player/Group01/male_03.mdl" )
AddValidHands( "male03", "models/weapons/c_arms_citizen.mdl", 1, "0000000" )
AddValidModel( "male04", "models/player/Group01/male_04.mdl" )
AddValidHands( "male04", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "male05", "models/player/Group01/male_05.mdl" )
AddValidHands( "male05", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "male06", "models/player/Group01/male_06.mdl" )
AddValidHands( "male06", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "male07", "models/player/Group01/male_07.mdl" )
AddValidHands( "male07", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "male08", "models/player/Group01/male_08.mdl" )
AddValidHands( "male08", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "male09", "models/player/Group01/male_09.mdl" )
AddValidHands( "male09", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "male10", "models/player/Group03/male_01.mdl" )
AddValidHands( "male10", "models/weapons/c_arms_refugee.mdl", 1, "0100000" )
AddValidModel( "male11", "models/player/Group03/male_02.mdl" )
AddValidHands( "male11", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "male12", "models/player/Group03/male_03.mdl" )
AddValidHands( "male12", "models/weapons/c_arms_refugee.mdl", 1, "0100000" )
AddValidModel( "male13", "models/player/Group03/male_04.mdl" )
AddValidHands( "male13", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "male14", "models/player/Group03/male_05.mdl" )
AddValidHands( "male14", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "male15", "models/player/Group03/male_06.mdl" )
AddValidHands( "male15", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "male16", "models/player/Group03/male_07.mdl" )
AddValidHands( "male16", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "male17", "models/player/Group03/male_08.mdl" )
AddValidHands( "male17", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "male18", "models/player/Group03/male_09.mdl" )
AddValidHands( "male18", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "medic01", "models/player/Group03m/male_01.mdl" )
AddValidHands( "medic01", "models/weapons/c_arms_refugee.mdl", 1, "0100000" )
AddValidModel( "medic02", "models/player/Group03m/male_02.mdl" )
AddValidHands( "medic02", "models/weapons/c_arms_refugee.mdl", 0, "0000000" )
AddValidModel( "medic03", "models/player/Group03m/male_03.mdl" )
AddValidHands( "medic03", "models/weapons/c_arms_refugee.mdl", 1, "0100000" )
AddValidModel( "medic04", "models/player/Group03m/male_04.mdl" )
AddValidHands( "medic04", "models/weapons/c_arms_refugee.mdl", 0, "0000000" )
AddValidModel( "medic05", "models/player/Group03m/male_05.mdl" )
AddValidHands( "medic05", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "medic06", "models/player/Group03m/male_06.mdl" )
AddValidHands( "medic06", "models/weapons/c_arms_refugee.mdl", 0, "0000000" )
AddValidModel( "medic07", "models/player/Group03m/male_07.mdl" )
AddValidHands( "medic07", "models/weapons/c_arms_refugee.mdl", 0, "0000000" )
AddValidModel( "medic08", "models/player/Group03m/male_08.mdl" )
AddValidHands( "medic08", "models/weapons/c_arms_refugee.mdl", 0, "0000000" )
AddValidModel( "medic09", "models/player/Group03m/male_09.mdl" )
AddValidHands( "medic09", "models/weapons/c_arms_refugee.mdl", 0, "0000000" )
AddValidModel( "medic10", "models/player/Group03m/female_01.mdl" )
AddValidHands( "medic10", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "medic11", "models/player/Group03m/female_02.mdl" )
AddValidHands( "medic11", "models/weapons/c_arms_refugee.mdl", 0, "0000000" )
AddValidModel( "medic12", "models/player/Group03m/female_03.mdl" )
AddValidHands( "medic12", "models/weapons/c_arms_refugee.mdl", 1, "0000000" )
AddValidModel( "medic13", "models/player/Group03m/female_04.mdl" )
AddValidHands( "medic13", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "medic14", "models/player/Group03m/female_05.mdl" )
AddValidHands( "medic14", "models/weapons/c_arms_refugee.mdl", 0, "0100000" )
AddValidModel( "medic15", "models/player/Group03m/female_06.mdl" )
AddValidHands( "medic15", "models/weapons/c_arms_refugee.mdl", 1, "0100000" )
AddValidModel( "refugee01", "models/player/Group02/male_02.mdl" )
AddValidHands( "refugee01", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "refugee02", "models/player/Group02/male_04.mdl" )
AddValidHands( "refugee02", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "refugee03", "models/player/Group02/male_06.mdl" )
AddValidHands( "refugee03", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "refugee04", "models/player/Group02/male_08.mdl" )
AddValidHands( "refugee04", "models/weapons/c_arms_citizen.mdl", 0, "0000000" )
--
-- Game specific player models! (EP2, CSS, DOD)
-- Moving them to here since we're now shipping all required files / fallbacks
AddValidModel( "magnusson", "models/player/magnusson.mdl" )
AddValidHands( "magnusson","models/weapons/c_arms_citizen.mdl", 0, "0000000" )
AddValidModel( "skeleton", "models/player/skeleton.mdl" )
AddValidHands( "skeleton", "models/weapons/c_arms_citizen.mdl", 2, "0000000" )
AddValidModel( "zombine", "models/player/zombie_soldier.mdl" )
AddValidHands( "zombine", "models/weapons/c_arms_combine.mdl", 0, "0000000" )
AddValidModel( "hostage01", "models/player/hostage/hostage_01.mdl" )
AddValidModel( "hostage02", "models/player/hostage/hostage_02.mdl" )
AddValidModel( "hostage03", "models/player/hostage/hostage_03.mdl" )
AddValidModel( "hostage04", "models/player/hostage/hostage_04.mdl" )
AddValidModel( "css_arctic", "models/player/arctic.mdl" )
AddValidHands( "css_arctic", "models/weapons/c_arms_cstrike.mdl", 0, "10000000" )
AddValidModel( "css_gasmask", "models/player/gasmask.mdl" )
AddValidHands( "css_gasmask", "models/weapons/c_arms_cstrike.mdl", 0, "10000000" )
AddValidModel( "css_guerilla", "models/player/guerilla.mdl" )
AddValidHands( "css_guerilla", "models/weapons/c_arms_cstrike.mdl", 0, "10000000" )
AddValidModel( "css_leet", "models/player/leet.mdl" )
AddValidHands( "css_leet", "models/weapons/c_arms_cstrike.mdl", 0, "10000000" )
AddValidModel( "css_phoenix", "models/player/phoenix.mdl" )
AddValidHands( "css_phoenix", "models/weapons/c_arms_cstrike.mdl", 0, "10000000" )
AddValidModel( "css_riot", "models/player/riot.mdl" )
AddValidHands( "css_riot", "models/weapons/c_arms_cstrike.mdl", 0, "10000000" )
AddValidModel( "css_swat", "models/player/swat.mdl" )
AddValidHands( "css_swat", "models/weapons/c_arms_cstrike.mdl", 0, "10000000" )
AddValidModel( "css_urban", "models/player/urban.mdl" )
AddValidHands( "css_urban", "models/weapons/c_arms_cstrike.mdl", 7, "10000000" )
AddValidModel( "dod_american", "models/player/dod_american.mdl" )
AddValidHands( "dod_american", "models/weapons/c_arms_dod.mdl", 0, "10000000" )
AddValidModel( "dod_german", "models/player/dod_german.mdl" )
AddValidHands( "dod_german", "models/weapons/c_arms_dod.mdl", 1, "10000000" )
--
-- Player Class Stuff
--
local Type = {}
function RegisterClass( name, table, base )
Type[ name ] = table;
--
-- If we have a base method then hook
-- it up in the meta table
--
if ( base ) then
if ( !Type[ name ] ) then ErrorNoHalt( "RegisterClass - deriving "..name.." from unknown class "..base.."!" ) end
setmetatable( Type[ name ], { __index = Type[ base ] } )
end
if ( SERVER ) then
util.AddNetworkString( name )
end
--
-- drive methods cooperate with the baseclass system
-- /lua/includes/modules/baseclass.lua
--
baseclass.Set( name, Type[ name ] )
end
function SetPlayerClass( ply, classname )
local t = Type[ classname ]
if ( !Type[ classname ] ) then ErrorNoHalt( "SetPlayerClass - attempt to use unknown player class "..classname ) end
local id = util.NetworkStringToID( classname )
ply:SetClassID( id )
end
function ClearPlayerClass( ply )
ply:SetClassID( 0 )
end
local function LookupPlayerClass( ply )
local id = ply:GetClassID()
if ( id == 0 ) then return end
--
-- Check the cache
--
local method = ply.m_CurrentPlayerClass;
if ( method && method.Player == ply && method.ClassID == id && method.Func ) then return method end
--
-- No class, lets create one
--
local classname = util.NetworkIDToString( id )
if ( !classname ) then return end
--
-- Get that type. Fail if we don't have the type.
--
local t = Type[ classname ]
if ( !t ) then return end
local method = {}
method.Player = ply
method.ClassID = id
method.Func = function() end
setmetatable( method, { __index = t } )
ply.m_CurrentPlayerClass = method
method.Player:InstallDataTable();
method:SetupDataTables()
method:Init()
return method
end
function RunClass( ply, funcname, ... )
local class = LookupPlayerClass( ply )
if ( !class ) then return end
local func = class[funcname]
if ( !func ) then ErrorNoHalt( "Function "..funcname.." not found on player class!\n" ) return end
return func( class, ... )
end
--
-- Should be called on spawn automatically to set the variables below
-- This is called in the base gamemode :PlayerSpawn function
--
function OnPlayerSpawn( ply )
local class = LookupPlayerClass( ply )
if ( !class ) then return end
ply:SetWalkSpeed( class.WalkSpeed )
ply:SetRunSpeed( class.RunSpeed )
ply:SetCrouchedWalkSpeed( class.CrouchedWalkSpeed )
ply:SetDuckSpeed( class.DuckSpeed )
ply:SetUnDuckSpeed( class.UnDuckSpeed )
ply:SetJumpPower( class.JumpPower )
ply:AllowFlashlight( class.CanUseFlashlight )
ply:SetMaxHealth( class.MaxHealth )
ply:SetHealth( class.StartHealth )
ply:SetArmor( class.StartArmor )
ply:ShouldDropWeapon( class.DropWeaponOnDie )
ply:SetNoCollideWithTeammates( class.TeammateNoCollide )
ply:SetAvoidPlayers( class.AvoidPlayers )
end
|
function isseq(...)
local args = {...}
if #args == 1 and type(args[1]) == "table" then args = args[1] end
local ix = {}
for i,_ in pairs(args) do ix[#ix+1] = i end
table.sort(ix)
for i=2, #ix do
if ix[i-1] + 1 == ix[i] then ix[i-1] = nil end
end
ret = {}
for _,v in pairs(ix) do ret[#ret+1] = v end
return #ret == 1 and args[1] ~= nil, ret
end
|
data:extend({
{
name = 'radarmarker-announce-placement',
order = 'a',
type = 'bool-setting',
setting_type = 'runtime-global',
default_value = true,
},
{
name = 'radarmarker-announce-removal',
order = 'b',
type = 'bool-setting',
setting_type = 'runtime-global',
default_value = true,
},
{
name = 'radarmarker-mark-placed-radars',
order = 'c',
type = 'string-setting',
setting_type = 'runtime-global',
default_value = "All",
allowed_values = {"All", "Misalligned", "None"}
},
{
name = 'radarmarker-mark-planned-radars',
order = 'd',
type = 'string-setting',
setting_type = 'runtime-global',
default_value = "All",
allowed_values = {"All", "Missing", "None"}
},
{
name = 'radarmarker-label-planned-radars',
order = 'e',
type = 'bool-setting',
setting_type = 'runtime-global',
default_value = true,
},
{
name = 'radarmarker-planned-radars-spacing',
order = 'f',
type = 'int-setting',
setting_type = 'runtime-global',
default_value = 224,
minimum_value = 32,
maximum_value = 999,
},
--[[
-- Possible future enhancement - align the markers to the chunk grid,
-- even if the spacing is not a multiple of the chunk size. (i.e. 32)
{
name = 'radarmarker-chunk-align-planned-radars',
order = 'g',
type = 'bool-setting',
setting_type = 'runtime-global',
default_value = true,
},
]]
{
name = 'radarmarker-planned-radars-x-offset',
order = 'h',
type = 'int-setting',
setting_type = 'runtime-global',
default_value = 16,
minimum_value = -999,
maximum_value = 999,
},
{
name = 'radarmarker-planned-radars-y-offset',
order = 'i',
type = 'int-setting',
setting_type = 'runtime-global',
default_value = 16,
minimum_value = -999,
maximum_value = 999,
},
})
|
-- bruiser default script.
-- This is run everytime bruiser is called.
-- By default bruiser will look for a file named defaults.lua in the same
-- directory as its executable. you can change the file using the --luadefault
-- option.
-- adds luarocks' path and cpath to bruiser
function default_luarocks_modules()
local luarocks_handle = io.popen("luarocks path --bin")
local path_b = false
local cpath_b = false
for line in luarocks_handle:lines() do
local path = string.match(line, "LUA_PATH%s*=%s*('.+')")
local cpath = string.match(line, "LUA_CPATH%s*=%s*('.+')")
if path ~= nil then
package.path = package.path..";"..string.sub(path, 2, -2)
end
if cpath ~= nil then
package.cpath = package.cpath..";"..string.sub(cpath, 2, -2)
end
end
if path_b then
io.write("failed to get path from luarocks.\n")
end
if cpath_b then
io.write("failed to get cpath from luarocks.\n")
end
end
default_luarocks_modules()
|
--microwave code by Wizzerine
--item_percent code by Noodlemire
local microwave_fs =
"size[9,9.5]"
.."background[0,0;9,4.5;mp_microwave_GUI.png]"
.."image_button[6.88,3.45;.85,.84;mp_microwave_start.png;btn_start;start]"
.."image[7.05,.05;2,.4;mp_mw_bar.png^[transformR270]"
.."list[current_player;main;.5,5;8,1;]"
.."list[current_player;main;.5,6.5;8,3;8]"
.."list[context;cook_slot;3.3,3;1,1;]"
.."label[1.5,0.4;Microwave]"
-- possibly add "fire" image?
local function get_active_microwave_fs(item_percent)
return "size[9,9.5]"
.."background[0,0;9,4.5;mp_microwave_GUI.png]"
.."image_button[6.88,3.45;.85,.84;mp_microwave_start.png;btn_start;start]"
.."image[7.05,.05;2,.4;mp_mw_bar.png^[lowpart:"
..(item_percent)..":mp_mw_bar_on.png^[transformR270]"
.."list[current_player;main;.5,5;8,1;]"
.."list[current_player;main;.5,6.5;8,3;8]"
.."list[context;cook_slot;3.3,3;1,1;]"
.."label[1.5,0.4;Microwave]"
-- possibly add "fire" image?
end
--x,y;w,h
-- Adding recipe API so we don't end up hardcoding items
ma_pops_furniture.microwave = {}
local microwave = ma_pops_furniture.microwave
microwave.recipes = {}
function microwave.register_recipe(input, output) microwave.recipes[input] = output end
local function update_formspec(progress, goal, meta)
local formspec
if progress > 0 and progress <= goal then
local item_percent = math.floor(progress / goal * 100)
formspec = get_active_microwave_fs(item_percent)
else
formspec = microwave_fs
end
meta:set_string("formspec", formspec)
end
local function recalculate(pos)
local meta, timer = minetest.get_meta(pos), minetest.get_node_timer(pos)
local inv = meta:get_inventory()
local stack = inv:get_stack("cook_slot", 1)
local goal = 3 * stack:get_count()
local k = microwave.recipes[stack:get_name()]
if not k then return end
timer:stop()
update_formspec(0, goal, meta)
timer:start(1)
end
local function do_cook_all(pos)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local stack = meta:get_inventory():get_stack("cook_slot", 1)
local food_uncooked = inv:remove_item("cook_slot", inv:get_stack("cook_slot", 1)) -- Clear the slot
local food_cooked = microwave.recipes[food_uncooked:get_name()] .. " " .. tostring(food_uncooked:get_count()) -- Get the cooked food
inv:add_item("cook_slot", food_cooked) -- Put the cooked food in the slot
end
minetest.register_node("ma_pops_furniture:microwave", {
description = "Microwave",
tiles = {"mp_mw_top.png", "mp_mw_bottom.png", "mp_mw_right.png", "mp_mw_left.png", "mp_mw_back.png", "mp_mw_front.png"},
paramtype2 = "facedir",
groups = {cracky = 2}, -- currently no pipeworks compat as I don't know how it works
sounds = moditems.STONE_SOUNDS,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-0.4375, -0.4375, -0.3125, 0.4375, 0.0625, 0.3125},
{-0.375, -0.5, -0.25, 0.375, -0.4375, 0.25},
},
},
can_dig = function(pos, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:is_empty("cook_slot")
end,
on_timer = function(pos, elapsed)
local meta = minetest.get_meta(pos)
local stack = meta:get_inventory():get_stack("cook_slot", 1)
local goal = 3 * stack:get_count()
local cooking_time = meta:get_int("cooking_time") or 0
cooking_time = cooking_time + 1
update_formspec(cooking_time, goal, meta)
meta:set_int("cooking_time", cooking_time)
--Keep cooking until there is nothing left to cook.
if cooking_time <= goal then
return true
else
do_cook_all(pos)
meta:set_int("cooking_time", 0)
update_formspec(0, goal, meta)
return false
end
end,
--on_metadata_inventory_put = recalculate,
--on_metadata_inventory_take = recalculate,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", microwave_fs)
local inv = meta:get_inventory()
inv:set_size("cook_slot", 1)
end,
on_receive_fields = function(pos, _, fields)
if fields.quit then return end
if fields.btn_start then
recalculate(pos)
end
end,
on_blast = function(pos)
local drops = {}
default.get_inventory_drops(pos, "cook_slot", drops)
table.insert(drops, "ma_pops_furniture:microwave")
minetest.remove_node(pos)
return drops
end,
allow_metadata_inventory_put = function(pos, list, index, stack, player)
return microwave.recipes[stack:get_name()] and stack:get_count() or 0
end,
--Only allow items to be taken if the microwave hasn't started yet
allow_metadata_inventory_take = function(pos, listname, index, stack, player)
if not minetest.get_node_timer(pos):is_started() then
return stack:get_count()
else
return 0
end
end
})
-- Recipe Registration
microwave.register_recipe("default:ice", "default:water_source")
-- No milk bucket as this doesn't support substitutes for now
microwave.register_recipe("mobs_mc:chicken_raw", "mobs_mc:chicken_cooked")
--[[ We don't need to check mod existance when registering recipe
Recipe won't even be executed if there is no raw chicken in input ]]--
microwave.register_recipe("mobs_mc:beef_raw", "mobs_mc:beef_cooked")
microwave.register_recipe("mobs:meat_raw", "mobs:meat")
microwave.register_recipe("farming:coffee_cup", "farming:coffee_cup_hot") -- What a crutch there was...
microwave.register_recipe("farming:corn", "farming:corn_cob")
-- Add needed recipes as you go, note that other mods can add more recipes too
|
pfUI:RegisterModule("actionbar", function ()
local default_border = C.appearance.border.default
if C.appearance.border.actionbars ~= "-1" then
default_border = C.appearance.border.actionbars
end
hooksecurefunc("MultiActionBar_ShowAllGrids", function()
MultiActionBar_UpdateGrid("BonusAction", 1)
MultiActionBar_UpdateGrid("Action", 1)
end)
hooksecurefunc("MultiActionBar_HideAllGrids", function()
MultiActionBar_UpdateGrid("BonusAction")
MultiActionBar_UpdateGrid("Action")
end)
hooksecurefunc("ShowBonusActionBar", function()
if pfActionBar then pfActionBar:Hide() end
if pfBonusBar then pfBonusBar:Show() end
end)
hooksecurefunc("HideBonusActionBar", function()
if pfActionBar then pfActionBar:Show() end
if pfBonusBar then pfBonusBar:Hide() end
end)
if C.bars.keydown == "1" then
hooksecurefunc("ActionButtonDown", function(id)
ActionButtonUp(id)
end, true)
hooksecurefunc("MultiActionButtonDown", function(bar, id)
MultiActionButtonUp(bar, id)
end, true)
end
if C.bars.pagemaster == "1" then
local modifier = { "ALT", "SHIFT", "CTRL" }
local buttons = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "+", "=", "´" }
local shift, ctrl, alt, default = 6, 5, 3, 1
local current = CURRENT_ACTIONBAR_PAGE
local function SwitchBar(bar)
if CURRENT_ACTIONBAR_PAGE ~= bar then
CURRENT_ACTIONBAR_PAGE = bar
ChangeActionBarPage()
end
end
local pagemaster = CreateFrame("Frame", "pfPageMaster", UIParent)
pagemaster:RegisterEvent("PLAYER_ENTERING_WORLD")
pagemaster:SetScript("OnEvent", function()
for _,mod in pairs(modifier) do
for _,but in pairs(buttons) do
SetBinding(mod.."-"..but)
end
end
end)
pagemaster:SetScript("OnUpdate", function()
if IsShiftKeyDown() then
SwitchBar(shift)
elseif IsControlKeyDown() then
SwitchBar(ctrl)
elseif IsAltKeyDown() then
SwitchBar(alt)
else
SwitchBar(default)
end
end)
end
-- reagent counter
local reagentslots = { }
local scanner = libtipscan:GetScanner("actionbar")
hooksecurefunc("ActionButton_OnEvent", function()
if event == "BAG_UPDATE" and arg1 < 5 then
ActionButton_Update()
end
end)
local reagent_capture = SPELL_REAGENTS.."(.+)"
local oldIsConsumableAction = IsConsumableAction
_G.IsConsumableAction = function(slot)
if oldIsConsumableAction(slot) then return true end
if this and this.GetParent and ActionButton_GetPagedID(this) == slot then
reagentslots[slot] = nil
scanner:SetAction(slot)
local _, reagents = scanner:Find(reagent_capture)
if reagents then
reagentslots[slot] = reagents
this:RegisterEvent("BAG_UPDATE")
return true
end
this:UnregisterEvent("BAG_UPDATE")
return nil
end
end
local oldGetActionCount = GetActionCount
_G.GetActionCount = function(slot)
if reagentslots[slot] then
return GetItemCount(reagentslots[slot])
end
if oldGetActionCount(slot) then return oldGetActionCount(slot) end
end
if C.bars.glowrange == "1" then
function _G.ActionButton_UpdateUsable()
if pfScanActive then return end
local icon = getglobal(this:GetName().."Icon");
local normalTexture = getglobal(this:GetName().."NormalTexture");
local isUsable, notEnoughMana = IsUsableAction(ActionButton_GetPagedID(this));
if ( isUsable ) then
icon:SetVertexColor(1.0, 1.0, 1.0);
normalTexture:SetVertexColor(1.0, 1.0, 1.0);
elseif ( notEnoughMana ) then
icon:SetVertexColor(0.5, 0.5, 1.0);
normalTexture:SetVertexColor(0.5, 0.5, 1.0);
else
icon:SetVertexColor(0.4, 0.4, 0.4);
normalTexture:SetVertexColor(1.0, 1.0, 1.0);
end
end
hooksecurefunc("ActionButton_OnUpdate", function(elapsed)
-- Handle range indicator
if ( this.rangeTimer ) then
this.rangeTimer = this.rangeTimer - elapsed
if ( this.rangeTimer <= 0.1 ) then
if ( IsActionInRange( ActionButton_GetPagedID(this)) == 0 ) then
if not this.a then
this.r,this.g,this.b,this.a = strsplit(",", C.bars.rangecolor)
end
_G[this:GetName() .. 'Icon']:SetVertexColor(this.r, this.g, this.b, this.a)
elseif IsUsableAction(ActionButton_GetPagedID(this)) then
_G[this:GetName() .. 'Icon']:SetVertexColor(1, 1, 1, 1)
end
this.rangeTimer = TOOLTIP_UPDATE_TIME
end
end
end)
end
function _G.ActionButton_GetPagedID(button)
if ( button.isBonus and CURRENT_ACTIONBAR_PAGE == 1 ) then
local offset = GetBonusBarOffset()
if ( offset == 0 and BonusActionBarFrame and BonusActionBarFrame.lastBonusBar ) then
offset = BonusActionBarFrame.lastBonusBar
end
return (button:GetID() + ((NUM_ACTIONBAR_PAGES + offset - 1) * NUM_ACTIONBAR_BUTTONS))
end
local parentName = button:GetParent():GetName()
if ( parentName == "pfMultiBarBottomLeft" or parentName == "MultiBarBottomLeft" ) then
return (button:GetID() + ((BOTTOMLEFT_ACTIONBAR_PAGE - 1) * NUM_ACTIONBAR_BUTTONS))
elseif ( parentName == "pfMultiBarBottomRight" or parentName == "MultiBarBottomRight" ) then
return (button:GetID() + ((BOTTOMRIGHT_ACTIONBAR_PAGE - 1) * NUM_ACTIONBAR_BUTTONS))
elseif ( parentName == "pfMultiBarLeft" or parentName == "MultiBarLeft" ) then
return (button:GetID() + ((LEFT_ACTIONBAR_PAGE - 1) * NUM_ACTIONBAR_BUTTONS))
elseif ( parentName == "pfMultiBarRight" or parentName == "MultiBarRight" ) then
return (button:GetID() + ((RIGHT_ACTIONBAR_PAGE - 1) * NUM_ACTIONBAR_BUTTONS))
else
return (button:GetID() + ((CURRENT_ACTIONBAR_PAGE - 1) * NUM_ACTIONBAR_BUTTONS))
end
end
-- hide default blizz
MainMenuBar:Hide()
BonusActionBarTexture0:Hide()
BonusActionBarTexture1:Hide()
-- hide background texture of petactionbar
SlidingActionBarTexture0:Hide()
SlidingActionBarTexture0.Show = function () return end
SlidingActionBarTexture1:Hide()
SlidingActionBarTexture1.Show = function () return end
-- create action bar frame
pfUI.bars = CreateFrame("Frame", nil, UIParent)
pfUI.bars:RegisterEvent("PLAYER_ENTERING_WORLD")
pfUI.bars:RegisterEvent("CVAR_UPDATE")
pfUI.bars:RegisterEvent("PET_BAR_UPDATE")
pfUI.bars:RegisterEvent("PLAYER_CONTROL_GAINED")
pfUI.bars:RegisterEvent("PLAYER_CONTROL_LOST")
pfUI.bars:RegisterEvent("PLAYER_FARSIGHT_FOCUS_CHANGED")
pfUI.bars:RegisterEvent("UPDATE_SHAPESHIFT_FORMS")
pfUI.bars.actionmain = CreateFrame("Frame", "pfBarActionMain", UIParent)
pfUI.bars.shapeshift = CreateFrame("Frame", "pfBarShapeshift", UIParent)
pfUI.bars.bottomleft = CreateFrame("Frame", "pfBarBottomLeft", UIParent)
pfUI.bars.bottomright = CreateFrame("Frame", "pfBarBottomRight", UIParent)
pfUI.bars.right = CreateFrame("Frame", "pfBarRight", UIParent)
pfUI.bars.tworight = CreateFrame("Frame", "pfBarTwoRight", UIParent)
pfUI.bars.pet = CreateFrame("Frame", "pfBarPet", UIParent)
pfUI.bars:SetScript("OnEvent", function()
MultiActionBar_Update()
UIParent_ManageFramePositions()
MultiActionBar_Update()
UpdateMicroButtons()
BarLayoutSize(pfUI.bars.actionmain, NUM_ACTIONBAR_BUTTONS, C.bars.actionmain.formfactor, C.bars.icon_size, default_border)
pfUI.bars.actionmain:SetWidth(pfUI.bars.actionmain._size[1])
pfUI.bars.actionmain:SetHeight(pfUI.bars.actionmain._size[2])
if (PetHasActionBar()) then
PetActionBar_Update()
pfUI.bars.pet:Show()
this.pet:ClearAllPoints()
this.pet:SetPoint("BOTTOM", this.bottomleft:IsShown() and this.bottomleft or this.actionmain, "TOP", 0, default_border * 3)
UpdateMovable(this.pet, true)
BarLayoutSize(pfUI.bars.pet, NUM_PET_ACTION_SLOTS, C.bars.pet.formfactor, C.bars.icon_size, default_border)
pfUI.bars.pet:SetWidth(pfUI.bars.pet._size[1])
pfUI.bars.pet:SetHeight(pfUI.bars.pet._size[2])
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.pet, default_border) end
PetActionBarFrame:ClearAllPoints()
PetActionBarFrame:Hide()
for i=1, NUM_PET_ACTION_SLOTS do
local b = _G["PetActionButton"..i]
b:ClearAllPoints()
b:SetFrameLevel(pfUI.bars.pet:GetFrameLevel() + 1)
b:SetParent(pfUI.bars.pet)
CreateBackdrop(b, default_border)
BarButtonAnchor(b, "PetActionButton", i, NUM_PET_ACTION_SLOTS, C.bars.pet.formfactor, C.bars.icon_size, default_border)
b:SetPoint(unpack(b._anchor))
end
else
pfUI.bars.pet:Hide()
end
local shapeshiftbuttons = 0
if ShapeshiftButton1:IsShown() then
ShapeshiftBarFrame:ClearAllPoints()
ShapeshiftBarFrame:SetAllPoints(pfUI.bars.shapeshift)
for i=1, NUM_SHAPESHIFT_SLOTS do
local b = _G["ShapeshiftButton"..i]
b:ClearAllPoints()
b:SetParent(pfUI.bars.shapeshift)
CreateBackdrop(b, default_border)
BarButtonAnchor(b, "ShapeshiftButton", i, NUM_SHAPESHIFT_SLOTS, C.bars.shapeshift.formfactor, C.bars.icon_size, default_border)
b:SetPoint(unpack(b._anchor))
if b:IsShown() then shapeshiftbuttons = shapeshiftbuttons + 1 end
end
this.shapeshift:ClearAllPoints()
this.shapeshift:SetPoint("BOTTOM", this.bottomleft:IsShown() and this.bottomleft or this.pet:IsShown() and this.pet or this.actionmain, "TOP", 0, default_border * 3)
UpdateMovable(this.shapeshift, true)
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.shapeshift, default_border) end
BarLayoutSize(pfUI.bars.shapeshift, NUM_SHAPESHIFT_SLOTS, C.bars.shapeshift.formfactor, C.bars.icon_size, default_border,shapeshiftbuttons)
pfUI.bars.shapeshift:SetWidth(pfUI.bars.shapeshift._size[1])
pfUI.bars.shapeshift:SetHeight(pfUI.bars.shapeshift._size[2])
pfUI.bars.shapeshift:Show()
else
pfUI.bars.shapeshift:Hide()
end
if SHOW_MULTI_ACTIONBAR_1 then
pfUI.bars.bottomleft:Show()
pfUI.bars.bottomleft:SetFrameStrata("LOW")
pfUI.bars.bottomleft:ClearAllPoints()
pfUI.bars.bottomleft:SetPoint("BOTTOM", pfUI.bars.actionmain, "TOP", 0, default_border)
UpdateMovable(pfUI.bars.bottomleft)
BarLayoutSize(pfUI.bars.bottomleft, NUM_ACTIONBAR_BUTTONS, C.bars.bottomleft.formfactor, C.bars.icon_size, default_border)
pfUI.bars.bottomleft:SetWidth(pfUI.bars.bottomleft._size[1])
pfUI.bars.bottomleft:SetHeight(pfUI.bars.bottomleft._size[2])
MultiBarBottomLeft:SetParent(pfUI.bars.bottomleft)
MultiBarBottomLeft:ClearAllPoints()
MultiBarBottomLeft:SetAllPoints(pfUI.bars.bottomleft)
-- create temp frame to give a named parent to the buttons
if not pfUI.bars.bottomleft.setuptf then
pfUI.bars.bottomleft.setuptf = true
local tf = CreateFrame("Frame", "pfMultiBarBottomLeft", UIParent )
tf:SetParent(pfUI.bars.bottomleft)
tf:SetAllPoints(pfUI.bars.bottomleft)
for i=1, NUM_ACTIONBAR_BUTTONS do
local b = _G["MultiBarBottomLeftButton"..i]
b:ClearAllPoints()
b:SetParent(tf)
CreateBackdrop(b, default_border)
BarButtonAnchor(b, "MultiBarBottomLeftButton", i, NUM_ACTIONBAR_BUTTONS, C.bars.bottomleft.formfactor, C.bars.icon_size, default_border)
b:SetPoint(unpack(b._anchor))
end
end
else
pfUI.bars.bottomleft:Hide()
end
pfUI.bars.actionmain:ClearAllPoints()
pfUI.bars.actionmain:SetPoint("BOTTOM", UIParent ,"BOTTOM",0,5)
if SHOW_MULTI_ACTIONBAR_2 then
pfUI.bars.bottomright:Show()
pfUI.bars.bottomright:SetFrameStrata("LOW")
pfUI.bars.bottomright:SetPoint("BOTTOMRIGHT", pfUI.bars.actionmain, "BOTTOMLEFT", -default_border*3, 0)
UpdateMovable(pfUI.bars.bottomright)
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.bottomright, default_border) end
BarLayoutSize(pfUI.bars.bottomright, NUM_ACTIONBAR_BUTTONS, C.bars.bottomright.formfactor, C.bars.icon_size, default_border)
pfUI.bars.bottomright:SetWidth(pfUI.bars.bottomright._size[1])
pfUI.bars.bottomright:SetHeight(pfUI.bars.bottomright._size[2])
MultiBarBottomRight:SetParent(pfUI.bars.bottomright)
MultiBarBottomRight:ClearAllPoints()
MultiBarBottomRight:SetAllPoints(pfUI.bars.bottomright)
-- create temp frame to give a named parent to the buttons
if not pfUI.bars.bottomright.setuptf then
pfUI.bars.bottomright.setuptf = true
local tf = CreateFrame("Frame", "pfMultiBarBottomRight", UIParent )
tf:SetParent(pfUI.bars.bottomright)
tf:SetAllPoints(pfUI.bars.bottomright)
for i=1, NUM_ACTIONBAR_BUTTONS do
local b = _G["MultiBarBottomRightButton"..i]
b:ClearAllPoints()
b:SetParent(tf)
CreateBackdrop(b, default_border)
BarButtonAnchor(b, "MultiBarBottomRightButton", i, NUM_ACTIONBAR_BUTTONS, C.bars.bottomright.formfactor, C.bars.icon_size, default_border)
b:SetPoint(unpack(b._anchor))
end
end
else
pfUI.bars.bottomright:Hide()
end
if SHOW_MULTI_ACTIONBAR_3 then
pfUI.bars.right:Show()
pfUI.bars.right:SetFrameStrata("LOW")
pfUI.bars.right:SetPoint("BOTTOMLEFT", pfUI.bars.actionmain, "BOTTOMRIGHT", default_border*3, 0)
UpdateMovable(pfUI.bars.right)
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.right, default_border) end
BarLayoutSize(pfUI.bars.right, NUM_ACTIONBAR_BUTTONS, C.bars.right.formfactor, C.bars.icon_size, default_border)
pfUI.bars.right:SetWidth(pfUI.bars.right._size[1])
pfUI.bars.right:SetHeight(pfUI.bars.right._size[2])
MultiBarRight:SetParent(pfUI.bars.right)
MultiBarRight:ClearAllPoints()
MultiBarRight:SetAllPoints(pfUI.bars.right)
-- create temp frame to give a named parent to the buttons
if not pfUI.bars.right.setuptf then
pfUI.bars.right.setuptf = true
local tf = CreateFrame("Frame", "pfMultiBarRight", UIParent )
tf:SetParent(pfUI.bars.right)
tf:SetAllPoints(pfUI.bars.right)
for i=1, NUM_ACTIONBAR_BUTTONS do
local b = _G["MultiBarRightButton"..i]
b:ClearAllPoints()
b:SetParent(tf)
CreateBackdrop(b, default_border)
BarButtonAnchor(b, "MultiBarRightButton", i, NUM_ACTIONBAR_BUTTONS, C.bars.right.formfactor, C.bars.icon_size, default_border)
b:SetPoint(unpack(b._anchor))
end
end
else
pfUI.bars.right:Hide()
end
if SHOW_MULTI_ACTIONBAR_4 then
pfUI.bars.tworight:Show()
for i=1, NUM_ACTIONBAR_BUTTONS do
_G["MultiBarLeftButton"..i]:Show()
end
pfUI.bars.tworight:SetFrameStrata("LOW")
pfUI.bars.tworight:ClearAllPoints()
pfUI.bars.tworight:SetPoint("RIGHT", UIParent, "RIGHT", -5, 0)
UpdateMovable(pfUI.bars.tworight)
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.tworight, default_border) end
BarLayoutSize(pfUI.bars.tworight, NUM_ACTIONBAR_BUTTONS, C.bars.tworight.formfactor, C.bars.icon_size, default_border)
pfUI.bars.tworight:SetWidth(pfUI.bars.tworight._size[1])
pfUI.bars.tworight:SetHeight(pfUI.bars.tworight._size[2])
MultiBarLeft:SetParent(pfUI.bars.tworight)
MultiBarLeft:ClearAllPoints()
MultiBarLeft:SetAllPoints(pfUI.bars.tworight)
-- create temp frame to give a named parent to the buttons
if not pfUI.bars.tworight.setuptf then
pfUI.bars.tworight.setuptf = true
local tf = CreateFrame("Frame", "pfMultiBarLeft", UIParent )
tf:SetParent(pfUI.bars.tworight)
tf:SetAllPoints(pfUI.bars.tworight)
for i=1, NUM_ACTIONBAR_BUTTONS do
local b = _G["MultiBarLeftButton"..i]
b:ClearAllPoints()
b:SetParent(tf)
CreateBackdrop(b, default_border)
BarButtonAnchor(b, "MultiBarLeftButton", i, NUM_ACTIONBAR_BUTTONS, C.bars.tworight.formfactor, C.bars.icon_size, default_border)
b:SetPoint(unpack(b._anchor))
end
end
else
pfUI.bars.tworight:Hide()
end
UpdateMovable(pfUI.bars.actionmain)
local _, a, _ = pfUI.bars.bottomleft:GetPoint()
if a and a == pfUI.bars.actionmain and pfUI.bars.bottomleft:IsShown() and pfUI.bars.bottomleft:GetWidth() == a:GetWidth() and pfUI.bars.bottomleft:GetScale() == a:GetScale() then
-- share one backdrop
if not pfUI.bars.actionmain.share then
pfUI.bars.actionmain.share = CreateFrame("Frame", "pfBottomBackdrop", UIParent)
pfUI.bars.actionmain.share:SetFrameStrata("LOW")
pfUI.bars.actionmain.share:SetPoint("TOPLEFT", pfUI.bars.bottomleft, "TOPLEFT", 0, 0)
pfUI.bars.actionmain.share:SetPoint("BOTTOMLEFT", pfUI.bars.actionmain, "BOTTOMLEFT", 0, 0)
pfUI.bars.actionmain.share:SetPoint("TOPRIGHT", pfUI.bars.bottomleft, "TOPRIGHT", 0, 0)
pfUI.bars.actionmain.share:SetPoint("BOTTOMRIGHT", pfUI.bars.actionmain, "BOTTOMRIGHT", 0, 0)
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.actionmain.share, default_border) end
end
else
-- give both their own backdrop
if pfUI.bars.actionmain.share then pfUI.bars.actionmain.share:Hide() end
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.actionmain, default_border) end
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.bottomleft, default_border) end
end
-- refresh all grids
MultiActionBar_ShowAllGrids()
MultiActionBar_HideAllGrids()
end)
pfUI.bars.autohide = CreateFrame("Frame", nil, UIParent)
pfUI.bars.autohide:RegisterEvent("PLAYER_ENTERING_WORLD")
pfUI.bars.autohide:SetScript("OnEvent", function()
if C.bars.hide_actionmain == "1" then
CreateAutohide(pfUI.bars.actionmain)
end
if C.bars.hide_bottomleft == "1" then
CreateAutohide(pfUI.bars.bottomleft)
end
if C.bars.hide_bottomright == "1" then
CreateAutohide(pfUI.bars.bottomright)
end
if C.bars.hide_right == "1" then
CreateAutohide(pfUI.bars.right)
end
if C.bars.hide_tworight == "1" then
CreateAutohide(pfUI.bars.tworight)
end
if C.bars.hide_shapeshift == "1" then
CreateAutohide(pfUI.bars.shapeshift)
end
if C.bars.hide_pet == "1" then
CreateAutohide(pfUI.bars.pet)
end
end)
-- create main action bar frame
pfUI.bars.actionmain:SetFrameStrata("LOW")
UpdateMovable(pfUI.bars.actionmain)
function pfUI.bars.bottomleft:OnMove()
local _, a, _ = pfUI.bars.bottomleft:GetPoint()
if a ~= pfUI.bars.actionmain or not pfUI.bars.bottomleft:IsShown() or pfUI.bars.bottomleft:GetWidth() ~= a:GetWidth() or pfUI.bars.bottomleft:GetScale() ~= a:GetScale() then
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.actionmain, default_border) end
if C.bars.background == "1" then CreateBackdrop(pfUI.bars.bottomleft, default_border) end
if pfUI.bars.actionmain.share then pfUI.bars.actionmain.share:Hide() end
end
end
-- create temp frame to give a named parent to the buttons
if not pfUI.bars.actionmain.setuptf then
pfUI.bars.actionmain.setuptf = true
local tf = CreateFrame("Frame","pfActionBar", UIParent)
tf:SetParent(pfUI.bars.actionmain)
tf:SetAllPoints(pfUI.bars.actionmain)
for i=1, NUM_ACTIONBAR_BUTTONS do
local b = _G["ActionButton"..i]
b:ClearAllPoints()
b:SetParent(tf)
CreateBackdrop(b, default_border)
BarButtonAnchor(b, "ActionButton", i, NUM_ACTIONBAR_BUTTONS, C.bars.actionmain.formfactor, C.bars.icon_size, default_border)
b:SetPoint(unpack(b._anchor))
end
end
BonusActionBarFrame:ClearAllPoints()
BonusActionBarFrame:SetParent(pfUI.bars.actionmain)
BonusActionBarFrame:SetAllPoints(pfUI.bars.actionmain)
BonusActionBarFrame:EnableMouse(0)
local tf = _G["pfBonusBar"] or CreateFrame("Frame","pfBonusBar", UIParent)
tf:SetParent(pfUI.bars.actionmain)
tf:SetAllPoints(pfUI.bars.actionmain)
tf:SetFrameLevel(pfActionBar:GetFrameLevel() + 1)
for i=1, NUM_BONUS_ACTION_SLOTS do
local b = _G["BonusActionButton"..i]
b:ClearAllPoints()
b:SetParent(tf)
CreateBackdrop(b, default_border)
BarButtonAnchor(b, "BonusActionButton", i, NUM_BONUS_ACTION_SLOTS, C.bars.actionmain.formfactor, C.bars.icon_size, default_border)
b:SetPoint(unpack(b._anchor))
end
for i = 1, NUM_SHAPESHIFT_SLOTS do
local button = _G["ShapeshiftButton"..i]
button:SetWidth(C.bars.icon_size)
button:SetHeight(C.bars.icon_size)
local cooldown = _G["ShapeshiftButton"..i..'Cooldown']
cooldown.pfCooldownType = "NOGCD"
local icon = _G["ShapeshiftButton"..i..'Icon']
icon:SetParent(button)
icon:SetAllPoints(button)
icon:SetTexCoord(.08, .92, .08, .92)
local texture = _G["ShapeshiftButton"..i..'NormalTexture']
texture:SetAlpha(0)
local border = _G["ShapeshiftButton"..i..'Border']
border:SetAlpha(0)
local hotkey = _G["ShapeshiftButton"..i..'HotKey']
hotkey:SetAllPoints(button)
hotkey:SetFont(pfUI.font_unit, C.global.font_unit_size -2, "OUTLINE")
hotkey:SetJustifyH("RIGHT")
hotkey:SetJustifyV("TOP")
end
PetActionBarFrame:SetParent(pfUI.bars.pet)
for i = 1, NUM_PET_ACTION_SLOTS do
local button = _G["PetActionButton"..i]
button:SetWidth(C.bars.icon_size)
button:SetHeight(C.bars.icon_size)
button:Show()
local cooldown = _G["PetActionButton"..i..'Cooldown']
cooldown.pfCooldownType = "NOGCD"
local icon = _G["PetActionButton"..i..'Icon']
icon:SetAllPoints(button)
icon:SetParent(button)
icon:SetTexCoord(.08, .92, .08, .92)
local texture = _G["PetActionButton"..i..'NormalTexture2']
texture:SetAlpha(0)
local castable = _G["PetActionButton"..i..'AutoCastable']
if C.bars.showcastable == "1" then
castable:SetWidth(C.bars.icon_size*1.5)
castable:SetHeight(C.bars.icon_size*1.5)
castable:SetParent(button)
castable:SetTexCoord(.08, .9, .08, .9)
else
castable:SetAlpha(0)
end
local border = _G["PetActionButton"..i..'Border']
border:SetAlpha(0)
local autocast = _G["PetActionButton"..i..'AutoCast']
autocast:SetScale(C.bars.icon_size / 30)
autocast:SetPoint("TOPLEFT", button, "TOPLEFT", 0, 0)
autocast:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 1, -1)
autocast:SetAlpha(.1)
end
-- theme all actionbars (spacing, size, border, text position and style)
local actionbars = { "ActionButton", "MultiBarLeftButton", "MultiBarRightButton",
"MultiBarBottomLeftButton", "MultiBarBottomRightButton", "BonusActionButton", }
for i = 1, NUM_ACTIONBAR_BUTTONS do
for _, actionbutton in pairs(actionbars) do
local button = _G[actionbutton..i]
button:SetWidth(C.bars.icon_size)
button:SetHeight(C.bars.icon_size)
button:Show()
button:SetNormalTexture("")
button.SetNormalTexture = function() return end
local cooldown = _G[actionbutton..i..'Cooldown']
cooldown.pfCooldownType = "NOGCD"
local icon = _G[actionbutton..i..'Icon']
icon:SetAllPoints(button)
icon:SetTexCoord(.08, .92, .08, .92)
local border = _G[actionbutton..i..'Border']
if C.bars.showequipped == "1" then
border:SetAllPoints(button)
border:SetTexture(0,1,0,.75)
else
border:SetTexture(0,0,0,0)
end
local hotkey = _G[actionbutton..i..'HotKey']
if C.bars.showkeybind == "1" then
hotkey:SetAllPoints(button)
hotkey:SetFont(pfUI.font_unit, C.global.font_unit_size -2, "OUTLINE")
hotkey:SetJustifyH("RIGHT")
hotkey:SetJustifyV("TOP")
else
hotkey:SetAlpha(0)
end
local count = _G[actionbutton..i..'Count']
count:SetAllPoints(button)
count:SetFont(pfUI.font_unit, C.global.font_unit_size, "OUTLINE")
count:SetJustifyH("RIGHT")
count:SetJustifyV("BOTTOM")
local name = _G[actionbutton..i..'Name']
if C.bars.showmacro == "1" then
name:SetAllPoints(button)
name:SetFont(pfUI.font_unit, C.global.font_unit_size -2, "OUTLINE")
name:SetJustifyH("CENTER")
name:SetJustifyV("BOTTOM")
else
name:SetAlpha(0)
end
end
end
end)
|
local Symbols = {}
Symbols.GLOBAL_REGISTRY = "kcontainer"
Symbols.CLASS_REGISTRY = "classes"
Symbols.OBJECT_REGISTRY = "objects"
Symbols.CLASS_NAME = "_class_"
Symbols.OBJECT_ID = "_id_"
Symbols.BASE_CLASS_NAME = "_base_class_"
Symbols.SINGLETON = "_singleton_"
Symbols.RAW = "_raw_" -- 加载器不再展开表,寻找 K 结构,客户代码要自己处理表
Symbols.GET_CLASS_NAME = "get_class_name"
Symbols.GET_BASE_CLASS_NAME = "get_base_class_name"
Symbols.GET_ID = "id"
Symbols.GET_CLASS = "get_class"
Symbols.SUPER = "super"
Symbols.NEW = "new"
Symbols.CONSTRUCTOR = "_constructor_"
Symbols.DESTROY = "destroy"
Symbols.ON_LOAD = "on_load"
Symbols.ON_READY = "on_ready"
Symbols.ON_DESTROY = "on_destroy"
Symbols.BIND_EVENT = "on"
return Symbols
|
--[[ Copyright 2020 DeepMind Technologies Limited.
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local args = require 'common.args'
local class = require 'common.class'
local helpers = require 'common.helpers'
local log = require 'common.log'
local set = require 'common.set'
local events = require 'system.events'
local random = require 'system.random'
local meltingpot = 'meltingpot.lua.'
local mp_modules = meltingpot .. 'modules.'
local paintball = meltingpot .. 'levels.paintball.'
local component = require(mp_modules .. 'component')
local shared_components = require(paintball .. 'shared_components')
local component_registry = require(mp_modules .. 'component_registry')
--[[ King of the Hill game uses a special Ground component to handle Hill logic,
different from the Ground component used by other paintball type games.
]]
local GroundOrHill = class.Class(shared_components.Ground)
function GroundOrHill:__init__(kwargs)
kwargs = args.parse(kwargs, {
{'name', args.default('GroundOrHill')},
{'teamNames', args.tableType},
{'isHill', args.default(false), args.booleanType},
})
GroundOrHill.Base.__init__(self, {name = kwargs.name,
teamNames = kwargs.teamNames})
self._teamNames = set.Set(kwargs.teamNames)
self._isHill = kwargs.isHill
end
function GroundOrHill:onHit(hittingGameObject, hittingTeam)
-- Assume teamNames are identical to color states e.g. red, blue etc.
local passThrough = GroundOrHill.Base.onHit(
self, hittingGameObject, hittingTeam)
if self._teamNames[hittingTeam] then
local oldTeam = self.gameObject:getState(oldTeam)
if self._isHill then
self._hillManager:squareColored(oldTeam, hittingTeam)
-- Provide reward for painting the hill if applicable.
if hittingGameObject:hasComponent('Taste') then
hittingGameObject:getComponent('Taste'):paintedHillSquare(oldTeam)
end
end
end
return passThrough
end
function GroundOrHill:capture(capturingTeam)
local oldTeam = self.gameObject:getState(oldTeam)
self.gameObject:setState(capturingTeam)
self._hillManager:squareColored(oldTeam, capturingTeam)
end
function GroundOrHill:start()
local sceneObject = self.gameObject.simulation:getSceneObject()
self._hillManager = sceneObject:getComponent('HillManager')
if self._isHill then
self._hillManager:registerSquare(self)
end
end
local ControlIndicator = class.Class(component.Component)
function ControlIndicator:__init__(kwargs)
kwargs = args.parse(kwargs, {
{'name', args.default('ControlIndicator')},
})
ControlIndicator.Base.__init__(self, kwargs)
end
function ControlIndicator:update()
local sceneObject = self.gameObject.simulation:getSceneObject()
local hillManager = sceneObject:getComponent('HillManager')
local teamInControl = hillManager:getTeamInControl()
if teamInControl ~= self.gameObject:getState() then
self.gameObject:setState(teamInControl)
end
end
local TeamMember = class.Class(component.Component)
function TeamMember:__init__(kwargs)
kwargs = args.parse(kwargs, {
{'name', args.default('TeamMember')},
{'team', args.stringType},
})
TeamMember.Base.__init__(self, kwargs)
self._config.team = kwargs.team
end
function TeamMember:start()
local sceneObject = self.gameObject.simulation:getSceneObject()
local avatarComponent = self.gameObject:getComponent('Avatar')
sceneObject:getComponent('HillManager'):registerAvatar(avatarComponent,
self._config.team)
end
function TeamMember:getTeam()
return self._config.team
end
local Taste = class.Class(component.Component)
function Taste:__init__(kwargs)
kwargs = args.parse(kwargs, {
{'name', args.default('Taste')},
{'mode', args.default('none'), args.oneOf('none',
'control_hill',
'paint_hill',
'zap_while_in_control')},
{'rewardAmount', args.default(0.0), args.numberType},
{'zeroMainReward', args.default(false), args.booleanType},
{'minFramesBetweenHillRewards', args.default(0), args.ge(0)},
})
Taste.Base.__init__(self, kwargs)
self._config.mode = kwargs.mode
self._config.rewardAmount = kwargs.rewardAmount
self._config.zeroMainReward = kwargs.zeroMainReward
self._config.minFramesBetweenHillRewards = kwargs.minFramesBetweenHillRewards
end
function Taste:reset()
self._hillManager = self.gameObject.simulation:getSceneObject():getComponent(
'HillManager')
self._framesSinceEvent = 0
end
function Taste:update()
self._framesSinceEvent = self._framesSinceEvent + 1
end
function Taste:paintedHillSquare(oldTeamOfThisSquare)
local teamInControl = self._hillManager:getTeamInControl()
local ownTeam = self.gameObject:getComponent('TeamMember'):getTeam()
if self._framesSinceEvent > self._config.minFramesBetweenHillRewards then
if self._config.mode == 'paint_hill' then
self.gameObject:getComponent('Avatar'):addReward(
self._config.rewardAmount)
end
if self._config.mode == 'control_hill' then
if teamInControl == 'uncontrolled' then
self.gameObject:getComponent('Avatar'):addReward(
self._config.rewardAmount)
end
end
self._framesSinceEvent = 0
end
-- Record event for player coloring the hill.
if ownTeam ~= oldTeamOfThisSquare then
local avatarComponent = self.gameObject:getComponent('Avatar')
events:add('hill_square_colored', 'dict',
'player_index', avatarComponent:getIndex(), -- int
'team', ownTeam) -- string
end
end
function Taste:zap(unusedAvatarThatGotZapped)
local teamInControl = self._hillManager:getTeamInControl()
local ownTeam = self.gameObject:getComponent('TeamMember'):getTeam()
if self._config.mode == 'zap_while_in_control' then
if teamInControl == ownTeam then
self.gameObject:getComponent('Avatar'):addReward(
self._config.rewardAmount)
end
end
end
function Taste:mainReward(avatar, isInControl)
if not self._config.zeroMainReward then
self._hillManager:sendMainReward(avatar, isInControl)
end
end
local HillManager = class.Class(component.Component)
function HillManager:__init__(kwargs)
kwargs = args.parse(kwargs, {
{'name', args.default('HillManager')},
{'percentToCapture', args.ge(0), args.le(100)},
{'rewardPerStepInControl', args.numberType},
})
HillManager.Base.__init__(self, kwargs)
self._config.percentToCapture = kwargs.percentToCapture
self._config.rewardPerStepInControl = kwargs.rewardPerStepInControl
end
function HillManager:reset()
self._numColoredByTeam = {}
self._registeredSquares = {}
self._avatarsByTeam = {}
self._teamCurrentlyInControl = "uncontrolled"
end
function HillManager:squareColored(sourceTeam, targetTeam)
if targetTeam ~= sourceTeam then
-- Bookkeeping: increment target team's hill control counter.
if not self._numColoredByTeam[targetTeam] then
self._numColoredByTeam[targetTeam] = 0
end
self._numColoredByTeam[targetTeam] = self._numColoredByTeam[targetTeam] + 1
-- Bookkeeping: decrement source team hill control counter (if applicable).
if self._numColoredByTeam[sourceTeam] then
self._numColoredByTeam[sourceTeam] =
self._numColoredByTeam[sourceTeam] - 1
end
end
end
function HillManager:_getPercentFilledByMaximalTeam()
local total = 0
local maximalTeam = "uncontrolled"
local maximalTeamAmount = 0
for team, numColored in pairs(self._numColoredByTeam) do
total = total + numColored
if numColored > maximalTeamAmount then
maximalTeam = team
maximalTeamAmount = numColored
end
end
local percentFilled = (maximalTeamAmount / total) * 100
return percentFilled, maximalTeam
end
function HillManager:_capture(capturedByTeam)
for _, square in ipairs(self._registeredSquares) do
square:capture(capturedByTeam)
end
-- Record the hill capture event.
events:add('hill_captured', 'dict',
'team', capturedByTeam) -- string
end
function HillManager:update()
local percentFilled, maximalTeam = self:_getPercentFilledByMaximalTeam()
if maximalTeam and maximalTeam ~= self._teamCurrentlyInControl then
-- Change of control
if percentFilled >= self._config.percentToCapture then
-- Successful capture
self:_capture(maximalTeam)
self._teamCurrentlyInControl = maximalTeam
else
-- Mere loss of control without a new team capturing
self._teamCurrentlyInControl = "uncontrolled"
end
end
if self._teamCurrentlyInControl ~= "uncontrolled" then
self:provideRewards(self._teamCurrentlyInControl, true)
local teamNotInControl = self:getOtherTeam(self._teamCurrentlyInControl)
self:provideRewards(teamNotInControl, false)
end
end
function HillManager:registerSquare(groundComponent)
table.insert(self._registeredSquares, groundComponent)
end
function HillManager:registerAvatar(avatar, team)
if not self._avatarsByTeam[team] then
self._avatarsByTeam[team] = {}
end
table.insert(self._avatarsByTeam[team], avatar)
end
function HillManager:provideRewards(team, isInControl)
for _, avatar in ipairs(self._avatarsByTeam[team]) do
if avatar.gameObject:hasComponent('Taste') then
-- Skip the main reward if applicable.
avatar.gameObject:getComponent('Taste'):mainReward(avatar, isInControl)
else
self:sendMainReward(avatar, isInControl)
end
end
end
function HillManager:sendMainReward(avatar, isInControl)
if isInControl then
avatar:addReward(self._config.rewardPerStepInControl)
else
avatar:addReward(-self._config.rewardPerStepInControl)
end
end
function HillManager:getTeamInControl()
return self._teamCurrentlyInControl
end
function HillManager:getOtherTeam(team)
if team == 'red' then
return 'blue'
elseif team == 'blue' then
return 'red'
end
end
local allComponents = {
-- Object components.
GroundOrHill = GroundOrHill,
ControlIndicator = ControlIndicator,
-- Avatar components.
TeamMember = TeamMember,
Taste = Taste,
-- Scene components.
HillManager = HillManager,
}
component_registry.registerAllComponents(allComponents)
return allComponents
|
local jid = require "util.jid";
local runner, waiter = require "util.async".runner, require "util.async".waiter;
--- Finds and returns room by its jid
-- @param room_jid the room jid to search in the muc component
-- @return returns room if found or nil
function get_room_from_jid(room_jid)
local _, host = jid.split(room_jid);
local component = hosts[host];
if component then
local muc = component.modules.muc
if muc and rawget(muc,"rooms") then
-- We're running 0.9.x or 0.10 (old MUC API)
return muc.rooms[room_jid];
elseif muc and rawget(muc,"get_room_from_jid") then
-- We're running >0.10 (new MUC API)
return muc.get_room_from_jid(room_jid);
else
return
end
end
end
function wrap_async_run(event,handler)
local result;
local async_func = runner(function (event)
local wait, done = waiter();
result=handler(event);
done();
return result;
end)
async_func:run(event)
return result;
end
return {
get_room_from_jid = get_room_from_jid;
wrap_async_run = wrap_async_run;
};
|
local npcid = 990001
function SkipNPC_OnGossipTalk(pUnit, event, player, pMisc)
if (player:IsInCombat() == true) then
player:SendAreaTriggerMessage("You are in combat!")
else
pUnit:SendChatMessage(12, 0, "You are about to skip the full chainquest from level sixty to eighty. We recommend to atleast get through the chainquest the first time. Skipping the chainquest will not influence your later gaming experience apart from a few miscellaneous items.")
pUnit:GossipCreateMenu(98, player, 0)
pUnit:GossipMenuAddItem(3, "|cFF008080Skip the level sixty to eighty chainquest", 3, 0)
pUnit:GossipMenuAddItem(3, "Nevermind", 9, 0)
pUnit:GossipSendMenu(player)
end
end
function SkipNPC_OnGossipSelect(pUnit, event, player, id, intid, code, pMisc)
if (player:IsInCombat() == true) then
player:SendAreaTriggerMessage("You are in combat!")
else
pUnit:GossipCreateMenu(98, player, 0)
pUnit:GossipMenuAddItem(3, "|cFF008080Skip the level sixty to eighty chainquest", 3, 0)
pUnit:GossipMenuAddItem(3, "Nevermind", 9, 0)
pUnit:GossipSendMenu(player)
end
if(intid == 3) then
pUnit:Emote(0, 2000)
player:SetPhase(2)
player:SendAreaTriggerMessage("Are you sure you want to skip the chainquest from level sixty to eighty? You will miss a great experience... ")
pUnit:GossipCreateMenu(99, player, 0)
pUnit:GossipMenuAddItem(3, "|cFF008080I am sure", 4, 0)
pUnit:GossipMenuAddItem(3, "Nevermind", 9, 0)
pUnit:GossipSendMenu(player)
end
if(intid == 4) then
local levelcount = (player:GetPlayerLevel())
local levelcount = 80 - levelcount
player:SetLevel(player:GetPlayerLevel()+levelcount)
pUnit:Emote(53, 2000)
player:AddItem(94025, 1)
player:AddItem(90131, 1)
player:SetPhase(1)
player:Teleport(619, 524.29, -564.56, 27)
pUnit:Emote(0, 2000)
end
if(intid == 9) then
player:SetPhase(1)
end
end
RegisterUnitGossipEvent(990001, 1, "SkipNPC_OnGossipTalk")
RegisterUnitGossipEvent(990001, 2, "SkipNPC_OnGossipSelect")
|
sets = {}
sets.pre_action = {}
sets.pre_action.Shiva = {
main = "Hvergelmir",
head = "Summoner's Horn",
body = "Summoner's Doublet",
hands = "Summoner's Bracers",
legs = "Summoner's Spats",
feet = "Summoner's Pigaches",
}
sets.pre_action.Ifrit = {
"Beckoner's Bracers +1",
"Hvergelmir",
"Beckoner's Doublet +1",
"Beckoner's Horn +1",
"Beckoner's Spats +1",
feet = "Beckoner's Pigaches +1",
}
sets.idle = {
"Hvergelmir",
"Summoner's Horn",
"Mithran Separates",
"Mithran Gauntlets",
"Mithran Loincloth",
"Mithran Gaiters",
"Defending Ring",
}
filter_action = function(action)
debug.message('User Filter Action',action.name)
end
pre_action = function(action)
debug.message('User Pre-Action',action.name)
if action.name == 'Shiva' then
equip(sets.pre_action.Shiva)
elseif action.name == 'Ifrit' then
equip(sets.pre_action.Ifrit)
end
end
mid_action = function(action)
debug.message('User Mid-Action',action.name)
end
post_action = function(action)
debug.message('User Post-Action',action.name)
equip(sets.idle)
end
|
--[[
Copyright 2016 10se1ucgo
https://github.com/10se1ucgo/
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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local saved_path = function() return "fence_npc/" .. string.lower(game.GetMap()) .. ".txt" end
local fence_npcs = {}
local help_msg = "Invalid arguments!\nUse 'fence_npc save' to save all locations.\nUse 'fence_npc delete' to delete all locations.\nUse 'fence_npc respawn' to respawn all locatons.\nUse 'fence_npc reload' to force reload the config file."
hook.Add("loadCustomDarkRPItems", "fence_npc_config_load", function() include('fence_npc_config.lua') end) -- Load config after DarkRP inits so TEAM enums are valid.
hook.Add("InitPostEntity", "fence_npc_load", function() timer.Simple(3, fence_npc_load) end) -- Load all saved NPCs
concommand.Add("fence_npc", function(ply, cmd, args)
if not ply:IsSuperAdmin() then
ply:PrintMessage(HUD_PRINTCONSOLE, "Superadmin only!")
return
end
if args[1] == "save" then
fence_npc_save(ply)
elseif args[1] == "delete" then
fence_npc_delete(ply)
elseif args[1] == "respawn"then
fence_npc_load(ply)
elseif args[1] == "reload" then
include('fence_npc_config.lua')
ply:PrintMessage(HUD_PRINTCONSOLE, "Config reloaded.")
else
ply:PrintMessage(HUD_PRINTCONSOLE, help_msg)
return
end
end)
function fence_npc_load(ply)
if not file.Exists("fence_npc", "DATA") then
file.CreateDir("fence_npc")
end
if not file.Exists(saved_path(), "DATA") then
if ply != nil then
ply:PrintMessage(HUD_PRINTCONSOLE, "No Fence NPC locations to respawn!")
end
return
end
for index, fence_ent in pairs(ents.FindByClass("fence_npc")) do fence_ent:Remove() end
fence_npcs = util.JSONToTable(file.Read(saved_path(), "DATA"))
for index, ent in pairs(fence_npcs) do
local fence_npc = ents.Create("fence_npc")
if IsValid(fence_npc) then
fence_npc:SetPos(ent.pos)
fence_npc:SetAngles(ent.ang)
fence_npc:Spawn()
end
end
print("Spawned " .. #fence_npcs .. " Fence NPCs.")
if ply != nil then
ply:PrintMessage(HUD_PRINTCONSOLE, "Spawned " .. #fence_npcs .. " Fence NPCs.")
end
end
function fence_npc_save(ply)
fence_npcs = {}
local all_fence_npcs = ents.FindByClass("fence_npc")
if #all_fence_npcs == 0 then
print("No NPCs to save!")
return
end
for index, ent in pairs(all_fence_npcs) do
local npc_data = {}
npc_data.pos = ent:GetPos()
npc_data.ang = ent:GetAngles()
table.insert(fence_npcs, npc_data)
end
file.Write(saved_path(), util.TableToJSON(fence_npcs))
print("Saved " .. #fence_npcs .. " NPC locations")
ply:PrintMessage(HUD_PRINTCONSOLE, "Saved " .. #fence_npcs .. " NPC locations")
end
function fence_npc_delete(ply)
fence_npcs = {}
if not file.Exists(saved_path(), "DATA") then
ply:PrintMessage(HUD_PRINTCONSOLE, "No locations to delete!")
return
end
file.Delete(saved_path())
for num, ent in pairs(ents.FindByClass("fence_npc")) do ent:Remove() end
print("Deleted all NPC locations")
ply:PrintMessage(HUD_PRINTCONSOLE, "Deleted all NPC locations")
end
|
return {'pinksteren','pin','pina','pinacotheek','pinakel','pinang','pinangnoot','pinapparaat','pinaren','pinas','pinautomaat','pincet','pincher','pinchhitter','pincode','pinda','pindachinees','pindakaas','pindaman','pindarotsje','pindasaus','pindasoep','pineut','ping','pingel','pingelaar','pingelen','pingping','pingpong','pingpongbal','pingpongen','pingpongspel','pingpongtafel','pinguin','pinguinverblijf','pink','pinkelen','pinken','pinker','pinkogen','pinkring','pinkster','pinksteravond','pinksterbeweging','pinksterbloem','pinksterdag','pinksterdinsdag','pinksterdrie','pinksterfeest','pinkstergemeente','pinkstergroepen','pinksterkroon','pinkstermaand','pinkstermaandag','pinksterroos','pinkstertheologie','pinkstertijd','pinkstervakantie','pinkstervuur','pinksterweek','pinksterweekeinde','pinksterweekend','pinksterweide','pinksterzending','pinksterzondag','pinkstier','pinkvaars','pinnen','pinnig','pinpas','pint','pintelieren','pinten','pinyin','pingponger','pingo','pinknagel','pindarisch','pindasambal','pinteriaans','pinpasfraude','pingen','pindakoek','pinksterchristen','pinkstergelovige','pinksterlied','pinatubo','pindosgebergte','pinto','pinar','pinxteren','pingen','pino','pinkse','pinckaers','pinxt','pinedo','pinacotheken','pinakels','pinakeltje','pinakeltjes','pinangnoten','pinapparaten','pinassen','pinautomaten','pinbetalingen','pincetje','pincetten','pinchers','pinchertje','pinchertjes','pincodes','pindas','pindaatje','pindaatjes','pindachinezen','pindakaaspotje','pindamannen','pindanootje','pindanootjes','pindarotsjes','pinde','pinden','pingelaars','pingelde','pingelden','pingelt','pingpongde','pingpongden','pingpongt','pingpongtafels','pinguins','pinkel','pinkelde','pinkelden','pinkelt','pinkeren','pinkers','pinkert','pinkje','pinkoog','pinkoogt','pinkringen','pinksterbloemen','pinksterdagen','pinksterfeesten','pinkstergebruiken','pinksterkronen','pinkstervakanties','pinkstervuren','pinksterweekends','pinkt','pinkte','pinkten','pinnetje','pinnetjes','pinnige','pinpassen','pintransacties','pinaarde','pinangen','pinangs','pingels','pingpongballen','pingpongballetje','pingpongballetjes','pingpongspellen','pinkoogde','pinkstergemeenten','pinkstergemeentes','pinksterrozen','pinksterweken','pinkstieren','pinkvaarzen','pins','pintelierde','pinguintje','pinchhitters','pindarische','pindasausen','pindasauzen','pingos','pingpongers','pinguinnetje','pinteriaanse','pintje','pintjes','pinars','pinkjes','pingpongspelletje','pindamannetjes','pindasausje','pindamannetje'}
|
--[[
Copyright © 2008 BartBes <bart.bes+nospam@gmail.com>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is 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 Software.
THE SOFTWARE IS 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 SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The above license is the MIT/X11 license, check the license for
information about distribution.
Also used:
-LuaSocket (MIT license) Copyright © 2004-2007 Diego Nehab. All rights reserved.
-Lua (MIT license) Copyright © 1994-2008 Lua.org, PUC-Rio.
]]--
bin = {}
bin.__index = bin
bin.null = string.char(30)
bin.one = string.char(31)
bin.defnull = bin.null
bin.defone = bin.one
function bin:setseperators(null, one)
null = null or self.defnull
one = one or self.defone
self.null = null
self.one = one
end
function bin:pack(t)
local result = ""
for i, v in pairs(t) do
result = result .. self:packvalue(i, v)
end
return result
end
function bin:packvalue(i, v)
local id = ""
local typev = type(v)
if typev == "string" then id = "S"
elseif typev == "number" then id = "N"
elseif typev == "boolean" then id = "B"
elseif typev == "userdata" then id = "U"
elseif typev == "nil" then id = "0"
else error("Type " .. typev .. " is not supported by Binary.lua") return
end
return tostring(id .. bin.one .. i .. bin.one .. tostring(v) .. bin.null)
end
function bin:unpack(s)
local t = {}
local i, v
for s2 in string.gmatch(s, "[^" .. bin.null .. "]+") do
i, v = self:unpackvalue(s2)
t[i] = v
end
return t
end
function bin:unpackvalue(s)
local id = s:sub(1, 1)
s = s:sub(3)
local len = s:find(bin.one)
local i = s:sub(1, len-1)
local v = s:sub(len+1)
if id == "N" then v = tonumber(v)
elseif id == "B" then v = (v == "true")
elseif id == "0" then v = nil
end
return i, v
end
|
p=io.popen('dir C:\\Tree\\Tree_Python /b/o/s')
for file in p:lines() do print(file) end
|
/*
GWAA:Ready hook
*/
hook.Add("InitPostEntity", "GWAA:Ready", function()
net.Start("GWAA:Ready")
net.SendToServer()
hook.Run("GWAA:Ready", LocalPlayer())
hook.Remove("InitPostEntity", "GWAA:Ready")
end)
/*
Authentication
*/
net.Receive("GWAA:Auth", function()
local jwt = net.ReadString()
if not isstring(jwt) or #jwt < 8 then return end
if GWAA._Session_JWT == nil then
hook.Run("GWAA:InitialAuthenticated", jwt)
end
hook.Run("GWAA:Authenticated", jwt)
GWAA._Session_JWT = jwt
GWAA.PrintToConsole("Received session")
end)
/*
GWAA.GetSession
*/
function GWAA.GetSession()
return GWAA._Session_JWT
end
|
local core = require('vfiler/libs/core')
local fs = require('vfiler/libs/filesystem')
local git = require('vfiler/libs/git')
local vim = require('vfiler/libs/vim')
local Directory = require('vfiler/items/directory')
------------------------------------------------------------------------------
-- ItemAttribute class
------------------------------------------------------------------------------
local ItemAttribute = {}
ItemAttribute.__index = ItemAttribute
function ItemAttribute.copy(attribute)
local root_attr = ItemAttribute.new(attribute.name)
for name, attr in pairs(attribute.opened_attributes) do
root_attr.opened_attributes[name] = ItemAttribute.copy(attr)
end
for name, selected in pairs(attribute.selected_names) do
root_attr.selected_names[name] = selected
end
return root_attr
end
function ItemAttribute.parse(root)
local root_attr = ItemAttribute.new(root.name)
if not root.children then
return root_attr
end
for _, child in ipairs(root.children) do
if child.opened then
root_attr.opened_attributes[child.name] = ItemAttribute.parse(child)
end
if child.selected then
root_attr.selected_names[child.name] = true
end
end
return root_attr
end
function ItemAttribute.new(name)
return setmetatable({
name = name,
opened_attributes = {},
selected_names = {},
}, ItemAttribute)
end
------------------------------------------------------------------------------
-- Session class
------------------------------------------------------------------------------
local Session = {}
Session.__index = Session
local shared_attributes = {}
local shared_drives = {}
local function expand(root, attribute)
for _, child in ipairs(root.children) do
local opened = attribute.opened_attributes[child.name]
if opened then
child:open()
expand(child, opened)
end
local selected = attribute.selected_names[child.name]
if selected then
child.selected = true
end
end
return root
end
function Session.new(type)
local attributes
if type == 'buffer' then
attributes = {}
elseif type == 'share' then
attributes = shared_attributes
end
local drives
if type == 'share' then
drives = shared_drives
else
drives = {}
end
return setmetatable({
_type = type,
_attributes = attributes,
_drives = drives,
}, Session)
end
function Session:copy()
local new = Session.new(self._type)
if new._type ~= 'share' then
new._drives = core.table.copy(self._drives)
end
if new._type == 'buffer' then
for path, attribute in pairs(self._attributes) do
new._attributes[path] = {
previus_path = attribute.previus_path,
object = ItemAttribute.copy(attribute.object),
}
end
end
return new
end
function Session:save(root, path)
local drive = core.path.root(root.path)
self._drives[drive] = root.path
if self._attributes then
self._attributes[root.path] = {
previus_path = path,
object = ItemAttribute.parse(root),
}
end
end
function Session:load(root)
if not self._attributes then
return nil
end
local attribute = self._attributes[root.path]
if not attribute then
return nil
end
expand(root, attribute.object)
return attribute.previus_path
end
function Session:get_path_in_drive(drive)
local dirpath = self._drives[drive]
if not dirpath then
return nil
end
return dirpath
end
------------------------------------------------------------------------------
-- Context class
------------------------------------------------------------------------------
local function walk_directories(root)
local function walk(item)
if item.children then
for _, child in ipairs(item.children) do
if child.type == 'directory' then
walk(child)
coroutine.yield(child)
end
end
end
end
return coroutine.wrap(function()
walk(root)
end)
end
local Context = {}
Context.__index = Context
--- Create a context object
---@param configs table
function Context.new(configs)
local self = setmetatable({}, Context)
self:_initialize()
self.options = core.table.copy(configs.options)
self.events = core.table.copy(configs.events)
self.mappings = core.table.copy(configs.mappings)
self._session = Session.new(self.options.session)
self._git_enabled = self:_check_git_enabled()
return self
end
--- Copy to context
function Context:copy()
local configs = {
options = self.options,
events = self.events,
mappings = self.mappings,
}
local new = Context.new(configs)
new._session = self._session:copy()
return new
end
--- Save the path in the current context
---@param path string
function Context:save(path)
if not self.root then
return
end
self._session:save(self.root, path)
end
--- Get the parent directory path of the current context
function Context:parent_path()
if self.root.parent then
return self.root.parent.path
end
return core.path.parent(self.root.path)
end
-- Reload the current directory path
function Context:reload()
local root_path = self.root.path
if vim.fn.getftime(root_path) > self.root.time then
self:switch(root_path)
return
end
local job = self:_reload_gitstatus_job(root_path)
for dir in walk_directories(self) do
if dir.opened then
if vim.fn.getftime(dir.path) > dir.time then
dir:open()
end
end
end
if job then
job:wait()
end
end
--- Switch the context to the specified directory path
---@param dirpath string
function Context:switch(dirpath)
dirpath = core.path.normalize(dirpath)
-- perform auto cd
if self.options.auto_cd then
vim.fn.execute('lcd ' .. dirpath, 'silent')
end
-- reload git status
local job = self:_reload_gitstatus_job(dirpath)
self.root = Directory.new(fs.stat(dirpath))
self.root:open()
local path = self._session:load(self.root)
if job then
job:wait()
end
return path
end
--- Switch the context to the specified drive path
---@param drive string
function Context:switch_drive(drive)
local dirpath = self._session:get_path_in_drive(drive)
if not dirpath then
dirpath = drive
end
return self:switch(dirpath)
end
--- Update from another context
---@param context table
function Context:update(context)
self.options = core.table.copy(context.options)
self.mappings = core.table.copy(context.mappings)
self.events = core.table.copy(context.events)
self._git_enabled = self:_check_git_enabled()
end
function Context:_check_git_enabled()
if not self.options.git.enabled or vim.fn.executable('git') ~= 1 then
return false
end
return self.options.columns:match('git%w*') ~= nil
end
function Context:_initialize()
self.clipboard = nil
self.extension = nil
self.linked = nil
self.root = nil
self.gitroot = nil
self.gitstatus = {}
self.in_preview = {
preview = nil,
once = false,
}
end
function Context:_reload_gitstatus_job(dirpath)
if not self._git_enabled then
return nil
end
if not (self.gitroot and dirpath:match(self.gitroot)) then
self.gitroot = git.get_toplevel(dirpath)
end
if not self.gitroot then
return nil
end
return git.reload_status(self.gitroot, {
untracked = self.options.git.untracked,
ignored = self.options.git.ignored,
}, function(status)
self.gitstatus = status
end)
end
return Context
|
local TextInput = {}
function TextInput.create()
cclog("TextInput.create")
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
TextInput.layer = layer
local res = "Images/CyanSquare.png"
local width = 200
local height = 40
local back = ccui.Scale9Sprite:create(res)
local edit = ccui.EditBox:create(cc.size(width,height),back)
layer:addChild(edit)
edit:setPosition( cc.p(250,200) )
edit:setPlaceHolder("click to input text")
local editPasswd = ccui.EditBox:create(cc.size(width,height),res)
editPasswd:setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD)
layer:addChild(editPasswd)
editPasswd:setPosition( cc.p(250,100) )
editPasswd:setPlaceHolder("click to input password")
editPasswd:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE);
return layer
end
function TextInputTestMain()
cclog("TextInputTestMain")
local scene = cc.Scene:create()
Helper.createFunctionTable = {
TextInput.create,
}
Helper.index = 1
scene:addChild(TextInput.create())
scene:addChild(CreateBackMenuItem())
return scene
end
|
--- Kaliel's Tracker
--- Copyright (c) 2012-2020, Marouan Sabbagh <mar.sabbagh@gmail.com>
--- All Rights Reserved.
---
--- This file is part of addon Kaliel's Tracker.
local addonName, addon = ...
local KT = LibStub("AceAddon-3.0"):NewAddon(addon, addonName, "LibSink-2.0")
KT:SetDefaultModuleState(false)
KT.title = GetAddOnMetadata(addonName, "Title")
KT.version = GetAddOnMetadata(addonName, "Version")
KT.gameVersion = GetBuildInfo()
KT.locale = GetLocale()
local LSM = LibStub("LibSharedMedia-3.0")
local _DBG = function(...) if _DBG then _DBG("KT", ...) end end
-- Lua API
local abs = math.abs
local floor = math.floor
local fmod = math.fmod
local format = string.format
local gsub = string.gsub
local ipairs = ipairs
local pairs = pairs
local strfind = string.find
local tonumber = tonumber
local tinsert = table.insert
local tremove = table.remove
local unpack = unpack
local round = function(n) return floor(n + 0.5) end
-- WoW API
local _G = _G
local CreateFrame = CreateFrame
local GameTooltip = GameTooltip
local HaveQuestRewardData = HaveQuestRewardData
local InCombatLockdown = InCombatLockdown
local FormatLargeNumber = FormatLargeNumber
local UIParent = UIParent
local trackerWidth = 280
local paddingBottom = 15
local mediaPath = "Interface\\AddOns\\"..addonName.."\\Media\\"
local questState = {}
local freeTags = {}
local freeButtons = {}
local msgPatterns = {}
local combatLockdown = false
local db, dbChar
-- Main frame
local KTF = CreateFrame("Frame", addonName.."Frame", UIParent)
KT.frame = KTF
-- Blizzard frame
local OTF = ObjectiveTrackerFrame
local OTFHeader = OTF.HeaderMenu
-- Constants
KT_QUEST_DASH = "- "
-- Blizzard Constants
OBJECTIVE_TRACKER_COLOR["Header"] = { r = 1, g = 0.5, b = 0 } -- orange
OBJECTIVE_TRACKER_COLOR["Complete"] = { r = 0.1, g = 0.85, b = 0.1 } -- green
OBJECTIVE_TRACKER_COLOR["CompleteHighlight"] = { r = 0, g = 1, b = 0 } -- green
OBJECTIVE_TRACKER_COLOR["TimeLeft2"] = { r = 0, g = 0.5, b = 1 } -- blue
OBJECTIVE_TRACKER_COLOR["TimeLeft2Highlight"] = { r = 0.3, g = 0.65, b = 1 } -- blue
OBJECTIVE_TRACKER_COLOR["Header"].reverse = OBJECTIVE_TRACKER_COLOR["HeaderHighlight"]
OBJECTIVE_TRACKER_COLOR["HeaderHighlight"].reverse = OBJECTIVE_TRACKER_COLOR["Header"]
OBJECTIVE_TRACKER_COLOR["Complete"].reverse = OBJECTIVE_TRACKER_COLOR["CompleteHighlight"]
OBJECTIVE_TRACKER_COLOR["CompleteHighlight"].reverse = OBJECTIVE_TRACKER_COLOR["Complete"]
OBJECTIVE_TRACKER_COLOR["TimeLeft2"].reverse = OBJECTIVE_TRACKER_COLOR["TimeLeft2Highlight"]
OBJECTIVE_TRACKER_COLOR["TimeLeft2Highlight"].reverse = OBJECTIVE_TRACKER_COLOR["TimeLeft2"]
OTF.BlocksFrame.PopupQuestHeader = CreateFrame("Frame", "PopupQuestHeader", OTF.BlocksFrame, "ObjectiveTrackerHeaderTemplate")
AUTO_QUEST_POPUP_TRACKER_MODULE:SetHeader(OTF.BlocksFrame.PopupQuestHeader, TRACKER_HEADER_QUESTS, nil)
AUTO_QUEST_POPUP_TRACKER_MODULE.blockOffsetX = -26
AUTO_QUEST_POPUP_TRACKER_MODULE.blockOffsetY = -6
SCENARIO_CONTENT_TRACKER_MODULE.blockOffsetX = -16
BONUS_OBJECTIVE_TRACKER_MODULE.blockPadding = 0
WORLD_QUEST_TRACKER_MODULE.blockPadding = 0
DEFAULT_OBJECTIVE_TRACKER_MODULE.blockTemplate = "KT_ObjectiveTrackerBlockTemplate"
DEFAULT_OBJECTIVE_TRACKER_MODULE.lineTemplate = "KT_ObjectiveTrackerLineTemplate"
BONUS_OBJECTIVE_TRACKER_MODULE.blockTemplate = "KT_BonusObjectiveTrackerBlockTemplate"
WORLD_QUEST_TRACKER_MODULE.blockTemplate = "KT_BonusObjectiveTrackerBlockTemplate"
QUEST_TRACKER_MODULE.buttonOffsets.groupFinder = { 2, 4 }
BONUS_OBJECTIVE_TRACKER_MODULE.buttonOffsets.groupFinder = { 2, 2 }
WORLD_QUEST_TRACKER_MODULE.buttonOffsets.groupFinder = { 2, 2 }
--------------
-- Internal --
--------------
local function SetHeaders(type)
local bgrColor = db.hdrBgrColorShare and KT.borderColor or db.hdrBgrColor
local txtColor = db.hdrTxtColorShare and KT.borderColor or db.hdrTxtColor
if not type or type == "background" then
for _, header in ipairs(KT.headers) do
if db.hdrBgr == 1 then
header.Background:Hide()
elseif db.hdrBgr == 2 then
header.Background:SetAtlas("Objective-Header")
header.Background:SetVertexColor(1, 1, 1)
header.Background:ClearAllPoints()
header.Background:SetPoint("TOPLEFT", -29, 14)
header.Background:Show()
elseif db.hdrBgr >= 3 then
header.Background:SetTexture(mediaPath.."UI-KT-HeaderBackground-"..(db.hdrBgr - 2))
header.Background:SetVertexColor(bgrColor.r, bgrColor.g, bgrColor.b)
header.Background:SetPoint("TOPLEFT", -20, 0)
header.Background:SetPoint("BOTTOMRIGHT", 17, -7)
header.Background:Show()
end
end
end
if not type or type == "text" then
OTFHeader.Title:SetFont(KT.font, db.fontSize, db.fontFlag)
OTFHeader.Title:SetTextColor(txtColor.r, txtColor.g, txtColor.b)
OTFHeader.Title:SetShadowColor(0, 0, 0, db.fontShadow)
for _, header in ipairs(KT.headers) do
if type == "text" then
header.Text:SetFont(KT.font, db.fontSize+1, db.fontFlag)
if db.hdrBgr == 2 then
header.Text:SetTextColor(1, 0.82, 0)
else
header.Text:SetTextColor(txtColor.r, txtColor.g, txtColor.b)
end
header.Text:SetShadowColor(0, 0, 0, db.fontShadow)
header.Text:SetPoint("LEFT", 4, 0.5)
header.animateReason = 0
end
end
end
end
local function SetMsgPatterns()
local patterns = {
-- enUS/frFR/etc. ... "%s: %d/%d"
-- deDE (only) ...... "%1$s: %2$d/%3$d"
ERR_QUEST_ADD_FOUND_SII,
ERR_QUEST_ADD_ITEM_SII,
ERR_QUEST_ADD_KILL_SII,
ERR_QUEST_ADD_PLAYER_KILL_SII,
}
for _, patt in ipairs(patterns) do
patt = "^"..patt:gsub("%d+%$", ""):gsub("%%s", ".*"):gsub("%%d", "%%d+").."$"
tinsert(msgPatterns, patt)
end
end
local function SlashHandler(msg, editbox)
local cmd, value = msg:match("^(%S*)%s*(.-)$")
if cmd == "config" then
KT:OpenOptions()
else
ObjectiveTracker_MinimizeButton_OnClick()
end
end
local function SetScrollbarPosition()
KTF.Bar:SetPoint("TOPRIGHT", -5, -round(5+(KTF.Scroll.value*(((db.maxHeight-60)/((OTF.height-db.maxHeight)/KTF.Scroll.step))/KTF.Scroll.step))))
end
local function GetTaskTimeLeftData(questID)
local timeString = ""
local timeColor = OBJECTIVE_TRACKER_COLOR["TimeLeft2"]
local timeLeftMinutes = C_TaskQuest.GetQuestTimeLeftMinutes(questID)
if timeLeftMinutes and timeLeftMinutes > 0 then
timeString = SecondsToTime(timeLeftMinutes * 60)
if timeLeftMinutes <= WORLD_QUESTS_TIME_CRITICAL_MINUTES then
timeColor = OBJECTIVE_TRACKER_COLOR["TimeLeft"]
end
end
return timeString, timeColor
end
-- Setup ---------------------------------------------------------------------------------------------------------------
local function Init()
db = KT.db.profile
if db.keyBindMinimize ~= "" then
SetOverrideBindingClick(KTF, false, db.keyBindMinimize, KTF.MinimizeButton:GetName())
end
for i, module in ipairs(db.modulesOrder) do
OTF.MODULES_UI_ORDER[i] = _G[module]
KT:SaveHeader(OTF.MODULES_UI_ORDER[i])
end
KT:MoveTracker()
KT:SetBackground()
KT:SetText()
KT.stopUpdate = false
KT.inWorld = true
if dbChar.collapsed then
ObjectiveTracker_MinimizeButton_OnClick()
end
C_Timer.After(0, function()
KT:SetQuestsHeaderText()
KT:SetAchievsHeaderText()
OTF:KTSetPoint("TOPLEFT", 30, -1)
OTF:KTSetPoint("BOTTOMRIGHT")
ObjectiveTracker_Update()
KT.initialized = true
KT.wqInitialized = true
end)
end
-- Frames --------------------------------------------------------------------------------------------------------------
local function SetFrames()
-- Main frame
KTF:SetWidth(trackerWidth)
KTF:SetFrameStrata(db.frameStrata)
KTF:SetFrameLevel(KTF:GetFrameLevel() + 25)
KTF:SetScript("OnEvent", function(_, event, ...)
_DBG("Event - "..event)
if event == "PLAYER_ENTERING_WORLD" and not KT.stopUpdate then
KT.inWorld = true
KT.inInstance = IsInInstance()
if db.collapseInInstance and KT.inInstance and not dbChar.collapsed then
ObjectiveTracker_MinimizeButton_OnClick()
end
elseif event == "PLAYER_LEAVING_WORLD" then
KT.inWorld = false
elseif event == "QUEST_WATCH_LIST_CHANGED" then
local id, added = ...
if id and not added then
if not KT.questStateStopUpdate then
questState[id] = nil
end
if KT.activeTasks[id] then
KT.activeTasks[id] = nil
end
end
KT:ToggleEmptyTracker(added)
elseif event == "TRACKED_ACHIEVEMENT_LIST_CHANGED" then
local id, added = ...
KT:ToggleEmptyTracker(added)
elseif event == "SCENARIO_UPDATE" then
local newStage = ...
if newStage == nil then
KT.inScenario = false
elseif not KT.inScenario then
KT.inScenario = true
KT:ToggleEmptyTracker(true)
end
if not newStage then
local numSpells = ScenarioObjectiveBlock.numSpells or 0
for i = 1, numSpells do
KT:RemoveFixedButton(ScenarioObjectiveBlock.spells[i])
end
ObjectiveTracker_Update()
end
elseif event == "SCENARIO_COMPLETED" then
KT.inScenario = false
KT:ToggleEmptyTracker()
elseif event == "QUEST_AUTOCOMPLETE" then
KTF.Scroll.value = 0
elseif event == "QUEST_ACCEPTED" or event == "QUEST_REMOVED" then
KT:SetQuestsHeaderText()
elseif event == "ACHIEVEMENT_EARNED" then
KT:SetAchievsHeaderText()
elseif event == "PLAYER_REGEN_ENABLED" and combatLockdown then
combatLockdown = false
KT:RemoveFixedButton()
ObjectiveTracker_Update()
elseif event == "ZONE_CHANGED_NEW_AREA" or event == "ZONE_CHANGED" then
KTF.Buttons.reanchor = (KTF.Buttons.num > 0)
elseif event == "UPDATE_BINDINGS" then
KT:UpdateHotkey()
elseif event == "PLAYER_LEVEL_UP" then
local level = ...
KT.playerLevel = level
end
end)
KTF:RegisterEvent("PLAYER_ENTERING_WORLD")
KTF:RegisterEvent("PLAYER_LEAVING_WORLD")
KTF:RegisterEvent("QUEST_WATCH_LIST_CHANGED")
KTF:RegisterEvent("TRACKED_ACHIEVEMENT_LIST_CHANGED")
KTF:RegisterEvent("SCENARIO_UPDATE")
KTF:RegisterEvent("SCENARIO_COMPLETED")
KTF:RegisterEvent("QUEST_AUTOCOMPLETE")
KTF:RegisterEvent("QUEST_ACCEPTED")
KTF:RegisterEvent("QUEST_REMOVED")
KTF:RegisterEvent("ACHIEVEMENT_EARNED")
KTF:RegisterEvent("PLAYER_REGEN_ENABLED")
KTF:RegisterEvent("ZONE_CHANGED_NEW_AREA")
KTF:RegisterEvent("ZONE_CHANGED")
KTF:RegisterEvent("UPDATE_BINDINGS")
KTF:RegisterEvent("PLAYER_LEVEL_UP")
-- DropDown frame
KT.DropDown = MSA_DropDownMenu_Create(addonName.."DropDown", KTF)
MSA_DropDownMenu_Initialize(KT.DropDown, nil, "MENU")
-- Minimize button
OTFHeader.MinimizeButton:Hide()
local button = CreateFrame("Button", addonName.."MinimizeButton", KTF)
button:SetSize(16, 16)
button:SetPoint("TOPRIGHT", -10, -8)
button:SetFrameLevel(KTF:GetFrameLevel() + 10)
button:SetNormalTexture(mediaPath.."UI-KT-HeaderButtons")
button:GetNormalTexture():SetTexCoord(0, 0.5, 0.25, 0.5)
button:RegisterForClicks("AnyDown")
button:SetScript("OnClick", function(self, btn)
if IsAltKeyDown() then
KT:OpenOptions()
elseif not KT:IsTrackerEmpty() then
ObjectiveTracker_MinimizeButton_OnClick()
end
end)
button:SetScript("OnEnter", function(self)
self:GetNormalTexture():SetVertexColor(1, 1, 1)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
local title = (db.keyBindMinimize ~= "") and KT.title.." "..NORMAL_FONT_COLOR_CODE.."("..db.keyBindMinimize..")|r" or KT.title
GameTooltip:AddLine(title, 1, 1, 1)
GameTooltip:AddLine("Alt+Click - addon Options", 0.5, 0.5, 0.5)
GameTooltip:Show()
end)
button:SetScript("OnLeave", function(self)
self:GetNormalTexture():SetVertexColor(KT.hdrBtnColor.r, KT.hdrBtnColor.g, KT.hdrBtnColor.b)
GameTooltip:Hide()
end)
KTF.MinimizeButton = button
-- Scroll frame
local Scroll = CreateFrame("ScrollFrame", addonName.."Scroll", KTF)
Scroll:SetPoint("TOPLEFT", 4, -4)
Scroll:SetPoint("BOTTOMRIGHT", -4, 4)
Scroll:SetClipsChildren(true)
Scroll:EnableMouseWheel(true)
Scroll.step = 20
Scroll.value = 0
Scroll:SetScript("OnMouseWheel", function(self, delta)
if not dbChar.collapsed and OTF.height > db.maxHeight then
if delta < 0 then
self.value = (self.value+self.step < OTF.height-db.maxHeight) and self.value + self.step or OTF.height - db.maxHeight
else
self.value = (self.value-self.step > 0) and self.value - self.step or 0
end
self:SetVerticalScroll(self.value)
if db.frameScrollbar then
SetScrollbarPosition()
end
if self.value > 0 and self.value < OTF.height-db.maxHeight then
MSA_CloseDropDownMenus()
end
_DBG("SCROLL ... "..self.value.." ... "..OTF.height.." - "..db.maxHeight)
end
end)
KTF.Scroll = Scroll
-- Scroll child frame
local Child = CreateFrame("Frame", addonName.."ScrollChild", KTF.Scroll)
Child:SetSize(trackerWidth-8, 8000)
KTF.Scroll:SetScrollChild(Child)
-- Scroll indicator
local Bar = CreateFrame("Frame", addonName.."ScrollBar", KTF)
Bar:SetSize(2, 50)
Bar:SetPoint("TOPRIGHT", -5, -5)
Bar:SetFrameLevel(KTF:GetFrameLevel() + 10)
Bar.texture = Bar:CreateTexture()
Bar.texture:SetAllPoints()
Bar:Hide()
KTF.Bar = Bar
-- Blizzard frame
OTF:KTSetPoint("TOPLEFT")
OTF:KTSetParent(Child)
OTFHeader:Show()
OTFHeader.Hide = function() end
OTFHeader.SetShown = function() end
OTFHeader:SetSize(10, 21)
OTFHeader:ClearAllPoints()
OTFHeader:SetPoint("TOPLEFT", -20, -1)
OTFHeader.Title:ClearAllPoints()
OTFHeader.Title:SetPoint("LEFT", -5, -1)
OTFHeader.Title:SetWidth(trackerWidth - 40)
OTFHeader.Title:SetJustifyH("LEFT")
OTFHeader.Title:SetWordWrap(false)
ScenarioBlocksFrame:SetWidth(243)
-- Other buttons
KT:ToggleOtherButtons()
-- Buttons frame
local Buttons = CreateFrame("Frame", addonName.."Buttons", UIParent)
Buttons:SetSize(40, 40)
Buttons:SetPoint("TOPLEFT", 0, 0)
Buttons:SetFrameStrata(db.frameStrata)
Buttons:SetFrameLevel(KTF:GetFrameLevel() - 1)
Buttons:SetAlpha(0)
Buttons.num = 0
Buttons.reanchor = false
KTF.Buttons = Buttons
-- Frame locks
if FRAMELOCK_STATES and FRAMELOCK_STATES.PETBATTLES then
FRAMELOCK_STATES.PETBATTLES[addonName.."Frame"] = "hidden"
FRAMELOCK_STATES.PETBATTLES[addonName.."Buttons"] = "hidden"
end
end
-- Hooks ---------------------------------------------------------------------------------------------------------------
local function SetHooks()
local function SetFixedButton(block, idx, height, yOfs)
if block.fixedTag and KT.fixedButtons[block.id] then
idx = idx + 1
block.fixedTag.text:SetText(idx)
KT.fixedButtons[block.id].text:SetText(idx)
KT.fixedButtons[block.id].num = idx
yOfs = -(height + 7)
height = height + 26 + 3
KT.fixedButtons[block.id]:SetPoint("TOP", 0, yOfs)
end
return idx, height, yOfs
end
local function FixedButtonsReanchor()
if InCombatLockdown() then
if KTF.Buttons.num > 0 then
combatLockdown = true
end
else
if KTF.Buttons.reanchor then
local questID, block, questLogIndex, yOfs
local idx = 0
local contentsHeight = 0
-- Scenario
_DBG(" - REANCHOR buttons - Scen", true)
local numSpells = ScenarioObjectiveBlock.numSpells or 0
for i = 1, numSpells do
block = ScenarioObjectiveBlock.spells[i]
if block and block.SpellButton then
idx, contentsHeight, yOfs = SetFixedButton(block, idx, contentsHeight, yOfs)
end
end
-- World Quest items
_DBG(" - REANCHOR buttons - WQ", true)
local tasksTable = GetTasksTable()
for i = 1, #tasksTable do
questID = tasksTable[i]
questLogIndex = GetQuestLogIndexByID(questID)
if questLogIndex > 0 and QuestUtils_IsQuestWorldQuest(questID) and not IsWorldQuestWatched(questID) then
block = WORLD_QUEST_TRACKER_MODULE.usedBlocks[questID]
if block and block.itemButton then
idx, contentsHeight, yOfs = SetFixedButton(block, idx, contentsHeight, yOfs)
end
end
end
for i = 1, GetNumWorldQuestWatches() do
questID = GetWorldQuestWatchInfo(i)
if questID then
block = WORLD_QUEST_TRACKER_MODULE.usedBlocks[questID]
if block and block.itemButton then
idx, contentsHeight, yOfs = SetFixedButton(block, idx, contentsHeight, yOfs)
end
end
end
-- Quest items
_DBG(" - REANCHOR buttons - Q", true)
for i = 1, GetNumQuestWatches() do
questID = GetQuestWatchInfo(i)
block = QUEST_TRACKER_MODULE.usedBlocks[questID]
if block and block.itemButton then
idx, contentsHeight, yOfs = SetFixedButton(block, idx, contentsHeight, yOfs)
end
end
if contentsHeight > 0 then
contentsHeight = contentsHeight + 7 + 4
end
KTF.Buttons:SetHeight(contentsHeight)
KTF.Buttons.num = idx
KTF.Buttons.reanchor = false
end
if dbChar.collapsed or KTF.Buttons.num == 0 then
KTF.Buttons:Hide()
else
KTF.Buttons:Show()
end
KT.ActiveButton:Update()
end
if dbChar.collapsed or KTF.Buttons.num == 0 then
KTF.Buttons:SetAlpha(0)
else
KTF.Buttons:SetAlpha(1)
end
end
OTF:HookScript("OnEvent", function(self, event)
if event == "PLAYER_ENTERING_WORLD" and not KT.initialized then
Init()
end
end)
local bck_ObjectiveTracker_Update = ObjectiveTracker_Update
ObjectiveTracker_Update = function(reason, id)
if KT.stopUpdate then return end
if reason ~= OBJECTIVE_TRACKER_UPDATE_STATIC then
local dbgReason
if reason == OBJECTIVE_TRACKER_UPDATE_ALL then
dbgReason = "FFFFFFFF"
else
dbgReason = reason and format("%x", reason) or ""
end
_DBG("|cffffff00Update ... "..dbgReason, true)
end
bck_ObjectiveTracker_Update(reason, id)
FixedButtonsReanchor()
if dbChar.collapsed then
local _, numQuests = GetNumQuestLogEntries()
local title = ""
if db.hdrCollapsedTxt == 2 then
title = "|T"..mediaPath.."KT_logo:22:22:0:1|t"..("%d/%d"):format(numQuests, MAX_QUESTS)
elseif db.hdrCollapsedTxt == 3 then
title = "|T"..mediaPath.."KT_logo:22:22:0:1|t"..("%d/%d Quests"):format(numQuests, MAX_QUESTS)
end
OTFHeader.Title:SetText(title)
end
if reason == OBJECTIVE_TRACKER_UPDATE_STATIC then
return
elseif KT.IsTableEmpty(KT.activeTasks) then
KT:ToggleEmptyTracker()
end
KT:SetSize()
end
function DEFAULT_OBJECTIVE_TRACKER_MODULE:AddObjective(block, objectiveKey, text, lineType, useFullHeight, dashStyle, colorStyle, adjustForNoText, overrideHeight) -- RO
if objectiveKey == "TimeLeft" then
text, colorStyle = GetTaskTimeLeftData(block.id)
self:FreeProgressBar(block, block.currentLine) -- fix ProgressBar duplicity
elseif objectiveKey == 0 then -- Bonus Objective as a Header
block.title = text
end
if self == ACHIEVEMENT_TRACKER_MODULE and text == "" then
text = "..." -- fix Blizz bug
end
local _, _, leftText, colon, progress, numHave, numNeed, rightText = strfind(text, "(.-)(%s?:?%s?)((%d+)%s?/%s?(%d+))(.*)")
if progress then
if tonumber(numHave) > 0 and tonumber(numHave) < tonumber(numNeed) then
progress = "|cffc8c800" .. progress .. "|r"
end
if not db.objNumSwitch then
text = leftText .. colon .. progress .. rightText
else
text = progress
if rightText ~= " " then
text = text .. rightText
end
if leftText ~= "" then
text = text .. " " .. leftText
end
end
end
local line = self:GetLine(block, objectiveKey, lineType);
-- width
if ( block.lineWidth ~= line.width ) then
line.Text:SetWidth(block.lineWidth or self.lineWidth);
line.width = block.lineWidth; -- default should be nil
end
-- dash
if ( line.Dash ) then
if ( not dashStyle ) then
dashStyle = OBJECTIVE_DASH_STYLE_SHOW;
end
if ( line.dashStyle ~= dashStyle ) then
if ( dashStyle == OBJECTIVE_DASH_STYLE_SHOW ) then
line.Dash:Show();
line.Dash:SetText(KT_QUEST_DASH);
elseif ( dashStyle == OBJECTIVE_DASH_STYLE_HIDE ) then
line.Dash:Hide();
line.Dash:SetText(KT_QUEST_DASH);
elseif ( dashStyle == OBJECTIVE_DASH_STYLE_HIDE_AND_COLLAPSE ) then
line.Dash:Hide();
line.Dash:SetText(nil);
else
error("Invalid dash style: " .. tostring(dashStyle));
end
line.dashStyle = dashStyle;
end
if not line.Dash.KTskinned or KT.forcedUpdate then
line.Dash:SetFont(KT.font, db.fontSize, db.fontFlag)
line.Dash:SetShadowColor(0, 0, 0, db.fontShadow)
line.Dash.KTskinned = true
end
end
-- check
if line.Check and (not line.Check.KTskinned or KT.forcedUpdate) then
line.Check:SetSize(db.fontSize-2.5, db.fontSize-2.5)
line.Check:ClearAllPoints()
line.Check:SetPoint("TOPLEFT", -db.fontSize*0.2+(db.fontFlag == "" and 0 or 1), -2)
line.Check.KTskinned = true
end
-- set the text
local textHeight = self:SetStringText(line.Text, text, useFullHeight, colorStyle, block.isHighlighted);
local height = overrideHeight or textHeight;
line:SetHeight(height);
local yOffset;
if ( adjustForNoText and text == "" ) then
-- don't change the height
-- move the line up so the next object ends up in the same position as if there had been no line
yOffset = height;
else
block.height = block.height + height + block.module.lineSpacing;
yOffset = -block.module.lineSpacing;
end
-- anchor the line
local anchor = block.currentLine or block.HeaderText;
if ( anchor ) then
line:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, yOffset);
else
line:SetPoint("TOPLEFT", 0, yOffset);
end
block.currentLine = line;
-- completion state
if KT.inWorld and type(objectiveKey) == "string" then
if strfind(objectiveKey, "Complete") then
if not questState[block.id] or questState[block.id] ~= "complete" then
if db.messageQuest then
KT:SetMessage(block.title, 0, 1, 0, ERR_QUEST_COMPLETE_S, "Interface\\GossipFrame\\ActiveQuestIcon", -2, 0)
end
if db.soundQuest then
KT:PlaySound(db.soundQuestComplete)
end
questState[block.id] = "complete"
end
elseif strfind(objectiveKey, "Failed") then
if not questState[block.id] or questState[block.id] ~= "failed" then
if db.messageQuest then
KT:SetMessage(block.title, 1, 0, 0, ERR_QUEST_FAILED_S, "Interface\\GossipFrame\\AvailableQuestIcon", -2, 0)
end
questState[block.id] = "failed"
end
end
end
return line;
end
function DEFAULT_OBJECTIVE_TRACKER_MODULE:SetStringText(fontString, text, useFullHeight, colorStyle, useHighlight) -- RO
if not fontString.KTskinned or KT.forcedUpdate then
fontString:SetFont(KT.font, db.fontSize, db.fontFlag)
fontString:SetShadowColor(0, 0, 0, db.fontShadow)
fontString:SetWordWrap(db.textWordWrap)
fontString.KTskinned = true
end
if self == QUEST_TRACKER_MODULE and not useHighlight then
useHighlight = fontString:GetParent().isHighlighted -- Fix Blizz bug
end
if useFullHeight then
fontString:SetMaxLines(0)
else
fontString:SetMaxLines(2)
end
fontString:SetText(text)
local stringHeight = fontString:GetHeight()
colorStyle = colorStyle or OBJECTIVE_TRACKER_COLOR["Normal"]
if ( useHighlight and colorStyle.reverse ) then
colorStyle = colorStyle.reverse
end
if ( fontString.colorStyle ~= colorStyle ) then
fontString:SetTextColor(colorStyle.r, colorStyle.g, colorStyle.b)
fontString.colorStyle = colorStyle
end
return stringHeight
end
local function ShouldShowWarModeBonus(questID, currencyID, firstInstance) -- R
if not C_PvP.IsWarModeDesired() then
return false;
end
local warModeBonusApplies, limitOncePerTooltip = C_CurrencyInfo.DoesWarModeBonusApply(currencyID);
if not warModeBonusApplies or (limitOncePerTooltip and not firstInstance) then
return false;
end
return QuestUtils_IsQuestWorldQuest(questID) and C_QuestLog.QuestHasWarModeBonus(questID) and not C_CurrencyInfo.GetFactionGrantedByCurrency(currencyID);
end
function QuestUtils_AddQuestCurrencyRewardsToTooltip(questID, tooltip, currencyContainerTooltip) -- RO
local numQuestCurrencies = GetNumQuestLogRewardCurrencies(questID);
local currencies = { };
local uniqueCurrencyIDs = { };
for i = 1, numQuestCurrencies do
local name, texture, numItems, currencyID = GetQuestLogRewardCurrencyInfo(i, questID);
local rarity = select(8, GetCurrencyInfo(currencyID));
local firstInstance = not uniqueCurrencyIDs[currencyID];
if firstInstance then
uniqueCurrencyIDs[currencyID] = true;
end
local currencyInfo = { name = name, texture = texture, numItems = numItems, currencyID = currencyID, rarity = rarity, firstInstance = firstInstance };
tinsert(currencies, currencyInfo);
end
table.sort(currencies,
function(currency1, currency2)
if currency1.rarity ~= currency2.rarity then
return currency1.rarity > currency2.rarity;
end
return currency1.currencyID > currency2.currencyID;
end
);
local addedQuestCurrencies = 0;
local alreadyUsedCurrencyContainerId = 0; --In the case of multiple currency containers needing to displayed, we only display the first.
local warModeBonus = C_PvP.GetWarModeRewardBonus();
for i, currencyInfo in ipairs(currencies) do
local isCurrencyContainer = C_CurrencyInfo.IsCurrencyContainer(currencyInfo.currencyID, currencyInfo.numItems);
if ( currencyContainerTooltip and isCurrencyContainer and (alreadyUsedCurrencyContainerId == 0) ) then
if ( EmbeddedItemTooltip_SetCurrencyByID(currencyContainerTooltip, currencyInfo.currencyID, currencyInfo.numItems) ) then
if ShouldShowWarModeBonus(questID, currencyInfo.currencyID, currencyInfo.firstInstance) then
currencyContainerTooltip.Tooltip:AddLine(WAR_MODE_BONUS_PERCENTAGE_FORMAT:format(warModeBonus));
currencyContainerTooltip.Tooltip:Show();
end
if ( not tooltip ) then
break;
end
addedQuestCurrencies = addedQuestCurrencies + 1;
alreadyUsedCurrencyContainerId = currencyInfo.currencyID;
end
elseif ( tooltip ) then
if( alreadyUsedCurrencyContainerId ~= currencyInfo.currencyID ) then --if there's already a currency container of this same type skip it entirely
local text, color
if currencyInfo.currencyID == 1553 then -- Azerite
text = format(BONUS_OBJECTIVE_ARTIFACT_XP_FORMAT, FormatLargeNumber(currencyInfo.numItems))
color = { r = 1, g = 1, b = 1 }
else
text = BONUS_OBJECTIVE_REWARD_WITH_COUNT_FORMAT:format(currencyInfo.texture, currencyInfo.numItems, currencyInfo.name)
color = GetColorForCurrencyReward(currencyInfo.currencyID, currencyInfo.numItems)
end
tooltip:AddLine(text, color.r, color.g, color.b)
if ShouldShowWarModeBonus(questID, currencyInfo.currencyID, currencyInfo.firstInstance) then
tooltip:AddLine(WAR_MODE_BONUS_PERCENTAGE_FORMAT:format(warModeBonus));
end
addedQuestCurrencies = addedQuestCurrencies + 1;
end
end
end
return addedQuestCurrencies, alreadyUsedCurrencyContainerId > 0;
end
hooksecurefunc(DEFAULT_OBJECTIVE_TRACKER_MODULE, "OnBlockHeaderEnter", function(self, block)
local colorStyle, _
if block.module == QUEST_TRACKER_MODULE then
if block.questCompleted then
colorStyle = OBJECTIVE_TRACKER_COLOR["CompleteHighlight"]
elseif db.colorDifficulty then
_, colorStyle = GetQuestDifficultyColor(block.level)
end
end
if colorStyle then
block.HeaderText:SetTextColor(colorStyle.r, colorStyle.g, colorStyle.b)
block.HeaderText.colorStyle = colorStyle
end
if db.tooltipShow and (block.module == QUEST_TRACKER_MODULE or block.module == ACHIEVEMENT_TRACKER_MODULE) then
GameTooltip:SetOwner(block, "ANCHOR_NONE")
GameTooltip:ClearAllPoints()
if KTF.anchorLeft then
GameTooltip:SetPoint("TOPLEFT", block, "TOPRIGHT", 12, 1)
else
GameTooltip:SetPoint("TOPRIGHT", block, "TOPLEFT", -32, 1)
end
if block.module == QUEST_TRACKER_MODULE then
GameTooltip:SetHyperlink(GetQuestLink(block.id))
if db.tooltipShowRewards then
KT.GameTooltip_AddQuestRewardsToTooltip(GameTooltip, block.id)
end
if IsInGroup() then
GameTooltip:AddLine(" ")
GameTooltip:AddLine(PARTY..":")
GameTooltip:SetQuestPartyProgress(block.id, true)
end
else
GameTooltip:SetHyperlink(GetAchievementLink(block.id))
end
if db.tooltipShowID then
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(" ", "ID: |cffffffff"..block.id)
end
GameTooltip:Show()
end
if block.fixedTag then
colorStyle = OBJECTIVE_TRACKER_COLOR["NormalHighlight"]
block.fixedTag:SetBackdropColor(colorStyle.r, colorStyle.g, colorStyle.b)
block.fixedTag.text:SetTextColor(colorStyle.r, colorStyle.g, colorStyle.b)
end
end)
hooksecurefunc(DEFAULT_OBJECTIVE_TRACKER_MODULE, "OnBlockHeaderLeave", function(self, block)
local colorStyle
if block.module == QUEST_TRACKER_MODULE then
if block.questCompleted then
colorStyle = OBJECTIVE_TRACKER_COLOR["Complete"]
elseif db.colorDifficulty then
colorStyle = GetQuestDifficultyColor(block.level)
end
end
if colorStyle then
block.HeaderText:SetTextColor(colorStyle.r, colorStyle.g, colorStyle.b)
block.HeaderText.colorStyle = colorStyle
end
if db.tooltipShow then
GameTooltip:Hide()
end
if block.fixedTag then
colorStyle = OBJECTIVE_TRACKER_COLOR["Normal"]
block.fixedTag:SetBackdropColor(colorStyle.r, colorStyle.g, colorStyle.b)
block.fixedTag.text:SetTextColor(colorStyle.r, colorStyle.g, colorStyle.b)
end
end)
function QUEST_TRACKER_MODULE:OnBlockHeaderEnter(block) -- R
DEFAULT_OBJECTIVE_TRACKER_MODULE:OnBlockHeaderEnter(block)
end
function QUEST_TRACKER_MODULE:OnBlockHeaderLeave(block) -- R
DEFAULT_OBJECTIVE_TRACKER_MODULE:OnBlockHeaderLeave(block)
end
hooksecurefunc(QUEST_TRACKER_MODULE, "OnBlockHeaderClick", function(self, block, mouseButton)
GameTooltip:Hide()
end)
hooksecurefunc(ACHIEVEMENT_TRACKER_MODULE, "OnBlockHeaderClick", function(self, block, mouseButton)
GameTooltip:Hide()
end)
function KT_ObjectiveTrackerBlock_OnEnter(self)
self.module:OnBlockHeaderEnter(self)
end
function KT_ObjectiveTrackerBlock_OnLeave(self)
self.module:OnBlockHeaderLeave(self)
end
function KT_ObjectiveTrackerBlock_OnClick(self, mouseButton)
self.module:OnBlockHeaderClick(self, mouseButton)
end
local bck_ObjectiveTracker_AddBlock = ObjectiveTracker_AddBlock
ObjectiveTracker_AddBlock = function(block, forceAdd)
local blockAdded = bck_ObjectiveTracker_AddBlock(block, forceAdd)
if blockAdded then
if block.module == BONUS_OBJECTIVE_TRACKER_MODULE or block.module == WORLD_QUEST_TRACKER_MODULE then
block:SetWidth(OBJECTIVE_TRACKER_LINE_WIDTH + 4)
end
end
return blockAdded
end
hooksecurefunc(DEFAULT_OBJECTIVE_TRACKER_MODULE, "FreeUnusedLines", function(self, block)
local colorStyle
if block.questCompleted then
colorStyle = OBJECTIVE_TRACKER_COLOR["Complete"]
elseif db.colorDifficulty and self == QUEST_TRACKER_MODULE then
colorStyle = GetQuestDifficultyColor(block.level)
end
if colorStyle then
block.HeaderText:SetTextColor(colorStyle.r, colorStyle.g, colorStyle.b)
block.HeaderText.colorStyle = colorStyle
end
end)
local function CreateFixedTag(block, x, y, anchor)
local tag = block.fixedTag
if not tag then
local numFreeButtons = #freeTags
if numFreeButtons > 0 then
tag = freeTags[numFreeButtons]
tremove(freeTags, numFreeButtons)
tag:SetParent(block)
tag:ClearAllPoints()
else
tag = CreateFrame("Frame", nil, block)
tag:SetSize(32, 32)
tag:SetBackdrop({ bgFile = mediaPath.."UI-KT-QuestItemTag" })
tag.text = tag:CreateFontString(nil, "ARTWORK", "GameFontNormalMed1")
tag.text:SetFont(LSM:Fetch("font", "Arial Narrow"), 13, "")
tag.text:SetPoint("CENTER", -0.5, 1)
end
tag:SetPoint(anchor or "TOPRIGHT", block, x, y)
tag:Show()
block.fixedTag = tag
end
local colorStyle = OBJECTIVE_TRACKER_COLOR["Normal"]
if block.isHighlighted and colorStyle.reverse then
colorStyle = colorStyle.reverse
end
tag:SetBackdropColor(colorStyle.r, colorStyle.g, colorStyle.b)
tag.text:SetTextColor(colorStyle.r, colorStyle.g, colorStyle.b)
end
local function CreateFixedButton(block, isSpell)
local questID = block.id
local button = KT:GetFixedButton(questID)
if not button then
if InCombatLockdown() then
_DBG(" - STOP Create button")
combatLockdown = true
return nil
end
local numFreeButtons = #freeButtons
if numFreeButtons > 0 then
_DBG(" - USE button "..questID)
button = freeButtons[numFreeButtons]
tremove(freeButtons, numFreeButtons)
else
_DBG(" - CREATE button "..questID)
local name = addonName.."Button"..time()..questID
button = CreateFrame("Button", name, KTF.Buttons, "SecureActionButtonTemplate") --"KTQuestObjectiveItemButtonTemplate"
button:SetSize(26, 26)
button.icon = button:CreateTexture(name.."Icon", "BORDER")
button.icon:SetAllPoints()
button.Icon = button.icon -- for Spell
button.Count = button:CreateFontString(name.."Count", "BORDER", "NumberFontNormal")
button.Count:SetJustifyH("RIGHT")
button.Count:SetPoint("BOTTOMRIGHT", button.icon, -3, 2)
button.Cooldown = CreateFrame("Cooldown", name.."Cooldown", button, "CooldownFrameTemplate")
button.Cooldown:SetAllPoints()
button.HotKey = button:CreateFontString(name.."HotKey", "ARTWORK", "NumberFontNormalSmallGray")
button.HotKey:SetSize(29, 10)
button.HotKey:SetJustifyH("RIGHT")
button.HotKey:SetText(RANGE_INDICATOR)
button.HotKey:SetPoint("TOPRIGHT", button.icon, 2, -2)
button.text = button:CreateFontString(name.."Text", "ARTWORK", "NumberFontNormalSmall")
button.text:SetSize(29, 10)
button.text:SetJustifyH("LEFT")
button.text:SetPoint("TOPLEFT", button.icon, 1, -3)
button:RegisterForClicks("AnyUp")
button:SetNormalTexture("Interface\\Buttons\\UI-Quickslot2")
do local tex = button:GetNormalTexture()
tex:ClearAllPoints()
tex:SetPoint("CENTER")
tex:SetSize(44, 44)
end
button:SetPushedTexture("Interface\\Buttons\\UI-Quickslot-Depress")
button:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square", "ADD")
button:SetFrameLevel(KTF:GetFrameLevel() + 1)
button:Hide() -- Cooldown init
KT:Masque_AddButton(button)
end
if not isSpell then
button:SetScript("OnEvent", QuestObjectiveItem_OnEvent)
button:SetScript("OnUpdate", QuestObjectiveItem_OnUpdate)
button:SetScript("OnShow", QuestObjectiveItem_OnShow)
button:SetScript("OnHide", QuestObjectiveItem_OnHide)
button:SetScript("OnEnter", QuestObjectiveItem_OnEnter)
button:SetScript("OnLeave", QuestObjectiveItem_OnLeave)
else
button.HotKey:Hide()
button:SetScript("OnEvent", nil)
button:SetScript("OnUpdate", nil)
button:SetScript("OnShow", nil)
button:SetScript("OnHide", nil)
button:SetScript("OnEnter", ScenarioSpellButton_OnEnter)
button:SetScript("OnLeave", GameTooltip_Hide)
end
button:SetAttribute("type", isSpell and "spell" or "item")
button:Show()
KT.fixedButtons[questID] = button
KTF.Buttons.reanchor = true
end
button.block = block
button:SetAlpha(1)
if db.qiActiveButton and KTF.ActiveButton.questID == questID then
KT.ActiveButton:Update(questID)
end
return button
end
hooksecurefunc(DEFAULT_OBJECTIVE_TRACKER_MODULE, "SetBlockHeader", function(self, block, text)
block.lineWidth = block.lineWidth or self.lineWidth - 8 -- mod default
end)
local bck_QUEST_TRACKER_MODULE_SetBlockHeader = QUEST_TRACKER_MODULE.SetBlockHeader
function QUEST_TRACKER_MODULE:SetBlockHeader(block, text, questLogIndex, isQuestComplete, questID)
local _, level, suggestedGroup, _, _, _, frequency, _ = GetQuestLogTitle(questLogIndex)
if db.questShowTags then
local tagID, _ = GetQuestTagInfo(questID)
text = KT:CreateQuestTag(level, tagID, frequency, suggestedGroup)..text
end
bck_QUEST_TRACKER_MODULE_SetBlockHeader(self, block, text, questLogIndex, isQuestComplete, questID)
block.lineWidth = block.lineWidth or self.lineWidth - 8 -- mod default
block.level = level
block.title = text
local link, item, charges, showItemWhenComplete = GetQuestLogSpecialItemInfo(questLogIndex)
if item and (not isQuestComplete or showItemWhenComplete) then
block.itemButton:Hide()
CreateFixedTag(block, 3, 4)
local button = CreateFixedButton(block)
if not InCombatLockdown() then
button:SetID(questLogIndex)
button.charges = charges
button.rangeTimer = -1
button.item = item
button.link = link
SetItemButtonTexture(button, item)
SetItemButtonCount(button, charges)
QuestObjectiveItem_UpdateCooldown(button)
button:SetAttribute("item", link)
end
else
KT:RemoveFixedButton(block)
end
end
local bck_QUEST_TRACKER_MODULE_OnFreeBlock = QUEST_TRACKER_MODULE.OnFreeBlock
function QUEST_TRACKER_MODULE:OnFreeBlock(block)
KT:RemoveFixedButton(block)
bck_QUEST_TRACKER_MODULE_OnFreeBlock(self, block)
end
local function SetQuestItemButton(block)
local questLogIndex = GetQuestLogIndexByID(block.id)
local link, item, charges, showItemWhenComplete = GetQuestLogSpecialItemInfo(questLogIndex)
if item and (not isQuestComplete or showItemWhenComplete) then
block.itemButton:Hide()
CreateFixedTag(block, 0, 2)
local button = CreateFixedButton(block)
if not InCombatLockdown() then
button:SetID(questLogIndex)
button.charges = charges
button.rangeTimer = -1
button.item = item
button.link = link
SetItemButtonTexture(button, item)
SetItemButtonCount(button, charges)
QuestObjectiveItem_UpdateCooldown(button)
button:SetAttribute("item", link)
end
else
KT:RemoveFixedButton(block)
end
end
hooksecurefunc(WORLD_QUEST_TRACKER_MODULE, "Update", function(self)
local block, questID, questLogIndex
local tasksTable = GetTasksTable()
for i = 1, #tasksTable do
questID = tasksTable[i]
questLogIndex = GetQuestLogIndexByID(questID)
if questLogIndex > 0 and QuestUtils_IsQuestWorldQuest(questID) and not IsWorldQuestWatched(questID) then
block = self.usedBlocks[questID]
if block then
block.TrackedQuest:SetPoint("TOPLEFT", -2, 0)
SetQuestItemButton(block)
end
end
end
if self.ShowWorldQuests then
for i = 1, GetNumWorldQuestWatches() do
questID = GetWorldQuestWatchInfo(i)
if questID then
block = self.usedBlocks[questID]
if block then
block.TrackedQuest:SetPoint("TOPLEFT", -2, 0)
SetQuestItemButton(block)
end
end
end
end
end)
local bck_WORLD_QUEST_TRACKER_MODULE_OnFreeBlock = WORLD_QUEST_TRACKER_MODULE.OnFreeBlock
function WORLD_QUEST_TRACKER_MODULE:OnFreeBlock(block)
if KT.activeTasks[block.id] then
KT.activeTasks[block.id] = nil
end
KT:RemoveFixedButton(block)
bck_WORLD_QUEST_TRACKER_MODULE_OnFreeBlock(self, block)
end
local bck_BONUS_OBJECTIVE_TRACKER_MODULE_OnFreeBlock = BONUS_OBJECTIVE_TRACKER_MODULE.OnFreeBlock
function BONUS_OBJECTIVE_TRACKER_MODULE:OnFreeBlock(block)
if KT.activeTasks[block.id] then
KT.activeTasks[block.id] = nil
end
KT:RemoveFixedButton(block)
bck_BONUS_OBJECTIVE_TRACKER_MODULE_OnFreeBlock(self, block)
end
hooksecurefunc("BonusObjectiveTracker_UntrackWorldQuest", function(questID)
KT:ToggleEmptyTracker(not KT.IsTableEmpty(KT.activeTasks))
end)
local function SetProgressBarStyle(progressBar)
if not progressBar.KTskinned or KT.forcedUpdate then
local block = progressBar.block
block.height = block.height - progressBar.height
progressBar:SetSize(232, 23)
progressBar.height = 23
--_C(progressBar, { r = 0, g = 1, b = 0 })
progressBar.Bar:SetSize(208, 13)
progressBar.Bar:EnableMouse(false)
progressBar.Bar:ClearAllPoints()
if progressBar.Bar.BarFrame then
-- World Quest
progressBar.Bar:SetPoint("LEFT", 22, 0)
progressBar.Bar.BarFrame:Hide()
progressBar.Bar.BarFrame2:Hide()
progressBar.Bar.BarFrame3:Hide()
progressBar.Bar.BarGlow:Hide()
progressBar.Bar.Sheen:Hide()
progressBar.Bar.Starburst:Hide()
else
-- Default
progressBar.Bar:SetPoint("LEFT", 2, 0)
progressBar.Bar.BorderLeft:Hide()
progressBar.Bar.BorderRight:Hide()
progressBar.Bar.BorderMid:Hide()
end
local border1 = progressBar.Bar:CreateTexture(nil, "BACKGROUND", nil, -2)
border1:SetPoint("TOPLEFT", -1, 1)
border1:SetPoint("BOTTOMRIGHT", 1, -1)
border1:SetColorTexture(0, 0, 0)
local border2 = progressBar.Bar:CreateTexture(nil, "BACKGROUND", nil, -3)
border2:SetPoint("TOPLEFT", -2, 2)
border2:SetPoint("BOTTOMRIGHT", 2, -2)
border2:SetColorTexture(0.4, 0.4, 0.4)
progressBar.Bar.Label:SetPoint("CENTER", 0, 0.5)
progressBar.Bar.Label:SetFont(LSM:Fetch("font", "Arial Narrow"), 13, "")
progressBar.Bar:SetStatusBarTexture(LSM:Fetch("statusbar", db.progressBar))
progressBar.KTskinned = true
progressBar.isSkinned = true -- ElvUI hack
block.height = block.height + progressBar.height
end
end
local bck_DEFAULT_OBJECTIVE_TRACKER_MODULE_AddProgressBar = DEFAULT_OBJECTIVE_TRACKER_MODULE.AddProgressBar
function DEFAULT_OBJECTIVE_TRACKER_MODULE:AddProgressBar(block, line, questID)
local progressBar = bck_DEFAULT_OBJECTIVE_TRACKER_MODULE_AddProgressBar(self, block, line, questID)
SetProgressBarStyle(progressBar)
return progressBar
end
local bck_BONUS_OBJECTIVE_TRACKER_MODULE_AddProgressBar = BONUS_OBJECTIVE_TRACKER_MODULE.AddProgressBar
function BONUS_OBJECTIVE_TRACKER_MODULE:AddProgressBar(block, line, questID, finished)
local progressBar = bck_BONUS_OBJECTIVE_TRACKER_MODULE_AddProgressBar(self, block, line, questID, finished)
SetProgressBarStyle(progressBar)
return progressBar
end
local bck_WORLD_QUEST_TRACKER_MODULE_AddProgressBar = WORLD_QUEST_TRACKER_MODULE.AddProgressBar
function WORLD_QUEST_TRACKER_MODULE:AddProgressBar(block, line, questID, finished)
local progressBar = bck_WORLD_QUEST_TRACKER_MODULE_AddProgressBar(self, block, line, questID, finished)
SetProgressBarStyle(progressBar)
return progressBar
end
BonusObjectiveTrackerProgressBar_UpdateReward = function(progressBar)
progressBar.Bar.Icon:Hide()
progressBar.Bar.IconBG:Hide()
progressBar.needsReward = nil
end
hooksecurefunc("BonusObjectiveTracker_OnTaskCompleted", function(questID, xp, money)
if KT.activeTasks[questID] then
KT.activeTasks[questID] = nil
end
end)
function BonusObjectiveTracker_ShowRewardsTooltip(block) -- R
if db.tooltipShow then
local questID
if block.id < 0 then
-- this is a scenario bonus objective
questID = C_Scenario.GetBonusStepRewardQuestID(-block.id)
if questID == 0 then
-- huh, no reward
return
end
else
questID = block.id
end
local questLink = GetQuestLink(questID)
if not questLink then
return
end
GameTooltip:SetOwner(block, "ANCHOR_NONE")
GameTooltip:ClearAllPoints()
if KTF.anchorLeft then
GameTooltip:SetPoint("TOPLEFT", block, "TOPRIGHT", 12, -1)
else
GameTooltip:SetPoint("TOPRIGHT", block, "TOPLEFT", -12, -1)
end
if not HaveQuestRewardData(questID) then
GameTooltip:AddLine(RETRIEVING_DATA, RED_FONT_COLOR.r, RED_FONT_COLOR.g, RED_FONT_COLOR.b);
else
GameTooltip:SetHyperlink(questLink)
if db.tooltipShowRewards then
KT.GameTooltip_AddQuestRewardsToTooltip(GameTooltip, questID, true)
end
if db.tooltipShowID then
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(" ", "ID: |cffffffff"..questID)
end
end
GameTooltip:Show()
block.module.tooltipBlock = block
end
end
local bck_SCENARIO_CONTENT_TRACKER_MODULE_Update = SCENARIO_CONTENT_TRACKER_MODULE.Update
function SCENARIO_CONTENT_TRACKER_MODULE:Update()
local _, _, numStages, _ = C_Scenario.GetInfo()
local BlocksFrame = SCENARIO_TRACKER_MODULE.BlocksFrame
self.topBlock = nil
self.lastBlock = nil
bck_SCENARIO_CONTENT_TRACKER_MODULE_Update(self)
if numStages > 0 and BlocksFrame.currentBlock then
self.lastBlock = ScenarioBlocksFrame
end
end
local bck_SCENARIO_TRACKER_MODULE_AddProgressBar = SCENARIO_TRACKER_MODULE.AddProgressBar
function SCENARIO_TRACKER_MODULE:AddProgressBar(block, line, criteriaIndex)
local progressBar = bck_SCENARIO_TRACKER_MODULE_AddProgressBar(self, block, line, criteriaIndex)
SetProgressBarStyle(progressBar)
return progressBar
end
hooksecurefunc("ObjectiveTracker_OnSlideBlockUpdate", function(block, elapsed)
local slideData = block.slideData
if block.slideTime >= slideData.duration + (slideData.endDelay or 0) then
ObjectiveTracker_Update() -- update after expand collapsed tracker
end
end)
hooksecurefunc(SCENARIO_CONTENT_TRACKER_MODULE, "AddSpells", function(self, objectiveBlock, spellInfo)
for i = 1, objectiveBlock.numSpells do
local block = objectiveBlock.spells[i]
block.id = spellInfo[i].spellID
block.SpellButton:Hide()
CreateFixedTag(block, 17, -1, "TOPLEFT")
local button = CreateFixedButton(block, true)
if not InCombatLockdown() then
button.spellID = spellInfo[i].spellID
button.Icon:SetTexture(spellInfo[i].spellIcon)
button:SetAttribute("spell", spellInfo[i].spellID)
end
end
for i = objectiveBlock.numSpells + 1, #objectiveBlock.spells do
KT:RemoveFixedButton(objectiveBlock.spells[i])
end
end)
ScenarioStageBlock:HookScript("OnEnter", function(self)
GameTooltip:ClearAllPoints()
if KTF.anchorLeft then
GameTooltip:SetPoint("TOPLEFT", self, "TOPRIGHT", 59, -1)
else
GameTooltip:SetPoint("TOPRIGHT", self, "TOPLEFT", -16, -1)
end
end)
hooksecurefunc(AUTO_QUEST_POPUP_TRACKER_MODULE, "EndLayout", function(self)
for i = 1, GetNumAutoQuestPopUps() do
local questID, popUpType = GetAutoQuestPopUp(i)
if not IsQuestBounty(questID) then
local questTitle = GetQuestLogTitle(GetQuestLogIndexByID(questID))
if questTitle and questTitle ~= "" then
local block = AUTO_QUEST_POPUP_TRACKER_MODULE:GetBlock(questID)
block.height = 68 -- fix
local blockContents = block.ScrollChild
blockContents.QuestName:SetFont(KT.font, 14, "")
blockContents.BottomText:SetPoint("BOTTOM", 0, 7)
end
end
end
end)
function ObjectiveTracker_Collapse()
_DBG("--------------------------------")
_DBG("COLLAPSE")
OTF.collapsed = true
dbChar.collapsed = OTF.collapsed
OTF.BlocksFrame:Hide()
KTF.MinimizeButton:GetNormalTexture():SetTexCoord(0, 0.5, 0, 0.25)
OTFHeader.Title:Show()
MSA_CloseDropDownMenus()
end
function ObjectiveTracker_Expand()
_DBG("--------------------------------")
_DBG("EXPAND")
OTF.collapsed = nil
dbChar.collapsed = OTF.collapsed
OTF.BlocksFrame:Show()
KTF.MinimizeButton:GetNormalTexture():SetTexCoord(0, 0.5, 0.25, 0.5)
OTFHeader.Title:Hide()
MSA_CloseDropDownMenus()
end
local bck_BonusObjectiveTracker_OnBlockAnimOutFinished = BonusObjectiveTracker_OnBlockAnimOutFinished
BonusObjectiveTracker_OnBlockAnimOutFinished = function(self)
local block = self:GetParent()
KT.activeTasks[block.id] = nil
bck_BonusObjectiveTracker_OnBlockAnimOutFinished(self)
end
hooksecurefunc("BonusObjectiveTracker_SetBlockState", function(block, state, force)
if state == "ENTERING" then
_DBG(" - "..state)
KT.activeTasks[block.id] = true
KT:ToggleEmptyTracker(true)
elseif state == "PRESENT" and not KT.activeTasks[block.id] then
_DBG(" - "..state)
KT.activeTasks[block.id] = true
if not IsWorldQuestWatched(block.id) then
KT:ToggleEmptyTracker(KT.initialized)
end
elseif state == "LEAVING" and KT.activeTasks[block.id] then
_DBG(" - "..state)
KT:RemoveFixedButton(block)
if dbChar.collapsed then
BonusObjectiveTracker_OnBlockAnimOutFinished(block.ScrollContents)
end
end
end)
local bck_ObjectiveTracker_ReorderModules = ObjectiveTracker_ReorderModules
ObjectiveTracker_ReorderModules = function()
local reorder = false
for i = 1, #OTF.MODULES do
if OTF.MODULES[i] ~= OTF.MODULES_UI_ORDER[i] then
reorder = true
break
end
end
if reorder then
bck_ObjectiveTracker_ReorderModules()
end
end
local bck_QuestPOI_GetButton = QuestPOI_GetButton
QuestPOI_GetButton = function(parent, questID, style, index)
local poiButton = bck_QuestPOI_GetButton(parent, questID, style, index)
poiButton.Glow.Show = function() end
return poiButton
end
hooksecurefunc(QuestUtil, "SetupWorldQuestButton", function(button, worldQuestType, rarity, isElite, tradeskillLineIndex, inProgress, selected, isCriteria, isSpellTarget, isEffectivelyTracked)
button.Glow:SetShown(false)
end)
local bck_UIErrorsFrame_OnEvent = UIErrorsFrame:GetScript("OnEvent")
UIErrorsFrame:SetScript("OnEvent", function(self, event, ...)
if db.messageQuest and event == "UI_INFO_MESSAGE" then
local text, _ = ...
for _, patt in ipairs(msgPatterns) do
if strfind(text, patt) then
KT:SetMessage(text, 1, 1, 0, nil, "Interface\\GossipFrame\\AvailableQuestIcon", -2, 0)
return
end
end
end
bck_UIErrorsFrame_OnEvent(self, event, ...)
end)
function QuestMapFrame_OpenToQuestDetails(questID) -- R
local mapID = GetQuestUiMapID(questID);
if ( mapID == 0 ) then mapID = nil; end
OpenQuestLog(mapID); -- fix Blizz bug
QuestMapFrame_ShowQuestDetails(questID);
end
-- Item handler functions
function QuestObjectiveItem_OnEnter(self) -- R
self.block.module:OnBlockHeaderEnter(self.block)
if KTF.anchorLeft then
GameTooltip:SetOwner(self, "ANCHOR_RIGHT", 3)
else
GameTooltip:SetOwner(self, "ANCHOR_LEFT", -3)
end
GameTooltip:SetQuestLogSpecialItem(self:GetID())
end
function QuestObjectiveItem_OnLeave(self)
self.block.module:OnBlockHeaderLeave(self.block)
GameTooltip:Hide()
end
function QuestObjectiveItem_OnUpdate(self, elapsed) -- R
local rangeTimer = self.rangeTimer
if rangeTimer then
rangeTimer = rangeTimer - elapsed
if rangeTimer <= 0 then
local link, item, charges, showItemWhenComplete = GetQuestLogSpecialItemInfo(self:GetID())
if charges and charges ~= self.charges then
ObjectiveTracker_Update(OBJECTIVE_TRACKER_UPDATE_MODULE_QUEST)
return
end
local hotkey = self.HotKey
local valid = IsQuestLogSpecialItemInRange(self:GetID())
if hotkey:GetText() == RANGE_INDICATOR then
if valid == 0 then
hotkey:Show()
hotkey:SetVertexColor(1.0, 0.1, 0.1)
elseif valid == 1 then
hotkey:Show()
hotkey:SetVertexColor(0.6, 0.6, 0.6)
else
hotkey:Hide()
end
else
if valid == 0 then
hotkey:SetVertexColor(1.0, 0.1, 0.1)
else
hotkey:SetVertexColor(0.6, 0.6, 0.6)
end
end
rangeTimer = TOOLTIP_UPDATE_TIME
end
self.rangeTimer = rangeTimer
end
if db.qiActiveButton and not InCombatLockdown() and self.block then
if KT.ActiveButton.timerID then
if KT.ActiveButton.timerID ~= self.block.id then
return
end
else
KT.ActiveButton.timerID = self.block.id
end
if KT.ActiveButton.timer > 50 then
KT.ActiveButton:Update()
else
--_DBG("... "..KT.ActiveButton.timer.." ... "..self.block.id)
KT.ActiveButton.timer = KT.ActiveButton.timer + TOOLTIP_UPDATE_TIME
end
end
end
-- DropDown
function ObjectiveTracker_ToggleDropDown(frame, handlerFunc) -- R
local dropDown = KT.DropDown;
if ( dropDown.activeFrame ~= frame ) then
MSA_CloseDropDownMenus();
end
dropDown.activeFrame = frame;
dropDown.initialize = handlerFunc;
MSA_ToggleDropDownMenu(1, nil, dropDown, "cursor", 3, -3, nil, nil, MSA_DROPDOWNMENU_SHOW_TIME);
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
end
function QUEST_TRACKER_MODULE:OnBlockHeaderClick(block, mouseButton) -- R
if ( ChatEdit_TryInsertQuestLinkForQuestID(block.id) ) then
return;
end
if ( mouseButton ~= "RightButton" ) then
MSA_CloseDropDownMenus();
if ( IsModifiedClick("QUESTWATCHTOGGLE") ) then
QuestObjectiveTracker_UntrackQuest(nil, block.id);
elseif IsModifiedClick(db.menuWowheadURLModifier) then
KT:Alert_WowheadURL("quest", block.id)
else
local questLogIndex = GetQuestLogIndexByID(block.id);
if ( IsQuestComplete(block.id) and GetQuestLogIsAutoComplete(questLogIndex) ) then
AutoQuestPopupTracker_RemovePopUp(block.id);
ShowQuestComplete(questLogIndex);
else
if db.questDefaultActionMap then
QuestMapFrame_OpenToQuestDetails(block.id);
else
QuestLogPopupDetailFrame_Show(questLogIndex);
end
end
end
return;
else
ObjectiveTracker_ToggleDropDown(block, QuestObjectiveTracker_OnOpenDropDown);
end
end
function QuestObjectiveTracker_OnOpenDropDown(self) -- R
local block = self.activeFrame;
local questLogIndex = GetQuestLogIndexByID(block.id);
local info = MSA_DropDownMenu_CreateInfo();
info.text = GetQuestLogTitle(questLogIndex);
info.isTitle = 1;
info.notCheckable = 1;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
info = MSA_DropDownMenu_CreateInfo();
info.notCheckable = 1;
info.text = OBJECTIVES_VIEW_IN_QUESTLOG;
info.func = QuestObjectiveTracker_OpenQuestDetails;
info.arg1 = block.id;
info.noClickSound = 1;
info.checked = false;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
info.text = OBJECTIVES_SHOW_QUEST_MAP;
info.func = QuestObjectiveTracker_OpenQuestMap;
info.arg1 = block.id;
info.checked = false;
info.noClickSound = 1;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
if ( GetQuestLogPushable(questLogIndex) and IsInGroup() ) then
info.text = SHARE_QUEST;
info.func = QuestObjectiveTracker_ShareQuest;
info.arg1 = block.id;
info.checked = false;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
end
info.text = OBJECTIVES_STOP_TRACKING;
info.func = QuestObjectiveTracker_UntrackQuest;
info.arg1 = block.id;
info.checked = false;
info.disabled = (db.filterAuto[1]);
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
info.disabled = false;
if db.menuWowheadURL then
info.text = "|cff33ff99Wowhead|r URL";
info.func = KT.Alert_WowheadURL;
info.arg1 = "quest";
info.arg2 = block.id;
info.checked = false;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
end
end
function ACHIEVEMENT_TRACKER_MODULE:OnBlockHeaderClick(block, mouseButton) -- R
if ( IsModifiedClick("CHATLINK") and ChatEdit_GetActiveWindow() ) then
local achievementLink = GetAchievementLink(block.id);
if ( achievementLink ) then
ChatEdit_InsertLink(achievementLink);
end
elseif ( mouseButton ~= "RightButton" ) then
MSA_CloseDropDownMenus();
if ( not AchievementFrame ) then
AchievementFrame_LoadUI();
end
if ( IsModifiedClick("QUESTWATCHTOGGLE") ) then
AchievementObjectiveTracker_UntrackAchievement(_, block.id);
elseif IsModifiedClick(db.menuWowheadURLModifier) then
KT:Alert_WowheadURL("achievement", block.id)
elseif ( not AchievementFrame:IsShown() ) then
AchievementFrame_ToggleAchievementFrame();
AchievementFrame_SelectAchievement(block.id);
else
if ( AchievementFrameAchievements.selection ~= block.id ) then
AchievementFrame_SelectAchievement(block.id);
else
AchievementFrame_ToggleAchievementFrame();
end
end
else
ObjectiveTracker_ToggleDropDown(block, AchievementObjectiveTracker_OnOpenDropDown);
end
end
function AchievementObjectiveTracker_OnOpenDropDown(self) -- R
local block = self.activeFrame;
local _, achievementName, _, completed, _, _, _, _, _, icon = GetAchievementInfo(block.id);
local info = MSA_DropDownMenu_CreateInfo();
info.text = achievementName;
info.isTitle = 1;
info.notCheckable = 1;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
info = MSA_DropDownMenu_CreateInfo();
info.notCheckable = 1;
info.text = OBJECTIVES_VIEW_ACHIEVEMENT;
info.func = function (button, ...) OpenAchievementFrameToAchievement(...); end;
info.arg1 = block.id;
info.checked = false;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
info.text = OBJECTIVES_STOP_TRACKING;
info.func = AchievementObjectiveTracker_UntrackAchievement;
info.arg1 = block.id;
info.checked = false;
info.disabled = (db.filterAuto[2]);
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
info.disabled = false;
if db.menuWowheadURL then
info.text = "|cff33ff99Wowhead|r URL";
info.func = KT.Alert_WowheadURL;
info.arg1 = "achievement";
info.arg2 = block.id;
info.checked = false;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
end
end
function BonusObjectiveTracker_OnBlockClick(self, button) -- R
local questID = self.TrackedQuest and self.TrackedQuest.questID or self.id;
local isThreatQuest = C_QuestLog.IsThreatQuest(questID);
if button == "LeftButton" then
if ( not ChatEdit_TryInsertQuestLinkForQuestID(questID) ) then
MSA_CloseDropDownMenus();
if IsShiftKeyDown() then
if IsWorldQuestWatched(questID) and not isThreatQuest then
BonusObjectiveTracker_UntrackWorldQuest(questID);
end
elseif IsModifiedClick(db.menuWowheadURLModifier) then
KT:Alert_WowheadURL("quest", questID)
else
local mapID = C_TaskQuest.GetQuestZoneID(questID);
if mapID then
QuestMapFrame_CloseQuestDetails();
OpenQuestLog(mapID);
WorldMapPing_StartPingQuest(questID);
end
end
end
elseif button == "RightButton" then
ObjectiveTracker_ToggleDropDown(self, BonusObjectiveTracker_OnOpenDropDown);
end
end
function BonusObjectiveTracker_OnOpenDropDown(self) -- R
local block = self.activeFrame;
local questID = block.TrackedQuest and block.TrackedQuest.questID or block.id;
local addStopTracking = IsWorldQuestWatched(questID);
-- Ensure at least one option will appear before showing the dropdown.
if not addStopTracking and not db.menuWowheadURL then
return;
end
-- Add title
local info = MSA_DropDownMenu_CreateInfo();
info.text = C_TaskQuest.GetQuestInfoByQuestID(questID);
info.isTitle = 1;
info.notCheckable = 1;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
-- Add "stop tracking"
if IsWorldQuestWatched(questID) then
info = MSA_DropDownMenu_CreateInfo();
info.notCheckable = true;
info.text = OBJECTIVES_STOP_TRACKING;
info.func = function()
BonusObjectiveTracker_UntrackWorldQuest(questID);
end
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
end
if db.menuWowheadURL then
info = MSA_DropDownMenu_CreateInfo();
info.notCheckable = true;
info.text = "|cff33ff99Wowhead|r URL";
info.func = KT.Alert_WowheadURL;
info.arg1 = "quest";
info.arg2 = questID;
info.checked = false;
MSA_DropDownMenu_AddButton(info, MSA_DROPDOWN_MENU_LEVEL);
end
end
-- Headers
hooksecurefunc(QUEST_TRACKER_MODULE.Header, "UpdateHeader", function(self)
self.module.title = self.Text:GetText()
KT:SetQuestsHeaderText()
end)
end
--------------
-- External --
--------------
function KT_WorldQuestPOIButton_OnClick(self)
local questID = self.questID
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON)
SetSuperTrackedQuestID(questID)
WorldMapPing_StartPingQuest(questID)
end
function KT:SetSize()
local height = 33
local mod = 0
if OTF.BlocksFrame.contentsHeight then
OTF.BlocksFrame.contentsHeight = round(OTF.BlocksFrame.contentsHeight)
else
return
end
_DBG(" - height = "..OTF.BlocksFrame.contentsHeight)
if not dbChar.collapsed and not self:IsTrackerEmpty() then
-- width
KTF:SetWidth(trackerWidth)
-- height
if BONUS_OBJECTIVE_TRACKER_MODULE.firstBlock then
mod = mod + BONUS_OBJECTIVE_TRACKER_MODULE.blockPadding
end
height = OTF.BlocksFrame.contentsHeight + mod + 10 + paddingBottom
_DBG(" - "..OTF.BlocksFrame.contentsHeight.." + "..mod.." + 10 + "..paddingBottom.." = "..height, true)
OTF.height = height
if height > db.maxHeight then
_DBG("MOVE ... "..KTF.Scroll.value.." > "..OTF.height.." - "..db.maxHeight)
if KTF.Scroll.value > OTF.height-db.maxHeight then
KTF.Scroll.value = OTF.height - db.maxHeight
end
KTF.Scroll:SetVerticalScroll(KTF.Scroll.value)
if db.frameScrollbar then
SetScrollbarPosition()
KTF.Bar:Show()
end
height = db.maxHeight
elseif height <= db.maxHeight then
if KTF.Scroll.value > 0 then
KTF.Scroll.value = 0
KTF.Scroll:SetVerticalScroll(0)
end
if db.frameScrollbar then
KTF.Bar:Hide()
end
end
if height ~= KTF.height then
KTF:SetHeight(height)
KTF.height = height
end
self:MoveButtons()
else
-- width
if db.hdrCollapsedTxt == 1 then
local width = 35
if KTF.FilterButton then
width = width + 20
end
if db.hdrOtherButtons then
width = width + (2 * 20)
end
KTF:SetWidth(width)
else
KTF:SetWidth(trackerWidth)
end
-- height
OTF.height = height - 10
OTF:SetHeight(OTF.height)
if OTF.BlocksFrame.contentsHeight == 0 then
KTF.Scroll.value = 0
end
KTF.Scroll:SetVerticalScroll(0)
if db.frameScrollbar then
KTF.Bar:Hide()
end
if height ~= KTF.height then
KTF:SetHeight(height)
KTF.height = height
end
end
end
function KT:MoveTracker()
KTF:ClearAllPoints()
KTF:SetPoint(db.anchorPoint, UIParent, db.anchorPoint, db.xOffset, db.yOffset)
KTF.directionUp = (db.anchorPoint == "BOTTOMLEFT" or db.anchorPoint == "BOTTOMRIGHT")
KTF.anchorLeft = (db.anchorPoint == "TOPLEFT" or db.anchorPoint == "BOTTOMLEFT")
local options = self.options.args.general.args.sec1.args
if KTF.anchorLeft then
options.xOffset.min = 0
options.xOffset.max = self.screenWidth - trackerWidth
else
options.xOffset.min = -(self.screenWidth - trackerWidth)
options.xOffset.max = 0
end
if KTF.directionUp then
options.yOffset.min = 0
options.yOffset.max = self.screenHeight - options.maxHeight.min
else
options.yOffset.min = -(self.screenHeight - options.maxHeight.min)
options.yOffset.max = 0
end
options.maxHeight.max = self.screenHeight - abs(db.yOffset)
db.maxHeight = (abs(db.yOffset)+db.maxHeight > self.screenHeight) and options.maxHeight.max or db.maxHeight
self:MoveButtons()
end
function KT:SetBackground()
local backdrop = {
bgFile = LSM:Fetch("background", db.bgr),
edgeFile = LSM:Fetch("border", db.border),
edgeSize = db.borderThickness,
insets = { left=db.bgrInset, right=db.bgrInset, top=db.bgrInset, bottom=db.bgrInset }
}
self.borderColor = db.classBorder and self.classColor or db.borderColor
KTF:SetBackdrop(backdrop)
KTF:SetBackdropColor(db.bgrColor.r, db.bgrColor.g, db.bgrColor.b, db.bgrColor.a)
KTF:SetBackdropBorderColor(self.borderColor.r, self.borderColor.g, self.borderColor.b, db.borderAlpha)
SetHeaders("background")
self.hdrBtnColor = db.hdrBtnColorShare and self.borderColor or db.hdrBtnColor
KTF.MinimizeButton:GetNormalTexture():SetVertexColor(self.hdrBtnColor.r, self.hdrBtnColor.g, self.hdrBtnColor.b)
if self.Filters:IsEnabled() then
if db.filterAuto[1] or db.filterAuto[2] or db.filterAuto[3] then
KTF.FilterButton:GetNormalTexture():SetVertexColor(0, 1, 0)
else
KTF.FilterButton:GetNormalTexture():SetVertexColor(self.hdrBtnColor.r, self.hdrBtnColor.g, self.hdrBtnColor.b)
end
end
if db.hdrOtherButtons then
KTF.QuestLogButton:GetNormalTexture():SetVertexColor(self.hdrBtnColor.r, self.hdrBtnColor.g, self.hdrBtnColor.b)
KTF.AchievementsButton:GetNormalTexture():SetVertexColor(self.hdrBtnColor.r, self.hdrBtnColor.g, self.hdrBtnColor.b)
end
if db.qiBgrBorder then
KTF.Buttons:SetBackdrop(backdrop)
KTF.Buttons:SetBackdropColor(db.bgrColor.r, db.bgrColor.g, db.bgrColor.b, db.bgrColor.a)
KTF.Buttons:SetBackdropBorderColor(self.borderColor.r, self.borderColor.g, self.borderColor.b, db.borderAlpha)
else
KTF.Buttons:SetBackdrop(nil)
end
KTF.Bar.texture:SetColorTexture(self.borderColor.r, self.borderColor.g, self.borderColor.b, db.borderAlpha)
if db.bgr == "None" and db.border == "None" then
KTF.Scroll:SetHitRectInsets(-150, 0, 0, 0.1)
else
KTF.Scroll:SetHitRectInsets(0.1, 0, 0, 0.1)
end
OTFHeader.Title:SetJustifyH(db.bgr == "None" and "RIGHT" or "LEFT")
end
function KT:SetText()
self.font = LSM:Fetch("font", db.font)
-- Headers
SetHeaders("text")
-- Others
ScenarioStageBlock.Stage:SetFont(self.font, db.fontSize+5, db.fontFlag)
end
function KT:SaveHeader(module)
module.Header.Text:SetWidth(165)
module.Header.LineGlow:Hide()
module.Header.SoftGlow:Hide()
module.Header.StarBurst:Hide()
module.Header.LineSheen:Hide()
if module == BONUS_OBJECTIVE_TRACKER_MODULE or module == WORLD_QUEST_TRACKER_MODULE then
module.Header.TopShadow:Hide()
module.Header.BottomShadow:Hide()
end
tinsert(KT.headers, module.Header)
module.title = module.Header.Text:GetText()
end
function KT:SetHeaderText(module, append)
local text = module.title
if append then
text = format("%s (%s)", text, append)
end
module.Header.Text:SetText(text)
end
function KT:SetQuestsHeaderText(reset)
if db.hdrQuestsTitleAppend then
local _, numQuests = GetNumQuestLogEntries()
self:SetHeaderText(QUEST_TRACKER_MODULE, numQuests.."/"..MAX_QUESTS)
elseif reset then
self:SetHeaderText(QUEST_TRACKER_MODULE)
end
end
function KT:SetAchievsHeaderText(reset)
if db.hdrAchievsTitleAppend then
self:SetHeaderText(ACHIEVEMENT_TRACKER_MODULE, GetTotalAchievementPoints())
elseif reset then
self:SetHeaderText(ACHIEVEMENT_TRACKER_MODULE)
end
end
function KT:ToggleOtherButtons()
if not db.hdrOtherButtons then
if KTF.QuestLogButton then
KTF.QuestLogButton:Hide()
KTF.AchievementsButton:Hide()
OTFHeader.Title:SetWidth(OTFHeader.Title:GetWidth() + 40)
end
return
end
OTFHeader.Title:SetWidth(OTFHeader.Title:GetWidth() - 40)
if KTF.QuestLogButton then
KTF.QuestLogButton:Show()
KTF.AchievementsButton:Show()
else
local button
-- Achievements button
button = CreateFrame("Button", addonName.."AchievementsButton", KTF)
button:SetSize(16, 16)
button:SetPoint("TOPRIGHT", (KTF.FilterButton or KTF.MinimizeButton), "TOPLEFT", -4, 0)
button:SetFrameLevel(KTF:GetFrameLevel() + 10)
button:SetNormalTexture(mediaPath.."UI-KT-HeaderButtons")
button:GetNormalTexture():SetTexCoord(0.5, 1, 0.25, 0.5)
button:RegisterForClicks("AnyDown")
button:SetScript("OnClick", function(self, btn)
ToggleAchievementFrame()
end)
button:SetScript("OnEnter", function(self)
self:GetNormalTexture():SetVertexColor(1, 1, 1)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip:AddLine(AchievementMicroButton.tooltipText, 1, 1, 1)
GameTooltip:Show()
end)
button:SetScript("OnLeave", function(self)
self:GetNormalTexture():SetVertexColor(KT.hdrBtnColor.r, KT.hdrBtnColor.g, KT.hdrBtnColor.b)
GameTooltip:Hide()
end)
KTF.AchievementsButton = button
-- Quest Log button
button = CreateFrame("Button", addonName.."QuestLogButton", KTF)
button:SetSize(16, 16)
button:SetPoint("TOPRIGHT", KTF.AchievementsButton, "TOPLEFT", -4, 0)
button:SetFrameLevel(KTF:GetFrameLevel() + 10)
button:SetNormalTexture(mediaPath.."UI-KT-HeaderButtons")
button:GetNormalTexture():SetTexCoord(0.5, 1, 0, 0.25)
button:RegisterForClicks("AnyDown")
button:SetScript("OnClick", function(self, btn)
ToggleQuestLog()
end)
button:SetScript("OnEnter", function(self)
self:GetNormalTexture():SetVertexColor(1, 1, 1)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip:AddLine(QuestLogMicroButton.tooltipText, 1, 1, 1)
GameTooltip:Show()
end)
button:SetScript("OnLeave", function(self)
self:GetNormalTexture():SetVertexColor(KT.hdrBtnColor.r, KT.hdrBtnColor.g, KT.hdrBtnColor.b)
GameTooltip:Hide()
end)
KTF.QuestLogButton = button
end
end
function KT:MoveButtons()
if not InCombatLockdown() then
local point, xOfs, yOfs
if KTF.anchorLeft then
point = "LEFT"
xOfs = KTF:GetRight() and KTF:GetRight() + db.qiXOffset
else
point = "RIGHT"
xOfs = KTF:GetLeft() and KTF:GetLeft() - db.qiXOffset
end
local hMod = 2 * (4 - db.bgrInset)
local yMod = 0
if not db.qiBgrBorder then
hMod = hMod + 4
yMod = 2 + (4 - db.bgrInset)
end
if KTF.directionUp and (db.maxHeight+hMod) < KTF.Buttons:GetHeight() then
point = "BOTTOM"..point
yOfs = KTF:GetBottom() and KTF:GetBottom() - yMod
else
point = "TOP"..point
yOfs = KTF:GetTop() and KTF:GetTop() + yMod
end
if xOfs and yOfs then
KTF.Buttons:ClearAllPoints()
KTF.Buttons:SetPoint(point, UIParent, "BOTTOMLEFT", xOfs, yOfs)
end
end
end
function KT:RemoveFixedButton(block)
if block then
local tag = block.fixedTag
if tag then
tinsert(freeTags, tag)
tag.text:SetText("")
tag:Hide()
block.fixedTag = nil
end
local questID = block.id
local button = self:GetFixedButton(questID)
if button then
button:SetAlpha(0)
if InCombatLockdown() then
_DBG(" - STOP Remove button")
combatLockdown = true
else
_DBG(" - REMOVE button "..questID)
tinsert(freeButtons, button)
self.fixedButtons[questID] = nil
button:Hide()
KTF.Buttons.reanchor = true
end
if db.qiActiveButton then
KTF.ActiveButton.text:SetText("")
end
end
if self.ActiveButton.timerID == questID then
self.ActiveButton.timerID = nil
end
else
for questID, button in pairs(self.fixedButtons) do
_DBG(" - REMOVE button "..questID)
tinsert(freeButtons, button)
self.fixedButtons[questID] = nil
button:Hide()
end
KTF.Buttons.reanchor = true
end
end
function KT:GetFixedButton(questID)
if self.fixedButtons[questID] then
return self.fixedButtons[questID]
else
return nil
end
end
function KT:CreateQuestTag(level, questTag, frequency, suggestedGroup)
local tag = ""
if level == -1 then
level = "*"
else
level = tostring(level)
end
if questTag == Enum.QuestTag.Group then
tag = "g"
if suggestedGroup > 0 then
tag = tag..suggestedGroup
end
elseif questTag == Enum.QuestTag.Pvp then
tag = "pvp"
elseif questTag == Enum.QuestTag.Dungeon then
tag = "d"
elseif questTag == Enum.QuestTag.Heroic then
tag = "hc"
elseif questTag == Enum.QuestTag.Raid then
tag = "r"
elseif questTag == Enum.QuestTag.Raid10 then
tag = "r10"
elseif questTag == Enum.QuestTag.Raid25 then
tag = "r25"
elseif questTag == Enum.QuestTag.Scenario then
tag = "s"
elseif questTag == Enum.QuestTag.Account then
tag = "a"
elseif questTag == Enum.QuestTag.Legendary then
tag = "leg"
end
if frequency == 2 then
tag = tag.."!" -- daily quest
elseif frequency == 3 then
tag = tag.."!!" -- weekly quest
end
if tag ~= "" then
tag = ("|cff00b3ff%s|r"):format(tag)
end
tag = ("[%s%s] "):format(level, tag)
return tag
end
function KT:IsTrackerEmpty(noaddon)
local result = (GetNumQuestWatches() == 0 and
GetNumAutoQuestPopUps() == 0 and
GetNumTrackedAchievements() == 0 and
self.IsTableEmpty(self.activeTasks) and
GetNumWorldQuestWatches() == 0 and
not self.inScenario)
if not noaddon then
result = (result and not self.AddonPetTracker:IsShown())
end
return result
end
function KT:ToggleEmptyTracker(added)
local alpha, mouse = 1, true
if self:IsTrackerEmpty() then
if not dbChar.collapsed then
ObjectiveTracker_MinimizeButton_OnClick()
end
KTF.MinimizeButton:GetNormalTexture():SetTexCoord(0, 0.5, 0.5, 0.75)
if db.hideEmptyTracker then
alpha = 0
mouse = false
end
else
if dbChar.collapsed then
if added then
ObjectiveTracker_MinimizeButton_OnClick()
else
KTF.MinimizeButton:GetNormalTexture():SetTexCoord(0, 0.5, 0, 0.25)
end
else
KTF.MinimizeButton:GetNormalTexture():SetTexCoord(0, 0.5, 0.25, 0.5)
end
end
KTF:SetAlpha(alpha)
KTF.MinimizeButton:EnableMouse(mouse)
if self.Filters:IsEnabled() then
KTF.FilterButton:EnableMouse(mouse)
end
if db.hdrOtherButtons then
KTF.QuestLogButton:EnableMouse(mouse)
KTF.AchievementsButton:EnableMouse(mouse)
end
end
function KT:SetMessage(text, r, g, b, pattern, icon, x, y)
if pattern then
text = format(pattern, text.." ...")
end
if icon then
x = x or 0
y = y or 0
if db.sink20OutputSink == "Blizzard" then
x = floor(x * 3 * COMBAT_TEXT_X_SCALE)
y = y - 8
end
text = format("|T%s:0:0:%d:%d|t%s", icon, x, y, text)
end
self:Pour(text, r, g, b)
end
function KT:PlaySound(key)
PlaySoundFile(LSM:Fetch("sound", key))
end
function KT:UpdateHotkey()
local key = GetBindingKey("EXTRAACTIONBUTTON1")
if db.keyBindMinimize == key then
SetOverrideBinding(KTF, false, db.keyBindMinimize, nil)
db.keyBindMinimize = ""
end
end
function KT:MergeTables(source, target)
if type(target) ~= "table" then target = {} end
for k, v in pairs(source) do
if type(v) == "table" then
target[k] = self:MergeTables(v, target[k])
elseif target[k] == nil then
target[k] = v
end
end
return target
end
-- Load ----------------------------------------------------------------------------------------------------------------
function KT:OnInitialize()
_DBG("|cffffff00Init|r - "..self:GetName(), true)
SLASH_KALIELSTRACKER1, SLASH_KALIELSTRACKER2 = "/kt", "/kalielstracker"
SlashCmdList["KALIELSTRACKER"] = SlashHandler
SetMsgPatterns()
-- Get character data
self.playerName = UnitName("player")
self.playerFaction = UnitFactionGroup("player")
self.playerLevel = UnitLevel("player")
local _, class = UnitClass("player")
self.classColor = RAID_CLASS_COLORS[class]
self.headers = {}
self.borderColor = {}
self.hdrBtnColor = {}
self.fixedButtons = {}
self.activeTasks = {}
self.inWorld = false
self.inInstance = IsInInstance()
self.inScenario = C_Scenario.IsInScenario()
self.stopUpdate = true
self.questStateStopUpdate = false
self.wqInitialized = false
self.initialized = false
-- Setup Options
self:SetupOptions()
db = self.db.profile
dbChar = self.db.char
KT:Alert_ResetIncompatibleProfiles("3.1.8")
-- Blizzard frame resets
OTF.IsUserPlaced = function() return true end
OTF.KTSetParent = OTF.SetParent
OTF.SetParent = function() end
OTF.SetFrameStrata = function() end
OTF.SetFrameLevel = function() end
OTF:SetClampedToScreen(false)
OTF.SetClampedToScreen = function() end
OTF:EnableMouse(false)
OTF.EnableMouse = function() end
OTF:SetMovable(false)
OTF.SetMovable = function() end
OTF:ClearAllPoints()
OTF.ClearAllPoints = function() end
OTF.SetAllPoints = function() end
OTF.KTSetPoint = OTF.SetPoint
OTF.SetPoint = function() end
OTF:Show()
OTF.Show = function() end
OTF.Hide = function() end
OTF.SetShown = function() end
end
function KT:OnEnable()
_DBG("|cff00ff00Enable|r - "..self:GetName(), true)
SetFrames()
SetHooks()
self.QuestLog:Enable()
self.Filters:Enable()
if self.AddonPetTracker.isLoaded then self.AddonPetTracker:Enable() end
if self.AddonTomTom.isLoaded then self.AddonTomTom:Enable() end
self.AddonOthers:Enable()
if db.qiActiveButton then self.ActiveButton:Enable() end
self.Help:Enable()
if self.db.global.version ~= self.version then
self.db.global.version = self.version
end
self.screenWidth = round(GetScreenWidth())
self.screenHeight = round(GetScreenHeight())
end
|
two_in_a_row = {
name = "Joe",
greeting = "Welcome",
}
|
local AceLocale = LibStub("AceLocale-3.0")
function MultiBarsConfig_MixinConfigFunctions(MultiBars)
function MultiBars:GetGroupAlignment(group)
if MultiBarsOptions and MultiBarsOptions.groups and MultiBarsOptions.groups[group].alignment then
return MultiBarsOptions.groups[group].alignment
end
return "left"
end
function MultiBars:SetGroupAlignment(group, alignment)
if MultiBarsOptions.groups[group] and (alignment == "left" or alignment == "right" or alignment == "top" or alignment == "bottom" or alignment == "unlocked" or alignment == "unlockedv") then
MultiBarsOptions.groups[group].alignment = alignment
end
end
function MultiBars:GetBarGroup(bar)
if MultiBarsOptions and MultiBarsOptions.groups then
local i, group
for i, group in ipairs(MultiBarsOptions.groups) do
if group.bars then
local _, v
for _, v in ipairs(group.bars) do
if v == bar then
return i
end
end
end
end
end
return 0
end
function MultiBars:SetBarGroup(barName, groupNumber)
local i, group
for i, group in ipairs(MultiBarsOptions.groups) do
if i == groupNumber then
-- for the matching group: add the bar if it's missing
if not tContains(group.bars, barName) then
tinsert(group.bars, barName)
end
else
-- for the rest of the groups: remove the bar if it's present
local index
local n, bn
-- find the index of the bar within the group
for i, bn in ipairs(group.bars) do
if bn == barName then
index = i
end
end
-- remove the bar, if the index was found
if index then
tremove(group.bars, index)
end
end
end
end
function MultiBars:AddBlacklistItem(itemid, global)
local options = MultiBarsOptions
if global then
options = MultiBarsGlobalOptions
end
if itemid then
options.blacklist[itemid] = true
end
end
function MultiBars:IsBlacklistItem(itemid)
if itemid then
return MultiBarsOptions.blacklist[itemid] or MultiBarsGlobalOptions.blacklist[itemid]
end
return false
end
function MultiBars:RemoveBlacklistItem(itemid, global)
if itemid then
if global == true then
MultiBarsGlobalOptions.blacklist[itemid] = nil
elseif global == false then
MultiBarsOptions.blacklist[itemid] = nil
else
MultiBarsGlobalOptions.blacklist[itemid] = nil
MultiBarsOptions.blacklist[itemid] = nil
end
end
end
function MultiBars:GetBlacklistString(global)
local options = MultiBarsOptions
if global then
options = MultiBarsGlobalOptions
end
local blacklistString = ""
local count = 0
local i, v
for i, v in pairs(options.blacklist) do
if v then
if count > 0 then
blacklistString = blacklistString .. "," .. i
else
blacklistString = tostring(i)
end
count = count + 1
end
end
return blacklistString
end
function MultiBars:SetBlacklistString(blacklistString, global)
local options = MultiBarsOptions
if global then
options = MultiBarsGlobalOptions
end
wipe(options.blacklist)
if blacklistString then
local k, v
for k, v in string.gmatch(blacklistString, "(%d+)(%D*)") do
local itemid = tonumber(k)
if itemid then
options.blacklist[itemid] = true
end
end
end
end
function MultiBars:AddFeedPetBlacklistItem(itemid)
if itemid then
MultiBarsGlobalOptions.feedPetBlacklist[itemid] = true
end
end
function MultiBars:IsFeedPetBlacklistItem(itemid)
if itemid then
return MultiBarsGlobalOptions.feedPetBlacklist[itemid]
end
return false
end
function MultiBars:RemoveFeedPetBlacklistItem(itemid)
if itemid then
MultiBarsGlobalOptions.feedPetBlacklist[itemid] = nil
end
end
-- does not return nil
function MultiBars:IsMacroGeneral(buttonNumber)
return MultiBarsOptions.macros[buttonNumber].general or false
end
function MultiBars:SetMacroGeneral(buttonNumber, general)
if general then
MultiBarsOptions.macros[buttonNumber].general = true
else
MultiBarsOptions.macros[buttonNumber].general = nil
end
end
-- Returns a macro name or nil
function MultiBars:GetMacroName(buttonNumber)
return MultiBarsOptions.macros[buttonNumber].name
end
function MultiBars:SetMacroName(buttonNumber, macroName)
local name = macroName
if not macroName or strlen(macroName) == 0 then
name = nil
end
MultiBarsOptions.macros[buttonNumber].name = name
end
end
local function MultiBarsConfig_CreateBaseOptions(MultiBars)
local options = {
name = "MultiBars",
handler = MultiBars,
type = 'group',
args = {
text = {
type = 'description',
order = 2,
name = GetAddOnMetadata("MultiBars", "Notes") or "",
},
version = {
type = 'description',
order = 3,
name = GetAddOnMetadata("MultiBars", "Version") or "",
},
dropdownSound = {
type = 'toggle',
order = 4,
name = "Dropdown Sounds",
desc = "Enables/Disables click sounds on the dropdown menus",
width = "full",
get = function(info) return MultiBarsOptions.dropdownSound end,
set = function(info, value)
MultiBarsOptions.dropdownSound = value
end,
},
noManagedContainerOffsetMod = {
type = 'toggle',
order = 5,
name = "Auto-adjust Blizzard Bag & Quest Tracker positions",
desc = "Adjusts default Blizzard UI elements so the MultiBars don't cover them",
width = "full",
get = function(info) return MultiBarsOptions.adjustContainerOffset end,
set = function(info, value)
MultiBarsOptions.adjustContainerOffset = value
if value then
MultiBars:LayoutBars()
else
MultiBars:ResetBlizzardContainerOffset()
end
UIParent_ManageFramePositions()
end,
},
reset = {
type = 'execute',
order = 25,
name = "Reset Settings",
func = function(info)
MultiBars:ShowResetSettingsConfirmation()
end,
}
},
}
local playerClass = UnitClassBase("player")
if playerClass == "HUNTER" or playerClass == "WARLOCK" then
options.args["adjustGroupsForPetBar"] = {
type = 'toggle',
order = 6,
name = "Left-aligned groups leave room for the pet action bar",
desc = "Positions left-aligned groups higher so that they don't cover up the pet action bar",
width = "full",
get = function(info) return MultiBarsOptions.adjustGroupsForPetBar end,
set = function(info, value)
MultiBarsOptions.adjustGroupsForPetBar = value
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end,
}
end
return options
end
local function MultiBarsConfig_CreateSingleBarOptions(MultiBars, options, barName, n)
local L = AceLocale:GetLocale("MultiBars", true)
options.args[barName] = {
type = 'group',
order = n,
name = L[barName],
inline = true,
args = {
color = {
type = 'color',
order = 1,
name = "Border Color",
desc = "",
hasAlpha = false,
get = function(info) return unpack(MultiBarsOptions.bars[barName].color) end,
set = function(info, r, g, b, a)
MultiBarsOptions.bars[barName].color = { r, g, b, a }
MultiBars:UpdateVisuals()
end,
},
reversed = {
type = 'toggle',
order = 2,
name = "Reverse Button Order",
desc = "",
get = function(info) return MultiBarsOptions.bars[barName].reversed end,
set = function(info, value)
MultiBarsOptions.bars[barName].reversed = value
MultiBars:UpdateActions()
end,
},
maxButtons = {
type = 'range',
order = 3,
name = "Max Buttons",
desc = "Limits the number of buttons that will be on the bar",
min = 1,
max = 12,
step = 1,
get = function(info) return MultiBarsOptions.bars[barName].maxButtons end,
set = function(info, value)
MultiBarsOptions.bars[barName].maxButtons = value
MultiBars:UpdateActions()
end,
},
}
}
local nextOrder = 4
if barName == "MultiBarFood" then
options.args[barName].args.includeBuffFood = {
type = 'toggle',
order = nextOrder,
name = "Include Buff Food",
desc = "Whether to also include buttons for buff food items on this bar",
get = function(info) return MultiBarsOptions.bars[barName].includeBuffFood end,
set = function(info, value)
MultiBarsOptions.bars[barName].includeBuffFood = value
MultiBars:UpdateActions()
end,
}
nextOrder = nextOrder + 1
end
if MULTIBARS_CLASS_BARS[barName] and MULTIBARS_CLASS_BARS[barName].hasAlternates then
options.args[barName].args.useAlternates = {
type = 'toggle',
order = nextOrder,
name = "Default to Alternates",
desc = "Un-modified clicks will be for the alternate version of the spell (i.e. the group buff instead of single-target version of the spell)",
get = function(info) return MultiBarsOptions.bars[barName].useAlternates end,
set = function(info, value)
MultiBarsOptions.bars[barName].useAlternates = value
MultiBars:UpdateActions()
end,
}
nextOrder = nextOrder + 1
options.args[barName].args.useModSwitch = {
type = 'toggle',
order = nextOrder,
name = "Use alt-key",
desc = 'Alt-clicking will cast the other version of the spell (either group or single-target depending on the "Default to Alternates" option)',
get = function(info) return MultiBarsOptions.bars[barName].useModSwitch end,
set = function(info, value)
MultiBarsOptions.bars[barName].useModSwitch = value
MultiBars:UpdateActions()
end,
}
nextOrder = nextOrder + 1
end
if _G[barName].actionType == "spell" then
options.args[barName].args.unhideAll = {
type = 'execute',
order = nextOrder,
name = "Un-Hide All Buttons",
desc = "Un-hides all previously-hidden buttons for this bar",
func = function(self)
wipe(MultiBarsOptions.bars[barName].hidden)
MultiBars:UpdateActions()
MultiBars:LayoutBars()
end,
}
nextOrder = nextOrder + 1
end
end
local function MultiBarsConfig_CreateBarOptions(MultiBars)
local options = {
name = "MultiBars Bar Options",
handler = MultiBars,
type = 'group',
args = {
},
}
local _, barName
local n = 0
local names = {}
for barName, _ in pairs(MultiBarsOptions.bars) do
n = n + 1
names[n] = barName
end
sort(names)
for n = 1, #names do
barName = names[n]
local barInfo = MULTIBARS_CLASS_BARS[barName]
if not barInfo or not barInfo.class or barInfo.class == UnitClassBase("player") then
MultiBarsConfig_CreateSingleBarOptions(MultiBars, options, barName, n)
end
end
return options
end
local function MultiBarsConfig_CreateLayoutGroupOptions(MultiBars, options, n)
local groupn = "group" .. n
local L = AceLocale:GetLocale("MultiBars", true)
options.args[groupn] = {
type = 'group',
order = n,
name = "Layout Group " .. n,
inline = true,
args = {
bars = {
type = 'multiselect',
order = 1,
name = "Included Bars",
desc = "",
values = {
MultiBarBuff = L.MultiBarBuff,
MultiBarConsumable = L.MultiBarConsumable,
MultiBarFood = L.MultiBarFood,
MultiBarMacro = L.MultiBarMacro,
MultiBarProfession = L.MultiBarProfession,
},
get = function(info, key) return MultiBars:GetBarGroup(key) == n end,
set = function(info, key, value)
if value then
MultiBars:SetBarGroup(key, n)
else
MultiBars:SetBarGroup(key, 0)
end
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end,
},
alignment = {
type = 'select',
order = 2,
name = "Alignment",
desc = "",
values = {
left = "Left",
right = "Right",
top = "Top",
bottom = "Bottom",
unlocked = "Unlocked (horizontal)",
unlockedv = "Unlocked (vertical)",
},
get = function(info) return MultiBars:GetGroupAlignment(n) end,
set = function(info, value)
MultiBars:SetGroupAlignment(n, value)
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end,
style = "radio",
},
scale = {
type = 'range',
order = 3,
name = "Scale",
desc = "Scales the size of the bars",
softMin = 0.1,
softMax = 2,
bigStep = 0.1,
get = function(info) return MultiBarsOptions.groups[n].scale end,
set = function(info, value)
local s = tonumber(value)
if s then
MultiBarsOptions.groups[n].scale = s
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end
end,
},
offsetX = {
type = 'range',
order = 4,
name = "X Offset",
desc = "Offset",
softMin = -100,
softMax = 100,
bigStep = 1,
get = function(info) return MultiBarsOptions.groups[n].offset.x end,
set = function(info, value)
local s = tonumber(value)
if s then
MultiBarsOptions.groups[n].offset.x = s
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end
end,
},
offsetY = {
type = 'range',
order = 5,
name = "Y Offset",
desc = "Offset",
softMin = -100,
softMax = 100,
bigStep = 1,
get = function(info) return MultiBarsOptions.groups[n].offset.y end,
set = function(info, value)
local s = tonumber(value)
if s then
MultiBarsOptions.groups[n].offset.y = s
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end
end,
},
hideWithPet = {
type = 'toggle',
order = 6,
name = "Hide if a pet is out",
desc = "The bars in this group will be hidden when the player has a pet out",
get = function(info) return MultiBarsOptions.groups[n].nopet end,
set = function(info, value)
MultiBarsOptions.groups[n].nopet = value
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end,
},
hideInCombat = {
type = 'toggle',
order = 7,
name = "Hide in combat",
desc = "The bars in this group will be hidden when the player is in combat",
get = function(info) return MultiBarsOptions.groups[n].nocombat end,
set = function(info, value)
MultiBarsOptions.groups[n].nocombat = value
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end,
},
}
}
local playerClass = UnitClassBase("player")
if playerClass == "DRUID" then
options.args[groupn].args.bars.values["MultiBarDruid"] = L.MultiBarDruid
elseif playerClass == "HUNTER" then
options.args[groupn].args.bars.values["MultiBarAspect"] = L.MultiBarAspect
options.args[groupn].args.bars.values["MultiBarFeedPet"] = L.MultiBarFeedPet
options.args[groupn].args.bars.values["MultiBarHunterPet"] = L.MultiBarHunterPet
options.args[groupn].args.bars.values["MultiBarTrap"] = L.MultiBarTrap
elseif playerClass == "MAGE" then
options.args[groupn].args.bars.values["MultiBarMageArmor"] = L.MultiBarMageArmor
options.args[groupn].args.bars.values["MultiBarMageBuff"] = L.MultiBarMageBuff
options.args[groupn].args.bars.values["MultiBarMagePortal"] = L.MultiBarMagePortal
elseif playerClass == "PALADIN" then
options.args[groupn].args.bars.values["MultiBarBlessing"] = L.MultiBarBlessing
options.args[groupn].args.bars.values["MultiBarSeal"] = L.MultiBarSeal
elseif playerClass == "PRIEST" then
options.args[groupn].args.bars.values["MultiBarPriest"] = L.MultiBarPriest
elseif playerClass == "WARLOCK" then
options.args[groupn].args.bars.values["MultiBarCurse"] = L.MultiBarCurse
options.args[groupn].args.bars.values["MultiBarDemon"] = L.MultiBarDemon
end
end
local function MultiBarsConfig_CreateLayoutOptions(MultiBars)
local options = {
name = "MultiBars Layout Groups",
handler = MultiBars,
type = 'group',
args = {
},
}
local n
for n = 1, #MultiBarsOptions.groups do
MultiBarsConfig_CreateLayoutGroupOptions(MultiBars, options, n)
end
return options
end
local function MultiBarsConfig_CreateBlacklistOptions(MultiBars)
local blacklistOptions = {
name = "MultiBars Item Blacklist",
handler = MultiBars,
type = 'group',
args = {
characterItems = {
type = 'input',
name = "Character-specific Item Blacklist",
desc = "Items to be blacklisted from appearing for this character",
width = "full",
get = function(info) return MultiBars:GetBlacklistString(false) end,
set = function(info, value)
MultiBars:SetBlacklistString(value, false)
MultiBarsCore_Bar_UpdateActions(MultiBarConsumable)
MultiBarsCore_Bar_UpdateActions(MultiBarFood)
end,
},
globalItems = {
type = 'input',
name = "Global Item Blacklist",
desc = "Items to be blacklisted from appearing for any character",
width = "full",
get = function(info) return MultiBars:GetBlacklistString(true) end,
set = function(info, value)
MultiBars:SetBlacklistString(value, true)
MultiBarsCore_Bar_UpdateActions(MultiBarConsumable)
MultiBarsCore_Bar_UpdateActions(MultiBarFood)
end,
},
},
}
return blacklistOptions
end
local function MultiBarsConfig_CreateMacroOptions(MultiBars)
local macroOptions = {
name = "MultiBars Macros",
handler = MultiBars,
type = 'group',
args = {},
}
local n
for n = 1, 12 do
macroOptions.args["macro" .. n] = {
type = 'input',
name = "Macro " .. n,
desc = "Macro " .. n,
order = (2 * n) - 1,
width = "double",
get = function(info) return MultiBars:GetMacroName(n) or "" end,
set = function(info, value)
MultiBars:SetMacroName(n, value)
MultiBarsCore_Bar_UpdateActions(MultiBarMacro)
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end,
}
macroOptions.args["macro" .. n .. "general"] = {
type = 'toggle',
name = "General Macro",
desc = "Use the named general macro instead of a character-specific macro",
order = 2 * n,
get = function(info) return MultiBars:IsMacroGeneral(n) end,
set = function(info, value)
MultiBars:SetMacroGeneral(n, value)
MultiBarsCore_Bar_UpdateActions(MultiBarMacro)
MultiBars:LayoutBars()
UIParent_ManageFramePositions()
end,
}
end
return macroOptions
end
function MultiBarsConfig_RegisterOptions(MultiBars, AceConfig, AceConfigDialog)
local options = MultiBarsConfig_CreateBaseOptions(MultiBars)
local barOptions = MultiBarsConfig_CreateBarOptions(MultiBars)
local layoutOptions = MultiBarsConfig_CreateLayoutOptions(MultiBars)
local blacklistOptions = MultiBarsConfig_CreateBlacklistOptions(MultiBars)
local macroOptions = MultiBarsConfig_CreateMacroOptions(MultiBars)
AceConfig:RegisterOptionsTable("MultiBars", options)
AceConfig:RegisterOptionsTable("MultiBarsBar", barOptions)
AceConfig:RegisterOptionsTable("MultiBarsLayout", layoutOptions)
AceConfig:RegisterOptionsTable("MultiBarsBlacklist", blacklistOptions)
AceConfig:RegisterOptionsTable("MultiBarsMacros", macroOptions)
MultiBars.optionsPanels = {
optionsPanel = AceConfigDialog:AddToBlizOptions("MultiBars", "MultiBars"),
barPanel = AceConfigDialog:AddToBlizOptions("MultiBarsBar", "Bars", "MultiBars"),
layoutPanel = AceConfigDialog:AddToBlizOptions("MultiBarsLayout", "Layout", "MultiBars"),
blacklistOptionsPanel = AceConfigDialog:AddToBlizOptions("MultiBarsBlacklist", "Item Blacklist", "MultiBars"),
macroOptionsPanel = AceConfigDialog:AddToBlizOptions("MultiBarsMacros", "Macros", "MultiBars"),
}
end
|
local function resolve()
local mleader = cache.get_cache_entry("marathonleader")
if mleader == nil then
ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
ngx.say("503 Service Unavailable: cache is invalid")
return ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
end
-- check the comment in cache.lua lib, fetch_and_store_marathon_leader() func
if mleader['address'] == "not elected" then
ngx.status = ngx.HTTP_NOT_FOUND
ngx.say("404 Not Found: Marathon leader is unknown.")
return ngx.exit(ngx.HTTP_NOT_FOUND)
end
ngx.var.mleader_host = DEFAULT_SCHEME .. mleader['address']
ngx.log(ngx.DEBUG, "Marathon leader addr from cache: " .. ngx.var.mleader_host)
end
-- Initialise and return the module:
local _M = {}
function _M.init()
local res = {}
res.resolve = resolve
return res
end
return _M
|
-- example "busy wait" daemon that's meant to crash
-- showing how "every" daemon is stand-alone
local i = 0
daemon.register(daemon.busy_wait, {
condition = function ()
i = i + 1
return (i > 2)
end,
action = function ()
print("event")
throw_exception("...")
end
})
|
print("Use cd [path] (where [path] is the directory) to go at a directory you want to go to")
print("Type dir to list the files and directories in your the directory.")
print("Type the name of the program you want to use (ends with .lua)")
|
STATE_PREGAME = 0;
STATE_GAME = 1;
STATE_POSTGAME = 2;
STATE_LOST = 3;
STATE_MAPEDIT = 99;
STATE_TIMES = {
[STATE_PREGAME] = 10,
[STATE_GAME] = 3550,
[STATE_POSTGAME] = 30
};
SUBSYSTEM_STATE_GOOD = 0;
SUBSYSTEM_STATE_DANGER = 1;
SUBSYSTEM_STATE_BROKEN = 2;
TASK_MASH = 0;
TASK_ALTERNATE = 1;
TASK_ROW = 2;
STAT_TERMINALS = 0;
STAT_DMG = 1;
TEAM_ENG = 1;
TEAM_PRO = 2;
TEAM_OFF = 3;
TEAM_UNJOINED = 999;
SHIP_HEALTH = 5;
INV_SIZE = 6;
|
package.path = package.path .. ";../lib/?.lua;?.lua"
local Compiler = require("com.blacksheepherd.ross.RossCompiler")
local Tester = require("com.blacksheepherd.test.Tester")
local File = require("com.blacksheepherd.io.File")
local t = Tester("RossCompileTest")
local function createCompileTest(className, filename)
return function()
local compiledSource = Compiler.Compile(className, require("data.ross.parsetrees.parsetree_" .. filename))
local checkSource = File.FileToString("./data/ross/lua/lua_" .. filename .. ".lua")
return Tester.AssertEqual(compiledSource, checkSource)
end
end
t:AddTest("Selector with an object and no properties.", createCompileTest("ObjectSelector", "object_selector"))
t:AddTest("Selector with properties attached.", createCompileTest("Properties", "properties"))
t:AddTest("Selector with a class.", createCompileTest("ClassSelector", "class_selector"))
t:AddTest("Selector with an id.", createCompileTest("IdSelector", "id_selector"))
t:AddTest("Multiple selectors on the stack.", createCompileTest("MultiSelectors", "multi_selectors"))
t:AddTest("Custom Object property filter.", createCompileTest("CustomObject", "custom_object"))
t:RunTests()
|
--[[
# Element: Border Highlight
Show a "glowing" texture when certain conditions are met.
## Widget
BorderHighlight - A "Table".
## Options
.target - Highlight when this is your current target (boolean)
.mouseover - Highlight when your mouse is over this unit (boolean)
.aggro - Highlight when this unit has aggro (boolean)
.debuff - Highlight when this unit has a debuff (integer)
1 - off (same as nil)
2 - Only highlight on debuffs you can dispel
3 - Highlight on all dispellable debuffs
#colors
.targetColor - {1, 1, 1}
.mouseoverColor - {1, 1, 1}
## Notes
A default texture will be applied if the widget is a Texture and doesn't have a texture set.
## Examples
-- Position and size
local BorderHighlight = {}
-- Register it with oUF
self.BorderHighlight = BorderHighlight
--]]
local _, ns = ...
local oUF = ns.oUF
local playerClass = select(2, UnitClass("player"))
local canCure = {}
local cures = {
["DRUID"] = {[2782] = {"Curse"}, [2893] = {"Poison"}, [8946] = {"Poison"}},
["PRIEST"] = {[528] = {"Disease"}, [552] = {"Disease"}, [527] = {"Magic"}, [988] = {"Magic"}},
["PALADIN"] = {[4987] = {"Poison", "Disease", "Magic"}, [1152] = {"Poison", "Disease"}},
["SHAMAN"] = {[2870] = {"Disease"}, [526] = {"Poison"}},
["MAGE"] = {[475] = {"Curse"}},
}
cures = cures[playerClass]
local function OnSizeChanged(self)
if not self then return end
local x, y = self:GetWidth(), self:GetHeight()
if x == 0 or y == 0 then return end
self.top:SetSize(x, self.size)
self.bottom:SetSize(x, self.size)
self.left:SetSize(self.size, y + (self.size * 2))
self.right:SetSize(self.size, y + (self.size * 2))
end
local function Update(self, event)
local element = self.BorderHighlight
local unit = self.unit
if not UnitExists(unit) then return end
if element.center.size ~= element.size then
element.center.size = element.size
OnSizeChanged(element.center)
end
--[[ Callback: BorderHighlight:PreUpdate()
Called before the element has been updated.
* self - the BorderHighlight element
--]]
if(element.PreUpdate) then
element:PreUpdate()
end
local hasMouseover = self == GetMouseFocus()
local isTarget = UnitIsUnit("target", unit)
local hasAggro = (UnitThreatSituation(unit) or 0) > 1
local showOwn, showAll, hasDebuff, highlightReason = element.debuff == 2, element.debuff == 3
if UnitIsFriend(unit, "player") then
for i=1, 16 do
local name, _, _, auraType = UnitDebuff(unit, i)
if( not name ) then break end
if( showOwn and canCure[auraType] and UnitCanAssist("player", unit) or (showAll and auraType) ) then
hasDebuff = auraType
break
end
end
end
local color
if element.debuff and element.debuff ~= 1 and hasDebuff then
color = oUF.colors.debuff[hasDebuff]
highlightReason = "debuff"
elseif element.aggro and hasAggro then
color = oUF.colors.threat[4]
highlightReason = "aggro"
elseif element.target and isTarget then
color = element.targetColor
highlightReason = "target"
elseif element.mouseover and hasMouseover then
color = element.mouseoverColor
highlightReason = "mouseover"
end
if not color then
element.center:Hide()
else
element.center:Show()
element.center.top:SetVertexColor(unpack(color))
element.center.bottom:SetVertexColor(unpack(color))
element.center.left:SetVertexColor(unpack(color))
element.center.right:SetVertexColor(unpack(color))
end
--[[ Callback: BorderHighlight:PostUpdate(highlightReason)
Called after the element has been updated.
* self - the BorderHighlight element
* highlightReason - what type of highlight is shown (nil, "mouseover", "target", "aggro", "debuff") (string)
--]]
if(element.PostUpdate) then
return element:PostUpdate(highlightReason)
end
end
local function checkCurableSpells(self, event, arg1)
if event == "UNIT_PET" and (arg1 ~= "player" or playerClass ~= "WARLOCK") then return end
table.wipe(canCure)
if playerClass == "WARLOCK" then
if IsUsableSpell(GetSpellInfo(19505)) then
canCure["Magic"] = true
end
elseif cures then
for spellID, types in pairs(cures) do
if( IsPlayerSpell(spellID) ) then
for _, type in pairs(types) do
canCure[type] = true
end
end
end
else
return
end
Update(self, event, self.unit)
end
local function Path(self, ...)
--[[ Override: BorderHighlight.Override(self, event, ...)
Used to completely override the internal update function.
* self - the parent object
* event - the event triggering the update (string)
* ... - the arguments accompanying the event
--]]
return (self.BorderHighlight.Override or Update) (self, ...)
end
local function ForceUpdate(element)
return Path(element.__owner, "ForceUpdate", element.__owner.unit)
end
local function Enable(self)
local element = self.BorderHighlight
if(element) then
element.__owner = self
element.ForceUpdate = ForceUpdate
self:RegisterEvent("UPDATE_MOUSEOVER_UNIT", Path, true)
self:RegisterEvent("UNIT_AURA", Path)
self:RegisterEvent("UNIT_THREAT_SITUATION_UPDATE", Path)
self:RegisterEvent("PLAYER_TARGET_CHANGED", Path, true)
self:RegisterEvent("LEARNED_SPELL_IN_TAB", checkCurableSpells, true)
self:RegisterEvent("PLAYER_LOGIN", checkCurableSpells, true)
self:RegisterEvent("UNIT_PET", checkCurableSpells, true)
if not element.center then
element.center = CreateFrame("Frame", nil, self)
element.center:SetScript("OnSizeChanged", OnSizeChanged)
element.center:SetAllPoints(self)
element.center.top = element.center:CreateTexture(nil, "BACKGROUND")
element.center.top:SetTexture([[Interface\Buttons\WHITE8X8]])
element.center.top:SetPoint("BOTTOMLEFT", element.center, "TOPLEFT")
element.center.bottom = element.center:CreateTexture(nil, "BACKGROUND")
element.center.bottom:SetTexture([[Interface\Buttons\WHITE8X8]])
element.center.bottom:SetPoint("TOPLEFT", element.center, "BOTTOMLEFT")
element.center.left = element.center:CreateTexture(nil, "BACKGROUND")
element.center.left:SetTexture([[Interface\Buttons\WHITE8X8]])
element.center.left:SetPoint("BOTTOMRIGHT", element.center.bottom, "BOTTOMLEFT")
element.center.right = element.center:CreateTexture(nil, "BACKGROUND")
element.center.right:SetTexture([[Interface\Buttons\WHITE8X8]])
element.center.right:SetPoint("BOTTOMLEFT", element.center.bottom, "BOTTOMRIGHT")
end
element.size = element.size or 1
element.center:Hide()
checkCurableSpells(self)
return true
end
end
local function Disable(self)
local element = self.BorderHighlight
if(element) then
element.center:Hide()
self:UnregisterEvent("UPDATE_MOUSEOVER_UNIT", Path)
self:UnregisterEvent("UNIT_AURA", Path)
self:UnregisterEvent("UNIT_THREAT_SITUATION_UPDATE", Path)
self:UnregisterEvent("PLAYER_TARGET_CHANGED", Path)
self:UnregisterEvent("LEARNED_SPELL_IN_TAB", checkCurableSpells)
self:UnregisterEvent("PLAYER_LOGIN", checkCurableSpells)
self:UnregisterEvent("UNIT_PET", checkCurableSpells)
end
end
oUF:AddElement("BorderHighlight", Path, Enable, Disable)
|
---
-- Implementation of afx.findfile
local string = require "string"
local table = require "table"
local coroutine = require "coroutine"
local PATH = require "path.module"
local function load(findfile_t)
local function clone(t) local o = {} for k,v in pairs(t) do o[k] = v end return o end
local function findfile_ssf(str_file, str_params, func_callback, tbl_option)
tbl_option = tbl_option and clone(tbl_option) or {}
tbl_option.file = assert(str_file)
tbl_option.param = assert(str_params)
tbl_option.callback = assert(func_callback)
return findfile_t(tbl_option)
end
local function findfile_ss(str_file, str_params, tbl_option)
tbl_option = tbl_option and clone(tbl_option) or {}
tbl_option.file = assert(str_file)
tbl_option.param = assert(str_params)
return findfile_t(tbl_option)
end
local function findfile_sf(str_file, func_callback, tbl_option)
tbl_option = tbl_option and clone(tbl_option) or {}
tbl_option.file = assert(str_file)
tbl_option.callback = assert(func_callback)
return findfile_t(tbl_option)
end
local function findfile_s(str_file, tbl_option)
tbl_option = tbl_option and clone(tbl_option) or {}
tbl_option.file = assert(str_file)
return findfile_t(tbl_option)
end
local function findfile_f(func_callback, tbl_option)
tbl_option = clone(assert(tbl_option)) -- need file
tbl_option.callback = assert(func_callback)
return findfile_t(tbl_option)
end
local function findfile(p1,p2,p3,p4)
if type(p1) == 'string' then
if type(p2) == 'string' then
if type(p3) == 'function' then
return findfile_ssf(p1,p2,p3,p4)
end
return findfile_ss(p1,p2,p3)
end
if type(p2) == 'function' then
return findfile_sf(p1,p2,p3)
end
return findfile_s(p1,p2)
end
if type(p1) == 'function' then
return findfile_f(p1,p2)
end
return findfile_t(p1)
end
return findfile
end
return {load = load}
|
local ROBO_RECIPES = {"equipment-bot-chip-feeder", "equipment-bot-chip-nanointerface"}
for _, force in pairs(game.forces) do
if force.technologies["personal-roboport-equipment"].researched then
for _, recipe in pairs(ROBO_RECIPES) do
if force.recipes[recipe] then force.recipes[recipe].enabled=true end
end
end
end
|
local utils = require 'utils'
validArgs = validArgs or utils.invert({
'help',
'civ',
'position',
'remove',
'add',
'verbose'
})
local args = utils.processArgs({...}, validArgs)
civid = tonumber(args.civ)
position = args.position
direction = 0
if args.remove then direction = -1 end
if args.add then direction = 1 end
if args.add and args.removes then return end
if direction == 0 then
print('No valid command, use -remove or -add')
return
end
dfhack.script_environment('functions/entity').changeNoble(civid,position,direction,args.verbose)
|
if managers.platform:presence() == "Playing" then
local num_winners = managers.network:session():amount_of_alive_players()
managers.network:session():send_to_peers( "mission_ended", true, num_winners )
game_state_machine:change_state_by_name( "victoryscreen", { num_winners = num_winners, personal_win = true } )
end
|
add_requires("vcpkg::zlib", "vcpkg::pcre2")
add_requires("vcpkg::boost[core]", {alias = "boost"})
target("test")
set_kind("binary")
add_files("src/*.cpp")
add_packages("vcpkg::zlib", "vcpkg::pcre2", "boost")
|
-- Requires Subliminal version 1.0 or newer
-- Make sure to specify your system's Subliminal location below:
subliminal = '/home/ananthu/.local/bin/subliminal'
language = 'en'
local utils = require 'mp.utils'
-- Log function: log to both terminal and mpv OSD (On-Screen Display)
function log(string, secs)
secs = secs or 2 -- secs defaults to 2 when the secs parameter is absent
mp.msg.warn(string) -- This logs to the terminal
mp.osd_message(string, secs) -- This logs to mpv screen
end
function download_subs()
log('Searching subtitles ...', 10)
path = mp.get_property('path')
filename = mp.get_property('filename')
save_dir = string.sub(path, 0, string.len(path) - string.len(filename))
conn_table = { args = {'ping','-c','1','google.com'} }
conn_result = utils.subprocess(conn_table)
if string.find(conn_result.stdout, 'packets transmitted') then
table = { args = {subliminal, 'download', '-s', '-l', language, '-d', save_dir, filename} }
result = utils.subprocess(table)
if string.find(result.stdout, 'Downloaded 1 subtitle') then
-- Subtitles are downloaded successfully, so rescan to activate them:
mp.commandv('rescan_external_files')
log('Subtitles ready!')
else
log('No subtitles found', 3)
end
else
log('Connection not available', 3)
end
end
-- Control function: only download if necessary
function control_download()
duration = tonumber(mp.get_property('duration'))
if duration < 900 then
mp.msg.warn('Video is less than 15 minutes\n=> NOT downloading any subtitles')
return
end
-- There does not seem to be any documentation for the 'sub' property,
-- but it works on both internally encoded as well as external subtitle files!
-- -> sub = number of subtitle track(s), when they are present
-- -> sub = 'no' when subtitles are not present
-- -> sub = 'auto' when called before the 'file-loaded' event is triggered
sub = tonumber(mp.get_property('sub')) or 0
if sub > 0 then
mp.msg.warn('Sub track is already present\n=> NOT downloading other subtitles')
return
end
mp.msg.warn('No sub track was detected\n=> Proceeding to download subtitles:')
download_subs()
end
-- For enabling auto download sub on startup uncomment below line
-- mp.register_event('file-loaded', control_download)
mp.add_key_binding('b', 'download_subs', download_subs)
|
data:extend({
{
type = "technology",
name = "meat-blood-processing",
icon = "__TheyreMadeOutofMeat__/graphics/icons/technology/liquid-blood.png",
icon_size = 128,
prerequisites = {"automation-2"},
effects = {
{
type = "unlock-recipe",
recipe = "dry-meat"
},
{
type = "unlock-recipe",
recipe = "meat-boiler"
}
},
unit = {
count = 50,
ingredients = {
{"automation-science-pack", 1},
},
time = 15
},
order = "meat-a-a"
},
{
type = "technology",
name = "meat-bone-processing",
icon = "__TheyreMadeOutofMeat__/graphics/icons/technology/bone-processing.png",
icon_size = 128,
prerequisites = {"meat-blood-processing"},
effects = {
{
type = "unlock-recipe",
recipe = "process-meat"
},
{
type = "unlock-recipe",
recipe = "meat-burger"
},
{
type = "unlock-recipe",
recipe = "bone-floor"
},
{
type = "unlock-recipe",
recipe = "bone-bullets"
}
},
unit = {
count = 100,
ingredients = {
{"automation-science-pack", 1},
},
time = 25
},
order = "meat-a-b"
},
{
type = "technology",
name = "meat-fuel-processing",
icon = "__TheyreMadeOutofMeat__/graphics/icons/technology/meat-cube.png",
icon_size = 128,
prerequisites = {"meat-bone-processing"},
effects = {
{
type = "unlock-recipe",
recipe = "compress-meat"
},
{
type = "unlock-recipe",
recipe = "solid-fuel-meat"
}
},
unit = {
count = 50,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
},
time = 30
},
order = "meat-a-c"
},
{
type = "technology",
name = "meat-robotics",
icon = "__base__/graphics/technology/construction-robotics.png",
icon_size = 128,
prerequisites = {
"meat-bone-processing",
"construction-robotics"
},
effects = {
{
type = "unlock-recipe",
recipe = "meat-roboport"
},
{
type = "unlock-recipe",
recipe = "meat-chest"
},
{
type = "unlock-recipe",
recipe = "meat-robot"
}
},
unit = {
count = 50,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1}
},
time = 30
},
order = "meat-b-g"
},
})
|
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com)
--
-- 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
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations under
-- the License.
debug = {}
---
--- Enters an interactive mode with the user, running each string that the user
--- enters. Using simple commands and other debug facilities, the user can
--- inspect global and local variables, change their values, evaluate
--- expressions, and so on. A line containing only the word `cont` finishes this
--- function, so that the caller continues its execution.
---
--- Note that commands for `debug.debug` are not lexically nested within any
--- function, and so have no direct access to local variables.
function debug.debug() end
---
--- Returns the current hook settings of the thread, as three values: the
--- current hook function, the current hook mask, and the current hook count
--- (as set by the `debug.sethook` function).
---@overload fun():thread
---@param thread thread
---@return thread
function debug.gethook(thread) end
---@shape std__DebugInfo
---@field activelines nil | {[number]: boolean}
---@field currentline number
---@field func nil | function
---@field istailcall boolean
---@field isvararg boolean
---@field lastlinedefined number
---@field linedefined number
---@field name nil | string
---@field namewhat "global" | "local" | "field" | "method"
---@field nparams number
---@field nups number
---@field short_src string
---@field source string
---@field what "C" | "main" | "lua"
---
--- This function returns a table with information about a function. You can
--- give the function directly, or you can give a number as the value of `f`,
--- which means the function running at level `f` of the call stack of the given
--- thread : Level 0 is the current function (`getinfo` itself); level 1 is the
--- function that called `getinfo`; and so on. If `f` is a number larger than
--- the number of active functions, then `getinfo` returns **nil**.
---
--- The returned table contains all the fields returned by `lua_getinfo`, with
--- the string `what` describing which fields to fill in. The default for `what`
--- is to get all information available. If present, the option "f" adds a field
--- named `func` with the function itself. If present, the option "L" adds a
--- field named `activelines` with the table of valid lines.
---
--- For instance, the expression `debug.getinfo(1,"n").name` returns the name of
--- the current function, if a reasonable name can be found, and
--- `debug.getinfo(print)` returns a table with all available information about
--- the `print` function.
---@overload fun(f: function | number): std__DebugInfo
---@overload fun(f: function | number, what: string): std__DebugInfo
---@overload fun(thread: thread, f: function | number): std__DebugInfo
---@param thread thread
---@param f function | number
---@param what string
---@return std__DebugInfo
function debug.getinfo(thread, f, what) end
---
--- This function returns the name and the value of the local variable with
--- index `local` of the function at level `level f` of the stack. This function
--- accesses not only explicit local variables, but also parameters,
--- temporaries, etc.
---
--- The first parameter or local variable has index 1, and so on, following the
--- order that they are declared in the code, counting only the variables that
--- are active in the current scope of the function. Negative indices refer to
--- vararg parameters; -1 is the first vararg parameter. The function returns
--- **nil** if there is no variable with the given index, and raises an error
--- when called with a level out of range. (You can call `debug.getinfo` to
--- check whether the level is valid.)
---
--- Variable names starting with '(' (open parenthesis) represent variables with
--- no known names (internal variables such as loop control variables, and
--- variables from chunks saved without debug information).
---
--- The parameter `f` may also be a function. In that case, `getlocal` returns
--- only the name of function parameters.
---@overload fun(f:table, var:string):table
---@param thread thread
---@param f table
---@param var string
---@return table
function debug.getlocal(thread, f, var) end
---
--- Returns the metatable of the given `value` or **nil** if it does not have
--- a metatable.
---@param value table
---@return table
function debug.getmetatable(value) end
---
--- Returns the registry table.
---@return table
function debug.getregistry() end
---
--- This function returns the name and the value of the upvalue with index
--- `up` of the function `f`. The function returns **nil** if there is no
--- upvalue with the given index.
---
--- Variable names starting with '(' (open parenthesis) represent variables with
--- no known names (variables from chunks saved without debug information).
---@param f number
---@param up number
---@return table
function debug.getupvalue(f, up) end
---
--- Returns the `n`-th user value associated to the userdata `u` plus a boolean,
--- **false** if the userdata does not have that value.
---@param u userdata
---@param n number
---@return boolean
function debug.getuservalue(u, n) end
---
--- Sets the given function as a hook. The string `mask` and the number `count`
--- describe when the hook will be called. The string mask may have any
--- combination of the following characters, with the given meaning:
---
--- * `"c"`: the hook is called every time Lua calls a function;
--- * `"r"`: the hook is called every time Lua returns from a function;
--- * `"l"`: the hook is called every time Lua enters a new line of code.
---
--- Moreover, with a `count` different from zero, the hook is called after every
--- `count` instructions.
---
--- When called without arguments, `debug.sethook` turns off the hook.
---
--- When the hook is called, its first parameter is a string describing
--- the event that has triggered its call: `"call"`, (or `"tail
--- call"`), `"return"`, `"line"`, and `"count"`. For line events, the hook also
--- gets the new line number as its second parameter. Inside a hook, you can
--- call `getinfo` with level 2 to get more information about the running
--- function (level 0 is the `getinfo` function, and level 1 is the hook
--- function)
---@overload fun(hook:(fun():any), mask:any)
---@param thread thread
---@param hook fun():any
---@param mask string
---@param count number
function debug.sethook(thread, hook, mask, count) end
---
--- This function assigns the value `value` to the local variable with
--- index `local` of the function at level `level` of the stack. The function
--- returns **nil** if there is no local variable with the given index, and
--- raises an error when called with a `level` out of range. (You can call
--- `getinfo` to check whether the level is valid.) Otherwise, it returns the
--- name of the local variable.
---@overload fun(level:number, var:string, value:any):string
---@param thread thread
---@param level number
---@param var string
---@param value any
---@return string
function debug.setlocal(thread, level, var, value) end
---
--- Sets the metatable for the given `object` to the given `table` (which
--- can be **nil**). Returns value.
---@param value any
---@param table table
---@return boolean
function debug.setmetatable(value, table) end
---
--- This function assigns the value `value` to the upvalue with index `up`
--- of the function `f`. The function returns **nil** if there is no upvalue
--- with the given index. Otherwise, it returns the name of the upvalue.
---@param f fun():any
---@param up number
---@param value any
---@return string
function debug.setupvalue(f, up, value) end
--- Sets the given `value` as the `n`-th associated to the given `udata`.
--- `udata` must be a full userdata.
---
--- Returns `udata`, or **nil** if the userdata does not have that value.
---@param udata userdata
---@param value any
---@param n number
---@return userdata
function debug.setuservalue(udata, value, n) end
--- If `message` is present but is neither a string nor **nil**, this function
--- returns `message` without further processing. Otherwise, it returns a string
--- with a traceback of the call stack. The optional `message` string is
--- appended at the beginning of the traceback. An optional `level` number
--- tells at which level to start the traceback (default is 1, the function
--- calling `traceback`).
---@overload fun(thread: thread, message: string): string
---@overload fun(message: string, level: number): string
---@overload fun(thread: thread): string
---@overload fun(message: string): string
---@overload fun(): string
---@param thread thread
---@param message string
---@param level number
---@return string
function debug.traceback(thread, message, level) end
--- Returns a unique identifier (as a light userdata) for the upvalue numbered
--- `n` from the given function.
---
--- These unique identifiers allow a program to check whether different
--- closures share upvalues. Lua closures that share an upvalue (that is, that
--- access a same external local variable) will return identical ids for those
--- upvalue indices.
---@param f fun():number
---@param n number
---@return number
function debug.upvalueid(f, n) end
---
--- Make the `n1`-th upvalue of the Lua closure f1 refer to the `n2`-th upvalue
--- of the Lua closure f2.
---@param f1 fun():any
---@param n1 number
---@param f2 fun():any
---@param n2 number
function debug.upvaluejoin(f1, n1, f2, n2) end
|
local Q = require 'Q'
local lDNN = require 'Q/RUNTIME/DNN/lua/lDNN'
local qc = require 'Q/UTILS/lua/qcore'
local Scalar = require 'libsclr'
function run_dnn(batch_size)
local batch_size = batch_size or 4096
local saved_file_path = "dnn_in.txt"
local n_samples = 1024 * 1024
print("batch size = ", batch_size)
-- For the first time, run the prepare_input.lua file to generate input (one time activity)
Q.restore(saved_file_path)
print("Network structure")
print("n_layers = " .. #npl)
local npl_str = ''
for i, v in pairs(npl) do
npl_str = npl_str .. "-" .. tostring(v)
end
print("structure = " .. npl_str)
local start_t = qc.RDTSC()
local x = lDNN.new({ npl = npl, dpl = dpl, activation_functions = afns} )
local end_t = qc.RDTSC()
print("dnn_new = " .. tonumber(end_t - start_t))
-- assert(x:check())
start_t = qc.RDTSC()
x:set_io(Xin, Xout)
end_t = qc.RDTSC()
print("set_io = " .. tonumber(end_t - start_t))
start_t = qc.RDTSC()
x:set_batch_size(batch_size)
end_t = qc.RDTSC()
print("set_batch = " .. tonumber(end_t - start_t))
print("training started")
start_t = qc.RDTSC()
x:fit(1)
end_t = qc.RDTSC()
print("fit = " .. tonumber(end_t - start_t))
print("Test succeeded")
end
return run_dnn
|
-- Petit script pour configurer le client WIFI du NodeMCU
print("\n wifi_cli_conf.lua zf180824.2000 \n")
wifi.sta.config{ssid="3g-s7", pwd="xxx", save=true}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.