repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
robert00s/koreader
spec/unit/cache_spec.lua
4
1555
describe("Cache module", function() local DocumentRegistry, Cache, DEBUG local doc local max_page = 1 setup(function() require("commonrequire") DocumentRegistry = require("document/documentregistry") Cache = require("cache") DEBUG = require("dbg") local sample_pdf = "spec/front/unit/data/sample.pdf" doc = DocumentRegistry:openDocument(sample_pdf) end) it("should clear cache", function() Cache:clear() end) it("should serialize blitbuffer", function() for pageno = 1, math.min(max_page, doc.info.number_of_pages) do doc:renderPage(pageno, nil, 1, 0, 1.0, 0) Cache:serialize() end Cache:clear() end) it("should deserialize blitbuffer", function() for pageno = 1, math.min(max_page, doc.info.number_of_pages) do doc:hintPage(pageno, 1, 0, 1.0, 0) end Cache:clear() end) it("should serialize koptcontext", function() doc.configurable.text_wrap = 1 for pageno = 1, math.min(max_page, doc.info.number_of_pages) do doc:renderPage(pageno, nil, 1, 0, 1.0, 0) doc:getPageDimensions(pageno) Cache:serialize() end Cache:clear() doc.configurable.text_wrap = 0 end) it("should deserialize koptcontext", function() for pageno = 1, math.min(max_page, doc.info.number_of_pages) do doc:renderPage(pageno, nil, 1, 0, 1.0, 0) end Cache:clear() end) end)
agpl-3.0
quill18/ProjectPorcupine
Assets/StreamingAssets/LUA/RoomBehavior.lua
36
3668
------------------------------------------------------- -- Project Porcupine Copyright(C) 2016 Team Porcupine -- This program comes with ABSOLUTELY NO WARRANTY; This is free software, -- and you are welcome to redistribute it under certain conditions; See -- file LICENSE, which is part of this source code package, for details. ------------------------------------------------------- -- HOWTO Log: -- ModUtils.ULog("Testing ModUtils.ULogChannel") -- ModUtils.ULogWarning("Testing ModUtils.ULogWarningChannel") -- ModUtils.ULogError("Testing ModUtils.ULogErrorChannel") -- Note: pauses the game -------------------------------- RoomBehavior Actions -------------------------------- function OnControl_Airlock( roomBehavior, deltaTime ) for discard, pressureDoor in pairs(roomBehavior.ControlledFurniture["Pressure Door"]) do pressureDoor.Parameters["pressure_locked"].SetValue(true) pressureDoor.Parameters["airlock_controlled"].SetValue(true) pressureDoor.UpdateOnChanged(pressureDoor) end for discard, pump in pairs(roomBehavior.ControlledFurniture["pump_air"]) do if (pump.Tile.South().Room == roomBehavior.room or pump.Tile.West().Room == roomBehavior.room ) then pump.Parameters["out_direction"].SetValue(1) else pump.Parameters["out_direction"].SetValue(0) end pump.Parameters["active"].SetValue(false) pump.Parameters["flow_direction_up"].SetValue(pump.Parameters["out_direction"].ToFloat()) pump.UpdateOnChanged(pump) end end function PumpOut_Airlock( roomBehavior, targetPressure ) --ModUtils.ULogWarning(os.clock() - roomBehavior.Parameters["pump_off_time"].ToFloat()) if (roomBehavior.Parameters["is_pumping_in"].ToBool() == false and (os.clock() - roomBehavior.Parameters["pump_off_time"].ToFloat()) > 2) then -- ModUtils.ULogWarning("Yes We Are") roomBehavior.Parameters["is_pumping_out"].SetValue(true) for discard, pump in pairs(roomBehavior.ControlledFurniture["pump_air"]) do pump.Parameters["source_pressure_limit"].SetValue(targetPressure) pump.Parameters["target_pressure_limit"].SetValue(3) pump.Parameters["active"].SetValue(true) pump.Parameters["flow_direction_up"].SetValue(pump.Parameters["out_direction"].ToFloat()) pump.UpdateOnChanged(pump) end end end function PumpIn_Airlock( roomBehavior, targetPressure ) --ModUtils.ULogWarning(os.clock() - roomBehavior.Parameters["pump_off_time"].ToFloat()) if (roomBehavior.Parameters["is_pumping_out"].ToBool() == false and (os.clock() - roomBehavior.Parameters["pump_off_time"].ToFloat()) > 2) then -- ModUtils.ULogWarning("Yes We Are") roomBehavior.Parameters["is_pumping_in"].SetValue(true) for discard, pump in pairs(roomBehavior.ControlledFurniture["pump_air"]) do pump.Parameters["source_pressure_limit"].SetValue(0) pump.Parameters["target_pressure_limit"].SetValue(targetPressure) pump.Parameters["active"].SetValue(true) pump.Parameters["flow_direction_up"].SetValue(1 - pump.Parameters["out_direction"].ToFloat()) pump.UpdateOnChanged(pump) end end end function PumpOff_Airlock( roomBehavior, deltaTime ) roomBehavior.Parameters["pump_off_time"].SetValue(os.clock()) roomBehavior.Parameters["is_pumping_in"].SetValue(false) roomBehavior.Parameters["is_pumping_out"].SetValue(false) for discard, pump in pairs(roomBehavior.ControlledFurniture["pump_air"]) do pump.Parameters["active"].SetValue(false) pump.UpdateOnChanged(pump) end end
gpl-3.0
cshore/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/disk.lua
68
1180
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.disk", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { { title = "%H: Disk I/O operations on %pi", vlabel = "Operations/s", number_format = "%5.1lf%sOp/s", data = { types = { "disk_ops" }, sources = { disk_ops = { "read", "write" }, }, options = { disk_ops__read = { title = "Reads", color = "00ff00", flip = false }, disk_ops__write = { title = "Writes", color = "ff0000", flip = true } } } }, { title = "%H: Disk I/O bandwidth on %pi", vlabel = "Bytes/s", number_format = "%5.1lf%sB/s", detail = true, data = { types = { "disk_octets" }, sources = { disk_octets = { "read", "write" } }, options = { disk_octets__read = { title = "Read", color = "00ff00", flip = false }, disk_octets__write = { title = "Write", color = "ff0000", flip = true } } } } } end
apache-2.0
daned33/nodemcu-firmware
lua_examples/yet-another-ds18b20.lua
79
1924
------------------------------------------------------------------------------ -- DS18B20 query module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- dofile("ds18b20.lua").read(4, function(r) for k, v in pairs(r) do print(k, v) end end) ------------------------------------------------------------------------------ local M do local bit = bit local format_addr = function(a) return ("%02x-%02x%02x%02x%02x%02x%02x"):format( a:byte(1), a:byte(7), a:byte(6), a:byte(5), a:byte(4), a:byte(3), a:byte(2) ) end local read = function(pin, cb, delay) local ow = require("ow") -- get list of relevant devices local d = { } ow.setup(pin) ow.reset_search(pin) while true do tmr.wdclr() local a = ow.search(pin) if not a then break end if ow.crc8(a) == 0 and (a:byte(1) == 0x10 or a:byte(1) == 0x28) then d[#d + 1] = a end end -- conversion command for all ow.reset(pin) ow.skip(pin) ow.write(pin, 0x44, 1) -- wait a bit tmr.alarm(0, delay or 100, 0, function() -- iterate over devices local r = { } for i = 1, #d do tmr.wdclr() -- read rom command ow.reset(pin) ow.select(pin, d[i]) ow.write(pin, 0xBE, 1) -- read data local x = ow.read_bytes(pin, 9) if ow.crc8(x) == 0 then local t = (x:byte(1) + x:byte(2) * 256) -- negatives? if bit.isset(t, 15) then t = 1 - bit.bxor(t, 0xffff) end -- NB: temperature in Celsius * 10^4 t = t * 625 -- NB: due 850000 means bad pullup. ignore if t ~= 850000 then r[format_addr(d[i])] = t end d[i] = nil end end cb(r) end) end -- expose M = { read = read, } end return M
mit
tupperkion/computercraft-programs
encryption.lua
1
7189
local function decimalToBinary(n) local left = n local max = 128 local current = max local result = {} repeat result[#result + 1] = (left >= current and "1" or "0") left = left >= current and left - current or left current = current / 2 until current < 1 return table.concat(result) end local function binaryToDecimal(n) local result = 0 for i = 1, 8 do if n:sub(i, i) == "1" then result = result + 2 ^ (8 - i) end end return result end local function reverseTable(t) local result = {} for i, j in ipairs(t) do result[#t - i + 1] = j end return result end local function toBase16(x) local digits = "0123456789abcdef" return (digits:sub(math.floor(x / 16) + 1, math.floor(x / 16) + 1))..(digits:sub(x % 16 + 1, x % 16 + 1)) end local function fromBase16(x) local digits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"} local result = 0 for i, j in pairs(digits) do if x:sub(1, 1) == j then result = result + (i - 1) * 16 end end for i, j in pairs(digits) do if x:sub(2, 2) == j then result = result + (i - 1) end end return result end function encodeAscii(x) local result = {} for i in x:gmatch(".") do result[#result + 1] = toBase16(string.byte(i)) end return table.concat(result) end function decodeAscii(x) local result = "" for i in x:gmatch("[0-f][0-f]") do result = result..(string.char(fromBase16(i))) end return result end function genKey(s) -- NOTE: will always produce same key if "s" is missing math.randomseed(s or 0) math.random(); math.random(); math.random(); math.random(); math.random() -- Reduce likelyhood of two seeds producing similar keys local result = "" local ops = math.random(45, 60) for i = 1, ops do local availableOps = {"s", "d", "r", "i", "b", "t", "m"} result = result..availableOps[math.random(1, #availableOps)]..math.random(5, 20) end return result end function encryptKey(k) return encodeAscii(k) end function decryptKey(k) return decodeAscii(k) end local function getSeedFromPassword(p) local result = 0 for i = 1, #p do result = result + (string.byte(p:sub(i)) * i * 255) end return result end function getKeyFromPassword(p) return genKey(getSeedFromPassword(p)) end function encodeWithKey(s, k) -- decrypted key required if type(s) ~= "string" then return s end local ops = {} for i in k:gmatch("[sbtxa]%d+") do ops[#ops + 1] = { name = i:match("%w"), count = tonumber(i:match("%d+")) } end local result = s local opFunctions = { s = function(n) -- Shift for i = 1, n do result = result:sub(-1)..result:sub(1, -2) end end, d = function(n) -- DoubleShift for i = 1, n do result = result:sub(-2)..result:sub(1, -3) end end, r = function(n) -- BitReverse for i = 1, n do local new = {} for i = 1, #result do new[#new + 1] = string.char(binaryToDecimal(decimalToBinary(string.byte(result:sub(i))):reverse())) end result = table.concat({new}) end end, i = function(n) -- BitInvert for i = 1, n do local new = {} for i = 1, #result do new[#new + 1] = string.char(binaryToDecimal(decimalToBinary(string.byte(result:sub(i))):gsub("0", "a"):gsub("1", "0"):gsub("a", "1"))) end result = table.concat(new) end end, b = function(n) -- BitShift for i = 1, n do local new = {} for i = 1, #result do local binary = decimalToBinary(string.byte(result:sub(i))) new[#new + 1] = string.char(binaryToDecimal(binary:sub(-1)..binary:sub(1, -2))) end result = table.concat(new) end end, t = function(n) -- TotalBitShift for i = 1, n do local bits = {} for i = 1, #result do bits[#bits + 1] = decimalToBinary(string.byte(result:sub(i))) end local bitString = table.concat(bits) bitString = bitString:sub(-1)..bitString:sub(1, -2) local resultTable = {} for i in bitString:gmatch("%d%d%d%d%d%d%d%d") do resultTable[#resultTable + 1] = string.char(binaryToDecimal(i)) end result = table.concat(resultTable) end end, m = function(n) -- BitMix for i = 1, n do local new = {} for j = 1, #result do local binary = "" local oldBinary = decimalToBinary(string.byte(result, i)) for k = 1, 8 do math.randomseed(i * j * k * n) binary = binary..(math.random(1, 2) == 1 and (oldBinary:sub(k) == "0" and "1" or "0") or oldBinary:sub(k)) end new[#new + 1] = string.char(binaryToDecimal(binary)) end result = table.concat(new) end end } for i, j in pairs(ops) do opFunctions[j.name](j.count) end return encodeAscii(result) end function decodeWithKey(s, k) if type(s) ~= "string" then return s end local ops = {} for i in k:gmatch("[sbtxa]%d+") do ops[#ops + 1] = { name = i:match("%w"), count = tonumber(i:match("%d+")) } end ops = reverseTable(ops) local result = decodeAscii(s) local opFunctions = { s = function(n) -- Shift for i = 1, n do result = result:sub(2)..result:sub(1, 1) end end, d = function(n) -- DoubleShift for i = 1, n do result = result:sub(3)..result:sub(1, 2) end end, r = function(n) -- BitReverse for i = 1, n do local new = {} for i = 1, #result do new[#new + 1] = string.char(binaryToDecimal(decimalToBinary(string.byte(result:sub(i))):reverse())) end result = table.concat(new) end end, i = function(n) -- BitInvert for i = 1, n do local new = {} for i = 1, #result do new[#new + 1] = string.char(binaryToDecimal(decimalToBinary(string.byte(result:sub(i))):gsub("0", "a"):gsub("1", "0"):gsub("a", "1"))) end result = table.concat(new) end end, b = function(n) -- BitShift for i = 1, n do local new = {} for i = 1, #result do local binary = decimalToBinary(string.byte(result:sub(i))) new[#new + 1] = string.char(binaryToDecimal(binary:sub(2)..binary:sub(1, 1))) end result = table.concat(new) end end, t = function(n) -- TotalBitShift for i = 1, n do local bits = {} for i = 1, #result do bits[#bits + 1] = decimalToBinary(string.byte(result:sub(i))) end local bitString = table.concat(bits) bitString = bitString:sub(2)..bitString:sub(1, 1) local resultTable = {} for i in bitString:gmatch("%d%d%d%d%d%d%d%d") do resultTable[#resultTable + 1] = string.char(binaryToDecimal(i)) end result = table.concat(resultTable) end end, m = function(n) -- BitMix for i = 1, n do local new = {} for j = 1, #result do local binary = "" local oldBinary = decimalToBinary(string.byte(result, i)) for k = 1, 8 do math.randomseed(i * j * k * n) binary = binary..(math.random(1, 2) == 1 and (oldBinary:sub(k) == "0" and "1" or "0") or oldBinary:sub(k)) end new[#new + 1] = string.char(binaryToDecimal(binary)) end result = table.concat(new) end end } for i, j in pairs(ops) do opFunctions[j.name](j.count) end return result end function encodeWithPassword(s, p) return encodeWithKey(s, getKeyFromPassword(p)) end function decodeWithPassword(s, p) return decodeWithKey(s, getKeyFromPassword(p)) end
mit
tianxiawuzhei/cocos-quick-lua
libs/quick/framework/cc/utils/Gettext.lua
21
3518
--[[ Load a mo file, retuan a lua function or table. A sample and description(in chinese): http://zengrong.net/post/1986.htm @see http://lua-users.org/lists/lua-l/2010-04/msg00005.html Modifier zrong(zengrong.net) Creation 2013-11-29 usage: local mo_data=assert(require("utils.Gettext").loadMOFromFile("main.mo")) print(mo_data["hello"]) -- 你好 print(mo_data["world"]) -- nil then you'll get a kind of gettext function: local gettext=assert(require("utils.Gettext").gettextFromFile("main.mo")) print(gettext("hello")) -- 你好 print(gettext("world")) -- world with a slight modification this will be ready-to-use for the xgettext tool: _ = assert(require("utils.Gettext").gettextFromFile("main.mo")) print(_("hello")) print(_("world")) ]] -- Original description ----------------------------------------------------------- -- load an mo file and return a lua table -- @param mo_file name of the file to load -- @return table on success -- @return nil,string on failure -- @copyright J.J?rgen von Bargen -- @licence I provide this as public domain -- @see http://www.gnu.org/software/hello/manual/gettext/MO-Files.html ----------------------------------------------------------- local Gettext = {} function Gettext._getFileData(mo_file) --- use lua io, cannot use in Android --[[ local fd,err=io.open(mo_file,"rb") if not fd then return nil,err end local mo_data=fd:read("*all") fd:close() --]] --- use quick-cocos2d-x cc.FileUtils, cross-platform local mo_data = cc.HelperFunc:getFileData(mo_file) return mo_data end function Gettext.loadMOFromFile(mo_file) return Gettext.parseData(Gettext._getFileData(mo_file)) end function Gettext.gettextFromFile(mo_file) return Gettext.gettext(Gettext._getFileData(mo_file)) end function Gettext.gettext(mo_data) local __hash = Gettext.parseData(mo_data) return function(text) return __hash[text] or text end end function Gettext.parseData(mo_data) -------------------------------- -- precache some functions -------------------------------- local byte=string.byte local sub=string.sub -------------------------------- -- check format -------------------------------- local peek_long --localize local magic=sub(mo_data,1,4) -- intel magic 0xde120495 if magic=="\222\018\004\149" then peek_long=function(offs) local a,b,c,d=byte(mo_data,offs+1,offs+4) return ((d*256+c)*256+b)*256+a end -- motorola magic = 0x950412de elseif magic=="\149\004\018\222" then peek_long=function(offs) local a,b,c,d=byte(mo_data,offs+1,offs+4) return ((a*256+b)*256+c)*256+d end else return nil,"no valid mo-file" end -------------------------------- -- version -------------------------------- local V=peek_long(4) if V~=0 then return nul,"unsupported version" end ------------------------------ -- get number of offsets of table ------------------------------ local N,O,T=peek_long(8),peek_long(12),peek_long(16) ------------------------------ -- traverse and get strings ------------------------------ local hash={} for nstr=1,N do local ol,oo=peek_long(O),peek_long(O+4) O=O+8 local tl,to=peek_long(T),peek_long(T+4) T=T+8 hash[sub(mo_data,oo+1,oo+ol)]=sub(mo_data,to+1,to+tl) end return hash -- return table end return Gettext
mit
NSAKEY/prosody-modules
mod_s2s_auth_monkeysphere/mod_s2s_auth_monkeysphere.lua
32
1870
module:set_global(); local http_request = require"socket.http".request; local ltn12 = require"ltn12"; local json = require"util.json"; local json_encode, json_decode = json.encode, json.decode; local gettime = require"socket".gettime; local serialize = require"util.serialization".serialize; local msva_url = assert(os.getenv"MONKEYSPHERE_VALIDATION_AGENT_SOCKET", "MONKEYSPHERE_VALIDATION_AGENT_SOCKET is unset, please set it").."/reviewcert"; local function check_with_monkeysphere(event) local session, host, cert = event.session, event.host, event.cert; local result = {}; local post_body = json_encode { peer = { name = host; type = "peer"; }; context = "https"; -- context = "xmpp"; -- Monkeysphere needs to be extended to understand this pkc = { type = "x509pem"; data = cert:pem(); }; } local req = { method = "POST"; url = msva_url; headers = { ["Content-Type"] = "application/json"; ["Content-Length"] = tostring(#post_body); }; sink = ltn12.sink.table(result); source = ltn12.source.string(post_body); }; session.log("debug", "Asking what Monkeysphere thinks about this certificate"); local starttime = gettime(); local ok, code = http_request(req); module:log("debug", "Request took %fs", gettime() - starttime); local body = table.concat(result); if ok and code == 200 and body then body = json_decode(body); if body then session.log(body.valid and "info" or "warn", "Monkeysphere thinks the cert is %salid: %s", body.valid and "V" or "Inv", body.message); if body.valid then session.cert_chain_status = "valid"; session.cert_identity_status = "valid"; return true; end end else module:log("warn", "Request failed: %s, %s", tostring(code), tostring(body)); module:log("debug", serialize(req)); end end module:hook("s2s-check-certificate", check_with_monkeysphere);
mit
dicebox/minetest-france
minetest/builtin/common/filterlist.lua
2
9943
--Minetest --Copyright (C) 2013 sapier -- --This program is free software; you can redistribute it and/or modify --it under the terms of the GNU Lesser General Public License as published by --the Free Software Foundation; either version 2.1 of the License, or --(at your option) any later version. -- --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --GNU Lesser General Public License for more details. -- --You should have received a copy of the GNU Lesser General Public License along --with this program; if not, write to the Free Software Foundation, Inc., --51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -------------------------------------------------------------------------------- -- TODO improve doc -- -- TODO code cleanup -- -- Generic implementation of a filter/sortable list -- -- Usage: -- -- Filterlist needs to be initialized on creation. To achieve this you need to -- -- pass following functions: -- -- raw_fct() (mandatory): -- -- function returning a table containing the elements to be filtered -- -- compare_fct(element1,element2) (mandatory): -- -- function returning true/false if element1 is same element as element2 -- -- uid_match_fct(element1,uid) (optional) -- -- function telling if uid is attached to element1 -- -- filter_fct(element,filtercriteria) (optional) -- -- function returning true/false if filtercriteria met to element -- -- fetch_param (optional) -- -- parameter passed to raw_fct to aquire correct raw data -- -- -- -------------------------------------------------------------------------------- filterlist = {} -------------------------------------------------------------------------------- function filterlist.refresh(self) self.m_raw_list = self.m_raw_list_fct(self.m_fetch_param) filterlist.process(self) end -------------------------------------------------------------------------------- function filterlist.create(raw_fct,compare_fct,uid_match_fct,filter_fct,fetch_param) assert((raw_fct ~= nil) and (type(raw_fct) == "function")) assert((compare_fct ~= nil) and (type(compare_fct) == "function")) local self = {} self.m_raw_list_fct = raw_fct self.m_compare_fct = compare_fct self.m_filter_fct = filter_fct self.m_uid_match_fct = uid_match_fct self.m_filtercriteria = nil self.m_fetch_param = fetch_param self.m_sortmode = "none" self.m_sort_list = {} self.m_processed_list = nil self.m_raw_list = self.m_raw_list_fct(self.m_fetch_param) self.add_sort_mechanism = filterlist.add_sort_mechanism self.set_filtercriteria = filterlist.set_filtercriteria self.get_filtercriteria = filterlist.get_filtercriteria self.set_sortmode = filterlist.set_sortmode self.get_list = filterlist.get_list self.get_raw_list = filterlist.get_raw_list self.get_raw_element = filterlist.get_raw_element self.get_raw_index = filterlist.get_raw_index self.get_current_index = filterlist.get_current_index self.size = filterlist.size self.uid_exists_raw = filterlist.uid_exists_raw self.raw_index_by_uid = filterlist.raw_index_by_uid self.refresh = filterlist.refresh filterlist.process(self) return self end -------------------------------------------------------------------------------- function filterlist.add_sort_mechanism(self,name,fct) self.m_sort_list[name] = fct end -------------------------------------------------------------------------------- function filterlist.set_filtercriteria(self,criteria) if criteria == self.m_filtercriteria and type(criteria) ~= "table" then return end self.m_filtercriteria = criteria filterlist.process(self) end -------------------------------------------------------------------------------- function filterlist.get_filtercriteria(self) return self.m_filtercriteria end -------------------------------------------------------------------------------- --supported sort mode "alphabetic|none" function filterlist.set_sortmode(self,mode) if (mode == self.m_sortmode) then return end self.m_sortmode = mode filterlist.process(self) end -------------------------------------------------------------------------------- function filterlist.get_list(self) return self.m_processed_list end -------------------------------------------------------------------------------- function filterlist.get_raw_list(self) return self.m_raw_list end -------------------------------------------------------------------------------- function filterlist.get_raw_element(self,idx) if type(idx) ~= "number" then idx = tonumber(idx) end if idx ~= nil and idx > 0 and idx <= #self.m_raw_list then return self.m_raw_list[idx] end return nil end -------------------------------------------------------------------------------- function filterlist.get_raw_index(self,listindex) assert(self.m_processed_list ~= nil) if listindex ~= nil and listindex > 0 and listindex <= #self.m_processed_list then local entry = self.m_processed_list[listindex] for i,v in ipairs(self.m_raw_list) do if self.m_compare_fct(v,entry) then return i end end end return 0 end -------------------------------------------------------------------------------- function filterlist.get_current_index(self,listindex) assert(self.m_processed_list ~= nil) if listindex ~= nil and listindex > 0 and listindex <= #self.m_raw_list then local entry = self.m_raw_list[listindex] for i,v in ipairs(self.m_processed_list) do if self.m_compare_fct(v,entry) then return i end end end return 0 end -------------------------------------------------------------------------------- function filterlist.process(self) assert(self.m_raw_list ~= nil) if self.m_sortmode == "none" and self.m_filtercriteria == nil then self.m_processed_list = self.m_raw_list return end self.m_processed_list = {} for k,v in pairs(self.m_raw_list) do if self.m_filtercriteria == nil or self.m_filter_fct(v,self.m_filtercriteria) then self.m_processed_list[#self.m_processed_list + 1] = v end end if self.m_sortmode == "none" then return end if self.m_sort_list[self.m_sortmode] ~= nil and type(self.m_sort_list[self.m_sortmode]) == "function" then self.m_sort_list[self.m_sortmode](self) end end -------------------------------------------------------------------------------- function filterlist.size(self) if self.m_processed_list == nil then return 0 end return #self.m_processed_list end -------------------------------------------------------------------------------- function filterlist.uid_exists_raw(self,uid) for i,v in ipairs(self.m_raw_list) do if self.m_uid_match_fct(v,uid) then return true end end return false end -------------------------------------------------------------------------------- function filterlist.raw_index_by_uid(self, uid) local elementcount = 0 local elementidx = 0 for i,v in ipairs(self.m_raw_list) do if self.m_uid_match_fct(v,uid) then elementcount = elementcount +1 elementidx = i end end -- If there are more elements than one with same name uid can't decide which -- one is meant. self shouldn't be possible but just for sure. if elementcount > 1 then elementidx=0 end return elementidx end -------------------------------------------------------------------------------- -- COMMON helper functions -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function compare_worlds(world1,world2) if world1.path ~= world2.path then return false end if world1.name ~= world2.name then return false end if world1.gameid ~= world2.gameid then return false end return true end -------------------------------------------------------------------------------- function sort_worlds_alphabetic(self) table.sort(self.m_processed_list, function(a, b) --fixes issue #857 (crash due to sorting nil in worldlist) if a == nil or b == nil then if a == nil and b ~= nil then return false end if b == nil and a ~= nil then return true end return false end if a.name:lower() == b.name:lower() then return a.name < b.name end return a.name:lower() < b.name:lower() end) end -------------------------------------------------------------------------------- function sort_mod_list(self) table.sort(self.m_processed_list, function(a, b) -- Show game mods at bottom if a.typ ~= b.typ then return b.typ == "game_mod" end -- If in same or no modpack, sort by name if a.modpack == b.modpack then if a.name:lower() == b.name:lower() then return a.name < b.name end return a.name:lower() < b.name:lower() -- Else compare name to modpack name else -- Always show modpack pseudo-mod on top of modpack mod list if a.name == b.modpack then return true elseif b.name == a.modpack then return false end local name_a = a.modpack or a.name local name_b = b.modpack or b.name if name_a:lower() == name_b:lower() then return name_a < name_b end return name_a:lower() < name_b:lower() end end) end
gpl-3.0
jugglerchris/textredux
examples/init.lua
2
1734
-- Copyright 2011-2012 Nils Nordman <nino at nordman.org> -- Copyright 2012-2014 Robert Gieseke <rob.g@web.de> -- License: MIT (see LICENSE) --[[ This directory contains a few examples that show how to build text based interfaces with the modules in `textredux.core`. When Textredux is installed you can paste the following line in Textadept's command entry to show a list of examples: examples = require('textredux.examples').show_examples() to select from a list of examples. ]] local M = {} local textredux = require 'textredux' M.basic_list = require 'textredux.examples.basic_list' M.buffer_actions = require 'textredux.examples.buffer_actions' M.buffer_indicators = require 'textredux.examples.buffer_indicators' M.buffer_styling = require 'textredux.examples.buffer_styling' M.list_commands = require 'textredux.examples.list_commands' M.multi_column_list = require 'textredux.examples.multi_column_list' M.styled_list = require 'textredux.examples.styled_list' examples = { ['Buffer styling'] = M.buffer_styling.create_styled_buffer, ['Basic list'] = M.basic_list.show_simple_list, ['Buffer indicators'] = M.buffer_indicators.create_indicator_buffer, ['Styled list'] = M.styled_list.show_styled_list, ['List commands'] = M.list_commands.show_action_list, ['Multi column list'] = M.multi_column_list.show_multi_column_list, ['Buffer actions'] = M.buffer_actions.create_action_buffer } local keys = {} for k, v in pairs(examples) do keys[#keys+1] = k end local function on_selection(list, item) ui.statusbar_text = item examples[item]() end function M.show_examples() local list = textredux.core.list.new( 'Textredux examples', keys, on_selection ) list:show() end return M
mit
4w/xtend
xfurniture/furniture/couches.lua
1
4580
local _register = _xtend.mods.xfurniture.register local _p2r = _xtend.mods.xfurniture.pattern_to_recipe for node in pairs(_xtend.mods.xfurniture.nodes) do ---------------------------------------------------------------------------- _register('couch_frame_u', { name = _xtend.translate('Couch U Frame'), material = node, nodebox = { {-0.5, -0.375, -0.625, 0.5, -0.3125, -0.375}, -- U_base {-0.625, -0.375, -0.5, -0.375, -0.3125, 0.5}, -- U_left {0.375, -0.375, -0.5, 0.625, -0.3125, 0.5}, -- U_right {-0.625, -0.5, 0.375, -0.375, -0.375, 0.5}, -- U_left_top_f {0.375, -0.5, 0.375, 0.625, -0.375, 0.5}, -- U_right_top_f {-0.625, -0.5, -0.625, -0.375, -0.3125, -0.375}, -- U_left_bottom_f {0.375, -0.5, -0.625, 0.625, -0.3125, -0.375}, -- U_right_bottom_f {-0.375, -0.25, -0.375, 0.375, -0.1875, 0.4375} -- placement_helper }, recipe = _p2r(node, 'couch_frame_u') }) _register('couch_frame_bars', { name = _xtend.translate('Couch Bars Frame'), material = node, nodebox = { {-0.5, -0.375, 0.375, 0.5, -0.3125, 0.625}, -- top {-0.5, -0.375, -0.625, 0.5, -0.3125, -0.375}, -- bottom {-0.5, -0.5, -0.625, -0.375, -0.375, -0.375}, -- bottom_left_foot {0.375, -0.5, -0.625, 0.5, -0.375, -0.375}, -- bottom_right_foot {-0.5, -0.5, 0.375, -0.375, -0.375, 0.625}, -- top_left_foot {0.375, -0.5, 0.375, 0.5, -0.375, 0.625}, -- top_right_foot {-0.4375, -0.25, -0.375, 0.4375, -0.1875, 0.375} -- placement_helper }, recipe = _p2r(node, 'couch_frame_bars') }) _register('couch_frame_corner', { name = _xtend.translate('Regular Couch Corner Frame'), material = node, nodebox = { {-0.5, -0.375, 0.375, 0.5, -0.3125, 0.625}, -- top {0.375, -0.375, -0.5, 0.625, -0.3125, 0.5}, -- right {-0.5, -0.5, 0.375, -0.375, -0.375, 0.625}, -- top_left_foot {0.375, -0.5, 0.375, 0.625, -0.3125, 0.625}, -- top_right_foot {-0.5, -0.5, -0.5, -0.375, -0.3125, -0.375}, -- bottom_left_foot {0.375, -0.5, -0.5, 0.625, -0.375, -0.375}, -- bottom_right_foot {-0.4375, -0.25, -0.4375, 0.375, -0.1875, 0.375} -- placement_helper }, recipe = _p2r(node, 'couch_frame_corner_regular') }) ---------------------------------------------------------------------------- _register('couch_seat_end_left', { name = _xtend.translate('Couch Left End Seat'), material = node, nodebox = { {-0.6875, -1.3125, -0.6875, 0.5, -1, 0.6875}, -- seat {-0.6875, -1, -0.5625, -0.4375, -0.75, 0.6875}, -- armrest {-0.5625, -1, 0.3125, 0.5, -0.5, 0.6875} -- backrest }, recipe = _p2r(node, 'couch_seat_end_left') }) _register('couch_seat_end_right', { name = _xtend.translate('Couch Right End Seat'), material = node, nodebox = { {-0.5, -1.3125, -0.6875, 0.6875, -1, 0.6875}, -- seat {0.4375, -1, -0.5625, 0.6875, -0.75, 0.6875}, -- armrest {-0.5, -1, 0.3125, 0.5625, -0.5, 0.6875} -- backrest }, recipe = _p2r(node, 'couch_seat_end_right') }) _register('couch_seat_center', { name = _xtend.translate('Couch Center Seat'), material = node, nodebox = { {-0.5, -1.3125, -0.6875, 0.5, -1, 0.6875}, -- seat {-0.5, -1, 0.3125, 0.5, -0.5, 0.6875} -- backrest }, recipe = _p2r(node, 'couch_seat_center') }) _register('couch_seat_corner_regular', { name = _xtend.translate('Couch Corner Seat (Regular)'), material = node, nodebox = { {-0.5, -1.3125, -0.5, 0.6875, -1, 0.6875}, -- seat {-0.5, -1, 0.3125, 0.5, -0.5, 0.6875}, -- backrest_1 {0.3125, -1.3125, -0.5, 0.6875, -0.5, 0.6875} -- backrest_2 }, recipe = _p2r(node, 'couch_seat_corner_regular') }) _register('couch_seat_corner_inverted', { name = _xtend.translate('Couch Corner Seat (Inverted)'), material = node, nodebox = { {-0.6875, -1.3125, -0.6875, 0.6875, -1, 0.6875}, -- seat {0.3125, -1, 0.3125, 0.6875, -0.5, 0.6875} -- backrest_pillar }, recipe = _p2r(node, 'couch_seat_corner_inverted') }) ---------------------------------------------------------------------------- end
gpl-3.0
bigdogmat/wire
lua/entities/gmod_wire_button.lua
1
4524
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Button" ENT.WireDebugName = "Button" function ENT:SetupDataTables() self:NetworkVar( "Bool", 0, "On" ) end if CLIENT then local halo_ent, halo_blur function ENT:Initialize() self.PosePosition = 0.0 end function ENT:Think() baseclass.Get("gmod_button").UpdateLever(self) end function ENT:Draw() self:DoNormalDraw(true,false) if LocalPlayer():GetEyeTrace().Entity == self and EyePos():Distance( self:GetPos() ) < 512 then if self:GetOn() then halo_ent = self halo_blur = 4 + math.sin(CurTime()*20)*2 else self:DrawEntityOutline() end end Wire_Render(self) end hook.Add("PreDrawHalos", "Wiremod_button_overlay_halos", function() if halo_ent then halo.Add({halo_ent}, Color(255,100,100), halo_blur, halo_blur, 1, true, true) halo_ent = nil end end) return -- No more client end ENT.OutputEntID = false ENT.EntToOutput = NULL local anims = { -- ["model"] = { on_anim, off_anim } ["models/props/switch001.mdl"] = { 2, 1 }, ["models/props_combine/combinebutton.mdl"] = { 3, 2 }, ["models/props_mining/control_lever01.mdl"] = { 1, 4 }, ["models/props_mining/freightelevatorbutton01.mdl"] = { 1, 2 }, ["models/props_mining/freightelevatorbutton02.mdl"] = { 1, 2 }, ["models/props_mining/switch01.mdl"] = { 1, 2 }, ["models/bull/buttons/rocker_switch.mdl"] = { 1, 2 }, ["models/bull/buttons/toggle_switch.mdl"] = { 1, 2 }, ["models/bull/buttons/key_switch.mdl"] = { 1, 2 }, ["models/props_mining/switch_updown01.mdl"] = { 2, 3 }, } function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) self.Outputs = Wire_CreateOutputs(self, { "Out" }) self.Inputs = Wire_CreateInputs(self, { "Set" }) local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[2]) end end function ENT:TriggerInput(iname, value) if iname == "Set" then if (self.toggle) then self:Switch(value ~= 0) self.PrevUser = nil self.podpress = nil end end end function ENT:Use(ply, caller) if (not ply:IsPlayer()) then return end if (self.PrevUser) and (self.PrevUser:IsValid()) then return end if self.OutputEntID then self.EntToOutput = ply end if (self:GetOn()) then if (self.toggle) then self:Switch(false) end return end if IsValid(caller) and caller:GetClass() == "gmod_wire_pod" then self.podpress = true end self:Switch(true) self.PrevUser = ply end function ENT:Think() self.BaseClass.Think(self) if ( self:GetOn() ) then if (not self.PrevUser) or (not self.PrevUser:IsValid()) or (not self.podpress and not self.PrevUser:KeyDown(IN_USE)) or (self.podpress and not self.PrevUser:KeyDown( IN_ATTACK )) then if (not self.toggle) then self:Switch(false) end self.PrevUser = nil self.podpress = nil end self:NextThink(CurTime()+0.05) return true end end function ENT:Setup(toggle, value_off, value_on, description, entityout) self.toggle = toggle self.value_off = value_off self.value_on = value_on self.entityout = entityout if entityout then WireLib.AdjustSpecialOutputs(self, { "Out", "EntID" , "Entity" }, { "NORMAL", "NORMAL" , "ENTITY" }) Wire_TriggerOutput(self, "EntID", 0) Wire_TriggerOutput(self, "Entity", nil) self.OutputEntID=true else Wire_AdjustOutputs(self, { "Out" }) self.OutputEntID=false end if toggle then Wire_AdjustInputs(self, { "Set" }) else Wire_AdjustInputs(self, {}) end self:Switch(self:GetOn()) end function ENT:Switch(on) if (not self:IsValid()) then return end self:SetOn( on ) if (on) then self:ShowOutput(self.value_on) self.Value = self.value_on local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[1]) end else self:ShowOutput(self.value_off) self.Value = self.value_off local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[2]) end if self.OutputEntID then self.EntToOutput = NULL end end Wire_TriggerOutput(self, "Out", self.Value) if self.OutputEntID then Wire_TriggerOutput(self, "EntID", self.EntToOutput:EntIndex()) Wire_TriggerOutput(self, "Entity", self.EntToOutput) end return true end function ENT:ShowOutput(value) self:SetOverlayText( "(" .. self.value_off .. " - " .. self.value_on .. ") = " .. value ) end duplicator.RegisterEntityClass("gmod_wire_button", WireLib.MakeWireEnt, "Data", "toggle", "value_off", "value_on", "description", "entityout" )
apache-2.0
ioiasff/qrt
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
robert00s/koreader
frontend/device/input.lua
1
21627
local Event = require("ui/event") local TimeVal = require("ui/timeval") local input = require("ffi/input") local DEBUG = require("dbg") local logger = require("logger") local _ = require("gettext") local Key = require("device/key") local GestureDetector = require("device/gesturedetector") local framebuffer = require("ffi/framebuffer") -- luacheck: push -- luacheck: ignore -- constants from <linux/input.h> local EV_SYN = 0 local EV_KEY = 1 local EV_ABS = 3 local EV_MSC = 4 -- key press event values (KEY.value) local EVENT_VALUE_KEY_PRESS = 1 local EVENT_VALUE_KEY_REPEAT = 2 local EVENT_VALUE_KEY_RELEASE = 0 -- Synchronization events (SYN.code). local SYN_REPORT = 0 local SYN_CONFIG = 1 local SYN_MT_REPORT = 2 -- For single-touch events (ABS.code). local ABS_X = 00 local ABS_Y = 01 local ABS_PRESSURE = 24 -- For multi-touch events (ABS.code). local ABS_MT_SLOT = 47 local ABS_MT_TOUCH_MAJOR = 48 local ABS_MT_WIDTH_MAJOR = 50 local ABS_MT_POSITION_X = 53 local ABS_MT_POSITION_Y = 54 local ABS_MT_TRACKING_ID = 57 local ABS_MT_PRESSURE = 58 -- For Kindle Oasis orientation events (ABS.code) -- the ABS code of orientation event will be adjusted to -24 from 24(ABS_PRESSURE) -- as ABS_PRESSURE is also used to detect touch input in KOBO devices. local ABS_OASIS_ORIENTATION = -24 local DEVICE_ORIENTATION_PORTRAIT_LEFT = 15 local DEVICE_ORIENTATION_PORTRAIT_RIGHT = 17 local DEVICE_ORIENTATION_PORTRAIT = 19 local DEVICE_ORIENTATION_PORTRAIT_ROTATED_LEFT = 16 local DEVICE_ORIENTATION_PORTRAIT_ROTATED_RIGHT = 18 local DEVICE_ORIENTATION_PORTRAIT_ROTATED = 20 local DEVICE_ORIENTATION_LANDSCAPE = 21 local DEVICE_ORIENTATION_LANDSCAPE_ROTATED = 22 -- luacheck: pop --[[ an interface to get input events ]] local Input = { -- this depends on keyboard layout and should be overridden: event_map = {}, -- adapters are post processing functions that transform a given event to another event event_map_adapter = {}, group = { Cursor = { "Up", "Down", "Left", "Right" }, PgFwd = { "RPgFwd", "LPgFwd" }, PgBack = { "RPgBack", "LPgBack" }, Alphabet = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }, AlphaNumeric = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }, Numeric = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }, Text = { " ", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }, Any = { " ", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Up", "Down", "Left", "Right", "Press", "Back", "Enter", "Sym", "AA", "Menu", "Home", "Del", "LPgBack", "RPgBack", "LPgFwd", "RPgFwd" }, }, rotation_map = { [framebuffer.ORIENTATION_PORTRAIT] = {}, [framebuffer.ORIENTATION_LANDSCAPE] = { Up = "Right", Right = "Down", Down = "Left", Left = "Up" }, [framebuffer.ORIENTATION_PORTRAIT_ROTATED] = { Up = "Down", Right = "Left", Down = "Up", Left = "Right", LPgFwd = "LPgBack", LPgBack = "LPgFwd", RPgFwd = "RPgBack", RPgBack = "RPgFwd" }, [framebuffer.ORIENTATION_LANDSCAPE_ROTATED] = { Up = "Left", Right = "Up", Down = "Right", Left = "Down" , LPgFwd = "LPgBack", LPgBack = "LPgFwd", RPgFwd = "RPgBack", RPgBack = "RPgFwd" } }, timer_callbacks = {}, disable_double_tap = true, -- keyboard state: modifiers = { Alt = false, Shift = false, }, -- touch state: cur_slot = 0, MTSlots = {}, ev_slots = { [0] = { slot = 0, } }, gesture_detector = nil, } function Input:new(o) o = o or {} setmetatable(o, self) self.__index = self if o.init then o:init() end return o end function Input:init() self.gesture_detector = GestureDetector:new{ screen = self.device.screen, input = self, } -- set up fake event map self.event_map[10000] = "IntoSS" -- go into screen saver self.event_map[10001] = "OutOfSS" -- go out of screen saver self.event_map[10020] = "Charging" self.event_map[10021] = "NotCharging" -- user custom event map local ok, custom_event_map = pcall(dofile, "custom.event.map.lua") if ok then for key, value in pairs(custom_event_map) do self.event_map[key] = value end logger.info("loaded custom event map", custom_event_map) end end --[[ wrapper for FFI input open Note that we adhere to the "." syntax here for compatibility. TODO: clean up separation FFI/this --]] function Input.open(device, is_emu_events) input.open(device, is_emu_events and 1 or 0) end --[[ Different device models can implement their own hooks and register them. --]] function Input:registerEventAdjustHook(hook, hook_params) local old = self.eventAdjustHook self.eventAdjustHook = function(this, ev) old(this, ev) hook(this, ev, hook_params) end end function Input:registerGestureAdjustHook(hook, hook_params) local old = self.gestureAdjustHook self.gestureAdjustHook = function(this, ges) old(this, ges) hook(this, ges, hook_params) end end function Input:eventAdjustHook(ev) -- do nothing by default end function Input:gestureAdjustHook(ges) -- do nothing by default end -- catalogue of predefined hooks: function Input:adjustTouchSwitchXY(ev) if ev.type == EV_ABS then if ev.code == ABS_X then ev.code = ABS_Y elseif ev.code == ABS_Y then ev.code = ABS_X elseif ev.code == ABS_MT_POSITION_X then ev.code = ABS_MT_POSITION_Y elseif ev.code == ABS_MT_POSITION_Y then ev.code = ABS_MT_POSITION_X end end end function Input:adjustTouchScale(ev, by) if ev.type == EV_ABS then if ev.code == ABS_X or ev.code == ABS_MT_POSITION_X then ev.value = by.x * ev.value end if ev.code == ABS_Y or ev.code == ABS_MT_POSITION_Y then ev.value = by.y * ev.value end end end function Input:adjustTouchMirrorX(ev, width) if ev.type == EV_ABS and (ev.code == ABS_X or ev.code == ABS_MT_POSITION_X) then ev.value = width - ev.value end end function Input:adjustTouchMirrorY(ev, height) if ev.type == EV_ABS and (ev.code == ABS_Y or ev.code == ABS_MT_POSITION_Y) then ev.value = height - ev.value end end function Input:adjustTouchTranslate(ev, by) if ev.type == EV_ABS then if ev.code == ABS_X or ev.code == ABS_MT_POSITION_X then ev.value = by.x + ev.value end if ev.code == ABS_Y or ev.code == ABS_MT_POSITION_Y then ev.value = by.y + ev.value end end end function Input:adjustKindleOasisOrientation(ev) if ev.type == EV_ABS and ev.code == ABS_PRESSURE then ev.code = ABS_OASIS_ORIENTATION end end function Input:setTimeout(cb, tv_out) local item = { callback = cb, deadline = tv_out, } table.insert(self.timer_callbacks, item) table.sort(self.timer_callbacks, function(v1,v2) return v1.deadline < v2.deadline end) end function Input:handleKeyBoardEv(ev) local keycode = self.event_map[ev.code] if not keycode then -- do not handle keypress for keys we don't know return end if self.event_map_adapter[keycode] then return self.event_map_adapter[keycode](ev) end -- take device rotation into account if self.rotation_map[self.device.screen:getRotationMode()][keycode] then keycode = self.rotation_map[self.device.screen:getRotationMode()][keycode] end if keycode == "IntoSS" or keycode == "OutOfSS" or keycode == "Charging" or keycode == "NotCharging" then return keycode end if keycode == "Power" then -- Kobo generates Power keycode only, we need to decide whether it's -- power-on or power-off ourselves. if self.device.screen_saver_mode then if ev.value == EVENT_VALUE_KEY_RELEASE then return "Resume" end else if ev.value == EVENT_VALUE_KEY_PRESS then return "PowerPress" elseif ev.value == EVENT_VALUE_KEY_RELEASE then return "PowerRelease" end end end -- handle modifier keys if self.modifiers[keycode] ~= nil then if ev.value == EVENT_VALUE_KEY_PRESS then self.modifiers[keycode] = true elseif ev.value == EVENT_VALUE_KEY_RELEASE then self.modifiers[keycode] = false end return end local key = Key:new(keycode, self.modifiers) if ev.value == EVENT_VALUE_KEY_PRESS then return Event:new("KeyPress", key) elseif ev.value == EVENT_VALUE_KEY_RELEASE then return Event:new("KeyRelease", key) end end function Input:handleMiscEv(ev) -- should be handled by a misc event protocol plugin end --[[ parse each touch ev from kernel and build up tev. tev will be sent to GestureDetector:feedEvent Events for a single tap motion from Linux kernel (MT protocol B): MT_TRACK_ID: 0 MT_X: 222 MT_Y: 207 SYN REPORT MT_TRACK_ID: -1 SYN REPORT Notice that each line is a single event. From kernel document: For type B devices, the kernel driver should associate a slot with each identified contact, and use that slot to propagate changes for the contact. Creation, replacement and destruction of contacts is achieved by modifying the ABS_MT_TRACKING_ID of the associated slot. A non-negative tracking id is interpreted as a contact, and the value -1 denotes an unused slot. A tracking id not previously present is considered new, and a tracking id no longer present is considered removed. Since only changes are propagated, the full state of each initiated contact has to reside in the receiving end. Upon receiving an MT event, one simply updates the appropriate attribute of the current slot. --]] function Input:handleTouchEv(ev) if ev.type == EV_ABS then if #self.MTSlots == 0 then table.insert(self.MTSlots, self:getMtSlot(self.cur_slot)) end if ev.code == ABS_MT_SLOT then if self.cur_slot ~= ev.value then table.insert(self.MTSlots, self:getMtSlot(ev.value)) end self.cur_slot = ev.value elseif ev.code == ABS_MT_TRACKING_ID then self:setCurrentMtSlot("id", ev.value) elseif ev.code == ABS_MT_POSITION_X then self:setCurrentMtSlot("x", ev.value) elseif ev.code == ABS_MT_POSITION_Y then self:setCurrentMtSlot("y", ev.value) -- code to emulate mt protocol on kobos -- we "confirm" abs_x, abs_y only when pressure ~= 0 elseif ev.code == ABS_X then self:setCurrentMtSlot("abs_x", ev.value) elseif ev.code == ABS_Y then self:setCurrentMtSlot("abs_y", ev.value) elseif ev.code == ABS_PRESSURE then if ev.value ~= 0 then self:setCurrentMtSlot("id", 1) self:confirmAbsxy() else self:cleanAbsxy() self:setCurrentMtSlot("id", -1) end end elseif ev.type == EV_SYN then if ev.code == SYN_REPORT then for _, MTSlot in pairs(self.MTSlots) do self:setMtSlot(MTSlot.slot, "timev", TimeVal:new(ev.time)) end -- feed ev in all slots to state machine local touch_ges = self.gesture_detector:feedEvent(self.MTSlots) self.MTSlots = {} if touch_ges then self:gestureAdjustHook(touch_ges) return Event:new("Gesture", self.gesture_detector:adjustGesCoordinate(touch_ges) ) end end end end function Input:handleTouchEvPhoenix(ev) -- Hack on handleTouchEV for the Kobo Aura -- It seems to be using a custom protocol: -- finger 0 down: -- input_report_abs(elan_touch_data.input, ABS_MT_TRACKING_ID, 0); -- input_report_abs(elan_touch_data.input, ABS_MT_TOUCH_MAJOR, 1); -- input_report_abs(elan_touch_data.input, ABS_MT_WIDTH_MAJOR, 1); -- input_report_abs(elan_touch_data.input, ABS_MT_POSITION_X, x1); -- input_report_abs(elan_touch_data.input, ABS_MT_POSITION_Y, y1); -- input_mt_sync (elan_touch_data.input); -- finger 1 down: -- input_report_abs(elan_touch_data.input, ABS_MT_TRACKING_ID, 1); -- input_report_abs(elan_touch_data.input, ABS_MT_TOUCH_MAJOR, 1); -- input_report_abs(elan_touch_data.input, ABS_MT_WIDTH_MAJOR, 1); -- input_report_abs(elan_touch_data.input, ABS_MT_POSITION_X, x2); -- input_report_abs(elan_touch_data.input, ABS_MT_POSITION_Y, y2); -- input_mt_sync (elan_touch_data.input); -- finger 0 up: -- input_report_abs(elan_touch_data.input, ABS_MT_TRACKING_ID, 0); -- input_report_abs(elan_touch_data.input, ABS_MT_TOUCH_MAJOR, 0); -- input_report_abs(elan_touch_data.input, ABS_MT_WIDTH_MAJOR, 0); -- input_report_abs(elan_touch_data.input, ABS_MT_POSITION_X, last_x); -- input_report_abs(elan_touch_data.input, ABS_MT_POSITION_Y, last_y); -- input_mt_sync (elan_touch_data.input); -- finger 1 up: -- input_report_abs(elan_touch_data.input, ABS_MT_TRACKING_ID, 1); -- input_report_abs(elan_touch_data.input, ABS_MT_TOUCH_MAJOR, 0); -- input_report_abs(elan_touch_data.input, ABS_MT_WIDTH_MAJOR, 0); -- input_report_abs(elan_touch_data.input, ABS_MT_POSITION_X, last_x2); -- input_report_abs(elan_touch_data.input, ABS_MT_POSITION_Y, last_y2); -- input_mt_sync (elan_touch_data.input); if ev.type == EV_ABS then if #self.MTSlots == 0 then table.insert(self.MTSlots, self:getMtSlot(self.cur_slot)) end if ev.code == ABS_MT_TRACKING_ID then if self.cur_slot ~= ev.value then table.insert(self.MTSlots, self:getMtSlot(ev.value)) end self.cur_slot = ev.value self:setCurrentMtSlot("id", ev.value) elseif ev.code == ABS_MT_TOUCH_MAJOR and ev.value == 0 then self:setCurrentMtSlot("id", -1) elseif ev.code == ABS_MT_POSITION_X then self:setCurrentMtSlot("x", ev.value) elseif ev.code == ABS_MT_POSITION_Y then self:setCurrentMtSlot("y", ev.value) end elseif ev.type == EV_SYN then if ev.code == SYN_REPORT then for _, MTSlot in pairs(self.MTSlots) do self:setMtSlot(MTSlot.slot, "timev", TimeVal:new(ev.time)) end -- feed ev in all slots to state machine local touch_ges = self.gesture_detector:feedEvent(self.MTSlots) self.MTSlots = {} if touch_ges then self:gestureAdjustHook(touch_ges) return Event:new("Gesture", self.gesture_detector:adjustGesCoordinate(touch_ges) ) end end end end function Input:handleOasisOrientationEv(ev) local rotation_mode, screen_mode if ev.value == DEVICE_ORIENTATION_PORTRAIT or ev.value == DEVICE_ORIENTATION_PORTRAIT_LEFT or ev.value == DEVICE_ORIENTATION_PORTRAIT_RIGHT then rotation_mode = framebuffer.ORIENTATION_PORTRAIT screen_mode = 'portrait' elseif ev.value == DEVICE_ORIENTATION_LANDSCAPE then rotation_mode = framebuffer.ORIENTATION_LANDSCAPE screen_mode = 'landscape' elseif ev.value == DEVICE_ORIENTATION_PORTRAIT_ROTATED or ev.value == DEVICE_ORIENTATION_PORTRAIT_ROTATED_LEFT or ev.value == DEVICE_ORIENTATION_PORTRAIT_ROTATED_RIGHT then rotation_mode = framebuffer.ORIENTATION_PORTRAIT_ROTATED screen_mode = 'portrait' elseif ev.value == DEVICE_ORIENTATION_LANDSCAPE_ROTATED then rotation_mode = framebuffer.ORIENTATION_LANDSCAPE_ROTATED screen_mode = 'landscape' end local old_rotation_mode = self.device.screen:getRotationMode() local old_screen_mode = self.device.screen:getScreenMode() if rotation_mode ~= old_rotation_mode and screen_mode == old_screen_mode then self.device.screen:setRotationMode(rotation_mode) local UIManager = require("ui/uimanager") UIManager:onRotation() end end -- helpers for touch event data management: function Input:setMtSlot(slot, key, val) if not self.ev_slots[slot] then self.ev_slots[slot] = { slot = slot } end self.ev_slots[slot][key] = val end function Input:setCurrentMtSlot(key, val) self:setMtSlot(self.cur_slot, key, val) end function Input:getMtSlot(slot) return self.ev_slots[slot] end function Input:getCurrentMtSlot() return self:getMtSlot(self.cur_slot) end function Input:confirmAbsxy() self:setCurrentMtSlot("x", self.ev_slots[self.cur_slot]["abs_x"]) self:setCurrentMtSlot("y", self.ev_slots[self.cur_slot]["abs_y"]) end function Input:cleanAbsxy() self:setCurrentMtSlot("abs_x", nil) self:setCurrentMtSlot("abs_y", nil) end function Input:isEvKeyPress(ev) return ev.value == EVENT_VALUE_KEY_PRESS end function Input:isEvKeyRelease(ev) return ev.value == EVENT_VALUE_KEY_RELEASE end -- main event handling: function Input:waitEvent(timeout_us) -- wrapper for input.waitForEvents that will retry for some cases local ok, ev while true do if #self.timer_callbacks > 0 then local wait_deadline = TimeVal:now() + TimeVal:new{ usec = timeout_us } -- we don't block if there is any timer, set wait to 10us while #self.timer_callbacks > 0 do ok, ev = pcall(input.waitForEvent, 100) if ok then break end local tv_now = TimeVal:now() if (not timeout_us or tv_now < wait_deadline) then -- check whether timer is up if tv_now >= self.timer_callbacks[1].deadline then local touch_ges = self.timer_callbacks[1].callback() table.remove(self.timer_callbacks, 1) if touch_ges then -- Do we really need to clear all setTimeout after -- decided a gesture? FIXME self.timer_callbacks = {} self:gestureAdjustHook(touch_ges) return Event:new("Gesture", self.gesture_detector:adjustGesCoordinate(touch_ges) ) end -- EOF if touch_ges end -- EOF if deadline reached else break end -- EOF if not exceed wait timeout end -- while #timer_callbacks > 0 else ok, ev = pcall(input.waitForEvent, timeout_us) end -- EOF if #timer_callbacks > 0 if ok then break end -- ev does contain an error message: if ev == "Waiting for input failed: timeout\n" then -- don't report an error on timeout ev = nil break elseif ev == "application forced to quit" then -- TODO: return an event that can be handled os.exit(0) end logger.warn("got error waiting for events:", ev) if ev ~= "Waiting for input failed: 4\n" then -- we only abort if the error is not EINTR break end end if ok and ev then if DEBUG.is_on and ev then DEBUG:logEv(ev) logger.dbg(string.format( "%s event => type: %d, code: %d(%s), value: %d, time: %d.%d", ev.type == EV_KEY and "key" or "input", ev.type, ev.code, self.event_map[ev.code], ev.value, ev.time.sec, ev.time.usec)) end self:eventAdjustHook(ev) if ev.type == EV_KEY then return self:handleKeyBoardEv(ev) elseif ev.type == EV_ABS and ev.code == ABS_OASIS_ORIENTATION then return self:handleOasisOrientationEv(ev) elseif ev.type == EV_ABS or ev.type == EV_SYN then return self:handleTouchEv(ev) elseif ev.type == EV_MSC then return self:handleMiscEv(ev) else -- some other kind of event that we do not know yet return Event:new("GenericInput", ev) end elseif not ok and ev then return Event:new("InputError", ev) end end return Input
agpl-3.0
ProtectiveTeam/protectiveBot
bot/protectivebot.lua
1
9983
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "admin" }, sudo_users = {110626080,103649648,143723991,111020322,0,tonumber(our_id)},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[protective bot V2 ]], help_text_realm = [[ Realm Commands: !creategroup [name] Create a group !createrealm [name] Create a realm !setname [name] Set realm name !setabout [group_id] [text] Set a group's about text !setrules [grupo_id] [text] Set a group's rules !lock [grupo_id] [setting] Lock a group's setting !unlock [grupo_id] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [grupo_id] Kick all memebers and delete group !kill realm [realm_id] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Get a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups » Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id Return group id or user id !help Get commands list !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules [text] Set [text] as rules !set about [text] Set [text] as about !settings Returns group settings !newlink Create/revoke your group link !link Returns group link !owner Returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] [text] Save [text] as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] Returns user id !log Will return group logs !banlist Will return group ban list » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
GarfieldJiang/UGFWithToLua
Assets/ToLua/ToLua/Lua/socket/url.lua
16
11058
----------------------------------------------------------------------------- -- URI parsing, composition and relative URL resolution -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local base = _G local table = require("table") local socket = require("socket") socket.url = {} local _M = socket.url ----------------------------------------------------------------------------- -- Module version ----------------------------------------------------------------------------- _M._VERSION = "URL 1.0.3" ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- function _M.escape(s) return (string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end)) end ----------------------------------------------------------------------------- -- Protects a path segment, to prevent it from interfering with the -- url parsing. -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end -- these are allowed withing a path segment, along with alphanum -- other characters must be escaped local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- function _M.unescape(s) return (string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end)) end ----------------------------------------------------------------------------- -- Builds a path from a base path and a relative path -- Input -- base_path -- relative_path -- Returns -- corresponding absolute path ----------------------------------------------------------------------------- local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function _M.parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query string url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:%]]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then -- IPv6? parsed.host = string.match(authority, "^%[(.+)%]$") or authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function _M.build(parsed) local ppath = _M.parse_path(parsed.path or "") local url = _M.build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if string.find(authority, ":") then -- IPv6? authority = "[" .. authority .. "]" end if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end ----------------------------------------------------------------------------- -- Builds a absolute URL from a base and a relative URL according to RFC 2396 -- Input -- base_url -- relative_url -- Returns -- corresponding absolute url ----------------------------------------------------------------------------- function _M.absolute(base_url, relative_url) local base_parsed if base.type(base_url) == "table" then base_parsed = base_url base_url = _M.build(base_parsed) else base_parsed = _M.parse(base_url) end local relative_parsed = _M.parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return _M.build(relative_parsed) end end ----------------------------------------------------------------------------- -- Breaks a path into its segments, unescaping the segments -- Input -- path -- Returns -- segment: a table with one entry per segment ----------------------------------------------------------------------------- function _M.parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = _M.unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end ----------------------------------------------------------------------------- -- Builds a path component from its segments, escaping protected characters. -- Input -- parsed: path segments -- unsafe: if true, segments are not protected before path is built -- Returns -- path: corresponding path stringing ----------------------------------------------------------------------------- function _M.build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return _M
mit
dicebox/minetest-france
mods/farming/hoes.lua
4
3457
local S = farming.intllib -- Hoe registration function farming.register_hoe = function(name, def) -- Check for : prefix (register new hoes in your mod's namespace) if name:sub(1,1) ~= ":" then name = ":" .. name end -- Check def table if def.description == nil then def.description = "Hoe" end if def.inventory_image == nil then def.inventory_image = "unknown_item.png" end if def.recipe == nil then def.recipe = { {"air","air",""}, {"","group:stick",""}, {"","group:stick",""} } end if def.max_uses == nil then def.max_uses = 30 end -- Register the tool minetest.register_tool(name, { description = def.description, inventory_image = def.inventory_image, on_use = function(itemstack, user, pointed_thing) return farming.hoe_on_use(itemstack, user, pointed_thing, def.max_uses) end }) -- Register its recipe if def.material == nil then minetest.register_craft({ output = name:sub(2), recipe = def.recipe }) else minetest.register_craft({ output = name:sub(2), recipe = { {def.material, def.material, ""}, {"", "group:stick", ""}, {"", "group:stick", ""} } }) end end -- Turns dirt with group soil=1 into soil function farming.hoe_on_use(itemstack, user, pointed_thing, uses) local pt = pointed_thing -- check if pointing at a node if not pt or pt.type ~= "node" then return end local under = minetest.get_node(pt.under) local upos = pointed_thing.under if minetest.is_protected(upos, user:get_player_name()) then minetest.record_protection_violation(upos, user:get_player_name()) return end local p = {x = pt.under.x, y = pt.under.y + 1, z = pt.under.z} local above = minetest.get_node(p) -- return if any of the nodes is not registered if not minetest.registered_nodes[under.name] or not minetest.registered_nodes[above.name] then return end -- check if the node above the pointed thing is air if above.name ~= "air" then return end -- check if pointing at dirt if minetest.get_item_group(under.name, "soil") ~= 1 then return end -- turn the node into soil, wear out item and play sound minetest.set_node(pt.under, {name = "farming:soil"}) minetest.sound_play("default_dig_crumbly", {pos = pt.under, gain = 0.5}) if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/(uses-1)) end return itemstack end -- Define Hoes farming.register_hoe(":farming:hoe_wood", { description = S("Wooden Hoe"), inventory_image = "farming_tool_woodhoe.png", max_uses = 30, material = "group:wood" }) farming.register_hoe(":farming:hoe_stone", { description = S("Stone Hoe"), inventory_image = "farming_tool_stonehoe.png", max_uses = 90, material = "group:stone" }) farming.register_hoe(":farming:hoe_steel", { description = S("Steel Hoe"), inventory_image = "farming_tool_steelhoe.png", max_uses = 200, material = "default:steel_ingot" }) farming.register_hoe(":farming:hoe_bronze", { description = S("Bronze Hoe"), inventory_image = "farming_tool_bronzehoe.png", max_uses = 220, material = "default:bronze_ingot" }) farming.register_hoe(":farming:hoe_mese", { description = S("Mese Hoe"), inventory_image = "farming_tool_mesehoe.png", max_uses = 350, material = "default:mese_crystal" }) farming.register_hoe(":farming:hoe_diamond", { description = S("Diamond Hoe"), inventory_image = "farming_tool_diamondhoe.png", max_uses = 500, material = "default:diamond" })
gpl-3.0
cshore/luci
protocols/luci-proto-3g/luasrc/model/cbi/admin_network/proto_3g.lua
52
4346
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, apn, service, pincode, username, password, dialnumber local ipv6, maxwait, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty[A-Z]*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end service = section:taboption("general", Value, "service", translate("Service Type")) service:value("", translate("-- Please choose --")) service:value("umts", "UMTS/GPRS") service:value("umts_only", translate("UMTS only")) service:value("gprs_only", translate("GPRS only")) service:value("evdo", "CDMA/EV-DO") apn = section:taboption("general", Value, "apn", translate("APN")) pincode = section:taboption("general", Value, "pincode", translate("PIN")) username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true dialnumber = section:taboption("general", Value, "dialnumber", translate("Dial number")) dialnumber.placeholder = "*99***1#" if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6") ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end maxwait = section:taboption("advanced", Value, "maxwait", translate("Modem init timeout"), translate("Maximum amount of seconds to wait for the modem to become ready")) maxwait.placeholder = "20" maxwait.datatype = "min(1)" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger"
apache-2.0
kracwarlock/dp
test/testDataset.lua
7
1918
require 'chex' local ffi = require 'ffi' require 'gfx.js' dataset = chex.dataset{paths={'../../toyset'}, sampleSize={3,256,226}} print('Saving to test.t7') torch.save('test.t7', dataset) print('Class names', dataset.classes) print('Total images in dataset: ' .. dataset:size()) print('Training size: ' .. dataset:sizeTrain()) print('Testing size: ' .. dataset:sizeTest()) print() for k,v in ipairs(dataset.classes) do print('Images for class: ' .. v .. ' : ' .. dataset:size(k) .. ' == ' .. dataset:size(v)) print('Training size: ' .. dataset:sizeTrain(k)) print('Testing size: ' .. dataset:sizeTest(k)) print('First image path: ' .. ffi.string(dataset.imagePath[dataset.classList[k][1]]:data())) print('Last image path: ' .. ffi.string(dataset.imagePath[dataset.classList[k][#dataset.classList[k]]]:data())) print() end -- now sample from this dataset and print out sizes, also visualize print('Getting 128 training samples') local inputs, labels = dataset:sample(128) print('Size of 128 training samples') print(#inputs) print('Size of 128 training labels') print(#labels) print('Getting 1 training sample') local inputs, labels = dataset:sample() print('Size of 1 training sample') print(#inputs) print('1 training label: ' .. labels) gfx.image(inputs) print('Getting 2 training samples') local inputs, labels = dataset:sample(2) print('Size of 2 training samples') print(#inputs) print('Size of 1 training labels') print(#labels) gfx.image(inputs) print('Getting test samples') local count = 0 for inputs, labels in dataset:test(128) do print(#inputs) print(#labels) count = count + 1 print(count) end -- dataset = chex.dataset{paths={'/home/fatbox/data/imagenet12/cropped_quality100/train'}, sampleSize={3,200,200}} -- dataset = chex.dataset{paths={'/home/fatbox/data/imagenet-fall11/images'}, sampleSize={3,200,200}} -- dataset = chex.dataset({'asdsd'}, {3,200,200})
bsd-3-clause
xuminic/ezthumb
external/iup/srclua5/elem/backgroundbox.lua
2
1075
------------------------------------------------------------------------------ -- BackgroundBox class ------------------------------------------------------------------------------ local ctrl = { nick = "backgroundbox", parent = iup.BOX, subdir = "elem", creation = "I", funcname = "BackgroundBox", callback = { action = "ff", } } function ctrl.createElement(class, param) return iup.BackgroundBox() end ctrl.DrawBegin = iup.DrawBegin ctrl.DrawEnd = iup.DrawEnd ctrl.DrawParentBackground = iup.DrawParentBackground ctrl.DrawLine = iup.DrawLine ctrl.DrawRectangle = iup.DrawRectangle ctrl.DrawArc = iup.DrawArc ctrl.DrawPolygon = iup.DrawPolygon ctrl.DrawText = iup.DrawText ctrl.DrawImage = iup.DrawImage ctrl.DrawSetClipRect = iup.DrawSetClipRect ctrl.DrawResetClip = iup.DrawResetClip ctrl.DrawSelectRect = iup.DrawSelectRect ctrl.DrawFocusRect = iup.DrawFocusRect ctrl.DrawGetSize = iup.DrawGetSize ctrl.DrawGetTextSize = iup.DrawGetTextSize ctrl.DrawGetImageInfo = iup.DrawGetImageInfo iup.RegisterWidget(ctrl) iup.SetClass(ctrl, "iupWidget")
gpl-3.0
s0ph05/awesome
vicious/widgets/mem.lua
15
1850
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Adrian C. <anrxc@sysphere.org> -- * (c) 2009, Lucas de Vries <lucas@glacicle.com> --------------------------------------------------- -- {{{ Grab environment local io = { lines = io.lines } local setmetatable = setmetatable local math = { floor = math.floor } local string = { gmatch = string.gmatch } -- }}} -- Mem: provides RAM and Swap usage statistics -- vicious.widgets.mem local mem = {} -- {{{ Memory widget type local function worker(format) local _mem = { buf = {}, swp = {} } -- Get MEM info for line in io.lines("/proc/meminfo") do for k, v in string.gmatch(line, "([%a]+):[%s]+([%d]+).+") do if k == "MemTotal" then _mem.total = math.floor(v/1024) elseif k == "MemFree" then _mem.buf.f = math.floor(v/1024) elseif k == "Buffers" then _mem.buf.b = math.floor(v/1024) elseif k == "Cached" then _mem.buf.c = math.floor(v/1024) elseif k == "SwapTotal" then _mem.swp.t = math.floor(v/1024) elseif k == "SwapFree" then _mem.swp.f = math.floor(v/1024) end end end -- Calculate memory percentage _mem.free = _mem.buf.f + _mem.buf.b + _mem.buf.c _mem.inuse = _mem.total - _mem.free _mem.bcuse = _mem.total - _mem.buf.f _mem.usep = math.floor(_mem.inuse / _mem.total * 100) -- Calculate swap percentage _mem.swp.inuse = _mem.swp.t - _mem.swp.f _mem.swp.usep = math.floor(_mem.swp.inuse / _mem.swp.t * 100) return {_mem.usep, _mem.inuse, _mem.total, _mem.free, _mem.swp.usep, _mem.swp.inuse, _mem.swp.t, _mem.swp.f, _mem.bcuse } end -- }}} return setmetatable(mem, { __call = function(_, ...) return worker(...) end })
mit
Relintai/Relintais-Enemy-Kooldown-Tracker-WotLK
lib/CallbackHandler-1.0/CallbackHandler-1.0.lua
4
8961
--[[ $Id: CallbackHandler-1.0.lua 895 2009-12-06 16:28:55Z nevcairiel $ ]] local MAJOR, MINOR = "CallbackHandler-1.0", 5 local CallbackHandler = LibStub:NewLibrary(MAJOR, MINOR) if not CallbackHandler then return end -- No upgrade needed local meta = {__index = function(tbl, key) tbl[key] = {} return tbl[key] end} -- Lua APIs local tconcat = table.concat local assert, error, loadstring = assert, error, loadstring local setmetatable, rawset, rawget = setmetatable, rawset, rawget local next, select, pairs, type, tostring = next, select, pairs, type, tostring -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: geterrorhandler local xpcall = xpcall local function errorhandler(err) return geterrorhandler()(err) end local function CreateDispatcher(argCount) local code = [[ local next, xpcall, eh = ... local method, ARGS local function call() method(ARGS) end local function dispatch(handlers, ...) local index index, method = next(handlers) if not method then return end local OLD_ARGS = ARGS ARGS = ... repeat xpcall(call, eh) index, method = next(handlers, index) until not method ARGS = OLD_ARGS end return dispatch ]] local ARGS, OLD_ARGS = {}, {} for i = 1, argCount do ARGS[i], OLD_ARGS[i] = "arg"..i, "old_arg"..i end code = code:gsub("OLD_ARGS", tconcat(OLD_ARGS, ", ")):gsub("ARGS", tconcat(ARGS, ", ")) return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(next, xpcall, errorhandler) end local Dispatchers = setmetatable({}, {__index=function(self, argCount) local dispatcher = CreateDispatcher(argCount) rawset(self, argCount, dispatcher) return dispatcher end}) -------------------------------------------------------------------------- -- CallbackHandler:New -- -- target - target object to embed public APIs in -- RegisterName - name of the callback registration API, default "RegisterCallback" -- UnregisterName - name of the callback unregistration API, default "UnregisterCallback" -- UnregisterAllName - name of the API to unregister all callbacks, default "UnregisterAllCallbacks". false == don't publish this API. function CallbackHandler:New(target, RegisterName, UnregisterName, UnregisterAllName, OnUsed, OnUnused) -- TODO: Remove this after beta has gone out assert(not OnUsed and not OnUnused, "ACE-80: OnUsed/OnUnused are deprecated. Callbacks are now done to registry.OnUsed and registry.OnUnused") RegisterName = RegisterName or "RegisterCallback" UnregisterName = UnregisterName or "UnregisterCallback" if UnregisterAllName==nil then -- false is used to indicate "don't want this method" UnregisterAllName = "UnregisterAllCallbacks" end -- we declare all objects and exported APIs inside this closure to quickly gain access -- to e.g. function names, the "target" parameter, etc -- Create the registry object local events = setmetatable({}, meta) local registry = { recurse=0, events=events } -- registry:Fire() - fires the given event/message into the registry function registry:Fire(eventname, ...) if not rawget(events, eventname) or not next(events[eventname]) then return end local oldrecurse = registry.recurse registry.recurse = oldrecurse + 1 Dispatchers[select('#', ...) + 1](events[eventname], eventname, ...) registry.recurse = oldrecurse if registry.insertQueue and oldrecurse==0 then -- Something in one of our callbacks wanted to register more callbacks; they got queued for eventname,callbacks in pairs(registry.insertQueue) do local first = not rawget(events, eventname) or not next(events[eventname]) -- test for empty before. not test for one member after. that one member may have been overwritten. for self,func in pairs(callbacks) do events[eventname][self] = func -- fire OnUsed callback? if first and registry.OnUsed then registry.OnUsed(registry, target, eventname) first = nil end end end registry.insertQueue = nil end end -- Registration of a callback, handles: -- self["method"], leads to self["method"](self, ...) -- self with function ref, leads to functionref(...) -- "addonId" (instead of self) with function ref, leads to functionref(...) -- all with an optional arg, which, if present, gets passed as first argument (after self if present) target[RegisterName] = function(self, eventname, method, ... --[[actually just a single arg]]) if type(eventname) ~= "string" then error("Usage: "..RegisterName.."(eventname, method[, arg]): 'eventname' - string expected.", 2) end method = method or eventname local first = not rawget(events, eventname) or not next(events[eventname]) -- test for empty before. not test for one member after. that one member may have been overwritten. if type(method) ~= "string" and type(method) ~= "function" then error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): 'methodname' - string or function expected.", 2) end local regfunc if type(method) == "string" then -- self["method"] calling style if type(self) ~= "table" then error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): self was not a table?", 2) elseif self==target then error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): do not use Library:"..RegisterName.."(), use your own 'self'", 2) elseif type(self[method]) ~= "function" then error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): 'methodname' - method '"..tostring(method).."' not found on self.", 2) end if select("#",...)>=1 then -- this is not the same as testing for arg==nil! local arg=select(1,...) regfunc = function(...) self[method](self,arg,...) end else regfunc = function(...) self[method](self,...) end end else -- function ref with self=object or self="addonId" if type(self)~="table" and type(self)~="string" then error("Usage: "..RegisterName.."(self or \"addonId\", eventname, method): 'self or addonId': table or string expected.", 2) end if select("#",...)>=1 then -- this is not the same as testing for arg==nil! local arg=select(1,...) regfunc = function(...) method(arg,...) end else regfunc = method end end if events[eventname][self] or registry.recurse<1 then -- if registry.recurse<1 then -- we're overwriting an existing entry, or not currently recursing. just set it. events[eventname][self] = regfunc -- fire OnUsed callback? if registry.OnUsed and first then registry.OnUsed(registry, target, eventname) end else -- we're currently processing a callback in this registry, so delay the registration of this new entry! -- yes, we're a bit wasteful on garbage, but this is a fringe case, so we're picking low implementation overhead over garbage efficiency registry.insertQueue = registry.insertQueue or setmetatable({},meta) registry.insertQueue[eventname][self] = regfunc end end -- Unregister a callback target[UnregisterName] = function(self, eventname) if not self or self==target then error("Usage: "..UnregisterName.."(eventname): bad 'self'", 2) end if type(eventname) ~= "string" then error("Usage: "..UnregisterName.."(eventname): 'eventname' - string expected.", 2) end if rawget(events, eventname) and events[eventname][self] then events[eventname][self] = nil -- Fire OnUnused callback? if registry.OnUnused and not next(events[eventname]) then registry.OnUnused(registry, target, eventname) end end if registry.insertQueue and rawget(registry.insertQueue, eventname) and registry.insertQueue[eventname][self] then registry.insertQueue[eventname][self] = nil end end -- OPTIONAL: Unregister all callbacks for given selfs/addonIds if UnregisterAllName then target[UnregisterAllName] = function(...) if select("#",...)<1 then error("Usage: "..UnregisterAllName.."([whatFor]): missing 'self' or \"addonId\" to unregister events for.", 2) end if select("#",...)==1 and ...==target then error("Usage: "..UnregisterAllName.."([whatFor]): supply a meaningful 'self' or \"addonId\"", 2) end for i=1,select("#",...) do local self = select(i,...) if registry.insertQueue then for eventname, callbacks in pairs(registry.insertQueue) do if callbacks[self] then callbacks[self] = nil end end end for eventname, callbacks in pairs(events) do if callbacks[self] then callbacks[self] = nil -- Fire OnUnused callback? if registry.OnUnused and not next(callbacks) then registry.OnUnused(registry, target, eventname) end end end end end end return registry end -- CallbackHandler purposefully does NOT do explicit embedding. Nor does it -- try to upgrade old implicit embeds since the system is selfcontained and -- relies on closures to work.
mit
mqmaker/witi-openwrt
package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/email.lua
78
1934
--[[ Luci configuration model for statistics - collectd email plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("E-Mail Plugin Configuration"), translate( "The email plugin creates a unix socket which can be used " .. "to transmit email-statistics to a running collectd daemon. " .. "This plugin is primarily intended to be used in conjunction " .. "with Mail::SpamAssasin::Plugin::Collectd but can be used in " .. "other ways as well." )) -- collectd_email config section s = m:section( NamedSection, "collectd_email", "luci_statistics" ) -- collectd_email.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_email.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile", translate("Socket file") ) socketfile.default = "/var/run/collect-email.sock" socketfile:depends( "enable", 1 ) -- collectd_email.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup", translate("Socket group") ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_email.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) -- collectd_email.maxconns (MaxConns) maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") ) maxconns.default = 5 maxconns.isinteger = true maxconns.rmempty = true maxconns.optional = true maxconns:depends( "enable", 1 ) return m
gpl-2.0
tupperkion/computercraft-programs
newType.lua
1
17200
local function dostring(...) return loadstring(...) end do local _G = getfenv(0) -- foolproof _G variable local rawType = type local rawTostring = tostring local uuid = "" local protectedEnv = {} local rawOs = os local firstSetfenv = setfenv local envMeta = {__index = function(t, i) return _G[i] end, __newindex = function(t, i, j) _G[i] = j end} function setfenv(f, t) local b, r = pcall(getmetatable, t) if (not b) or (type(r) ~= "table") then r = {__metatable = uuid..": Environment"} else r.__metatable = uuid..": Environment" end pcall(setmetatable, t, r) firstSetfenv(f, t) end local rawGetfenv = getfenv local rawSetfenv = setfenv for i = 1, 20 do local hex = "0123456789abcdef" math.randomseed(math.random(1000000000, 9999999999)) local randomNumber = math.random(1, 16) uuid = uuid..hex:sub(randomNumber, randomNumber) end pcall(setmetatable, _G, {__metatable = uuid..": Environment"}) local function scanGlobalVariable(var, noString) if not noString then if type(_G[var]) == "nil" or type(_G[var]) == "boolean" or type(_G[var]) == "number" or type(_G[var]) == "string" then return true end if not scanGlobalVariable(_G[var]) then return false end if var == "setfenv" or var == "getfenv" or var == "os" then -- the obvious return false elseif type(var) == "string" then return scanGlobalVariable(_G[var]) end end if type(var) ~= "string" then if var == rawGetfenv or var == rawSetfenv or var == os then return false else for i, j in pairs(os) do if var == j then return false end end end end if type(var) == "table" then for i, j in pairs(var) do return scanGlobalVariable(i) and scanGlobalVariable(j) and (pcall(getmetatable[i]) and scanGlobalVariable(getmetatable[i]) or true) end end return true end local resetFunctions = {} local globalTable = {} setmetatable(globalTable, { __index = function(t, i) if scanGlobalVariable(protectedEnv[i]) then if type(protectedEnv[i]) == "function" then resetFunctions[#resetFunctions + 1] = protectedEnv[i] return function(...) setfenv(1, _G) local results = {protectedEnv[i](...)} for i, j in pairs(results) do if not scanGlobalVariable(j) then error("Eval and runSafe cannot attempt to access protected variable", 2) end if rawType(j) == "function" then setfenv(j, globalTable) resetFunctions[#resetFunctions + 1] = j end end return(unpack(results)) end else return protectedEnv[i] end end end, __newindex = function(t, i, j) if scanGlobalVariable(j) then protectedEnv[i] = j end end }) local addedVars = {} local function paint(v) if not scanGlobalVariable(v) then return nil end if type(v) == "function" then local result = setmetatable({}, { __metatable = uuid..": Function", __call = function(t, ...) firstSetfenv(1, _G) pcall(firstSetfenv, v, globalTable) local r = {pcall(v, ...)} if not r[1] then error(r[2], 2) end table.remove(r, 1) for i, j in pairs(r) do if not (scanGlobalVariable(i) and scanGlobalVariable(j)) then error("Eval and runSafe cannot attempt to access protected variable") end end return unpack(r) end }) return result elseif rawType(v) == "table" then local result = setmetatable({}, { __metatable = type(getmetatable(v)) == "string" and getmetatable(v) or uuid..": Table", __index = function(t, i) return paint(v[i]) end, __newindex = function() error("Eval and runSafe cannot attempt to modify pre-existing global tables") end }) else return v end end local function secure() addedVars = {} rawGetfenv = getfenv rawSetfenv = setfenv rawOs = os local errorFunction = function() error("Eval and runSafe cannot attempt to modify or retrieve function environments", 2) end --[[ getfenv = errorFunction setfenv = errorFunction os = setmetatable({}, { __metatable = uuid..": Protected", __index = function() error("Eval and runSafe cannot attempt to access os api", 2) end, __newindex = function() error("Eval and runSafe cannot attempt to access os api", 2) end })]] protectedEnv = {} local env = _G local removed = {} for i, j in pairs(env) do if scanGlobalVariable(i) then protectedEnv[i] = paint(_G[i]) else if type(_G[i]) == "function" then protectedEnv[i] = function() error("Eval and runSafe cannot attempt to access protected function", 2) end elseif type(_G[i]) == "table" then protectedEnv[i] = setmetatable({}, { __metatable = uuid..": Protected", __index = function() error("Eval and runSafe cannot attempt to access protected api", 2) end, __newindex = function() error("Eval and runSafe cannot attempt to access protected api", 2) end }) end removed[#removed + 1] = i end end return "Removed global variables '"..table.concat(removed, "' , '").."'" end local function unsecure() --[[getfenv = rawGetfenv setfenv = rawSetfenv os = rawOs]] for i, j in pairs(protectedEnv) do if _G[i] == nil then _G[i] = j end end for i, j in pairs(resetFunctions) do setfenv(j, _G) end resetFunctions = {} end _G.eval = function(x, super) if super then local results = {pcall(setfenv(dostring(x), {}))} if results[1] then table.remove(results, 1) return unpack(results) else error(results[2], 2) end end local status = secure() local f = dostring("return "..x) setfenv(f, globalTable) local results = {pcall(f)} local endStatus = status.." and filtered "..(#resetFunctions).." function calls" if results[1] then table.remove(results, 1) return unpack(results), endStatus else error(results[2], 2) end unsecure() end _G.runSafe = function(x, super) if super then local results = {pcall(setfenv(dostring(x), {}))} if results[1] then table.remove(results, 1) return unpack(results) else error(results[2], 2) end end local status = secure() local f = dostring(x) setfenv(f, globalTable) local results = {pcall(f)} local endStatus = status.." and filtered "..(#resetFunctions).." function calls" if results[1] then table.remove(results, 1) return unpack(results), endStatus else error(results[2], 2) end unsecure() end local constructors = {} _G.getConstructorName = function(x, noError, includeStandard) if rawType(getmetatable(x)) == "string" and getmetatable(x):match("^"..uuid..": .") then if getmetatable(x):sub(#(getmetatable(x):match("^"..uuid..": ."))) == "_This" then if noError then return "Unitialized" end error("Cannot get constructor name of uninitialized variable", 2) elseif getmetatable(x):sub(#(getmetatable(x):match("^"..uuid..": ."))) == "_NoEnv" then error("Constructor environment not set up\nUse 'Variable()' instead of 'Variable.constructor()'", 3) elseif getmetatable(x):sub(#(getmetatable(x):match("^"..uuid..": ."))) == "_NoProto" then error("Cannot call prototype directly from constructor\nCreate new instance of constructor and index value as if it were a prototype", 3) end return getmetatable(x):sub(#(getmetatable(x):match("^"..uuid..": ."))) end if includeStandard then if rawType(x) == "table" then return "Table" elseif rawType(x) == "function" then return "Function" elseif rawType(x) == "thread" then return "Thread" elseif rawType(x) == "string" then return "String" elseif rawType(x) == "number" then return "Number" elseif rawType(x) == "boolean" then return "Boolean" elseif rawType(x) == "userdata" then return "UserData" elseif rawType(x) == "nil" then return "Nil" end end if noError then return "Unknown" else if includeStandard then error("Invalid or corrupt constructor", 2) else if rawType(x) == "table" or rawType(x) == "function" or rawType(x) == "thread" or rawType(x) == "string" or rawType(x) == "number" or rawType(x) == "boolean" or rawType(x) == "userdata" then error("Native values don't have a constructor", 2) elseif rawType(x) == "nil" then error("Nil values don't have a constructor", 2) else error("Invalid or corrupt constructor", 2) end end end end _G.type = function(x) if not pcall(getmetatable, x) then return rawType(x) end if getmetatable(x) == uuid..": _NoEnv" then error("Constructor environment not set up\nUse 'Variable()' instead of 'Variable.constructor()'", 3) elseif getmetatable(x) == uuid..": _NoProto" then error("Cannot call prototype directly from constructor\nCreate new instance of constructor and index value as if it were a prototype", 3) end local result = getConstructorName(x, true) if result == "Unknown" then result = rawType(x) elseif result:match("^Constructor: ") then return "constructor" end return result:lower() end _G.tostring = function(x) local match = type(rawTostring(x)) == "string" and (rawTostring(x):match("0x%x%x%x%x%x%x%x%x") and ": "..(rawTostring(x):match("0x%x%x%x%x%x%x%x%x") or "")) or "" if type(x) ~= "string" and type(x) ~= "number" and type(x) ~= "boolean" and type(x) ~= "nil" then if rawType(x) == "table" and type(x.toString) == "function" then return x.toString() end return "[object "..getConstructorName(x, true, true)..match.."]" end return rawTostring(x) end local function newConstructor(name, constructor, noGlobal) if type(constructor) ~= "function" then error("Expected [object Function], got [object "..getConstructorName(constructor, true, true)"]", 3) end if name:sub(1, 1) == "_" then error("Cannot start constructor name with underscore", 3) elseif name:match("^%d") then error("Cannot start constructor name with digit", 3) elseif name:lower():match("[^%w%d_]") then error("Constructor name can only contain letters, digits and underscores", 3) elseif name:lower() == "unknown" then error("Cannot set constructor name to 'Unknown'", 3) elseif name:lower() == "keyword" then error("Cannot set constructor name to 'Keyword'", 3) elseif name:lower() == "uninitialized" then error("Cannot set constructor name to 'Uninitialized'", 3) elseif name:lower() == "constructor" then error("Cannot set constructor name to 'Constructor'", 3) elseif name:lower() == "prototype" then error("Cannot set constructor name to 'Prototype'", 3) elseif name:lower() == "environment" then error("Cannot set constructor name to 'Environment'", 3) elseif name:lower() == "table" or name:lower() == "function" or name:lower() == "thread" or name:lower() == "string" or name:lower() == "number" or name:lower() == "boolean" or name:lower() == "userdata" or name:lower() == "nil" then error("Cannot use native type as constructor name", 3) end if type(constructors[name]) == "constructor" then error("Constructer name already exists as a constructor", 3) elseif _G[name] then error("Constructer name already exists as a global value", 3) end local env = setmetatable({}, envMeta) env.this = setmetatable({}, { __metatable = uuid..": _NoEnv", __newindex = function() error("Constructor environment not set up\nUse '"..name.."()' instead of '"..name..".constructor()'", 3) end, __index = function() error("Constructor environment not set up\nUse '"..name.."()' instead of '"..name..".constructor()'", 3) end }) setfenv(constructor, env) constructors[name] = setmetatable({ constructor = constructor, prototype = setmetatable({}, { __metatable = uuid..": Prototype", __newindex = function(t, i, j) if type(j) == "function" then local env = setmetatable({}, envMeta) env.this = setmetatable({}, { __metatable = uuid..": _NoProto", __newindex = function() error("Cannot call prototype directly from constructor\nCreate new instance of '"..name.."' and index value as if it were a prototype", 3) end, __index = function() error("Cannot call prototype directly from constructor\nCreate new instance of '"..name.."' and index value as if it were a prototype", 3) end }) setfenv(j, env) end rawset(t, i, j) end }) }, { __metatable = uuid..": Constructor: "..name, __call = function(...) local args = {...} local construct = args[1] table.remove(args, 1) local env = {} local result = setmetatable({}, { __metatable = getmetatable(construct):gsub("^("..uuid..": )Constructor: ", "%1"), __index = function(t, i) if not constructors[getmetatable(t):gsub("^"..uuid..": ", "")] then error("Invalid or corrupt constructor", 2) end local method = constructors[getmetatable(t):gsub("^"..uuid..": ", "")].prototype[i] if not method then return end if type(method) ~= "function" then return method end local vars = setmetatable({}, envMeta) vars.this = setmetatable({}, { __metatable = getmetatable(t), __index = function(a, i) return t[i] end, __newindex = function(a, i, j) t[i] = j end }) setfenv(method, vars) return function(...) local result = {method(...)} vars.this = setmetatable({}, { __metatable = uuid..": _NoProto", __newindex = function() error("Cannot call prototype directly from constructor\nCreate new instance of constructor and index value as if it were a prototype", 3) end, __index = function() error("Cannot call prototype directly from constructor\nCreate new instance of constructor and index value as if it were a prototype", 3) end }) return unpack(result) end end }) env.this = setmetatable({}, { __metatable = uuid..": _This", __newindex = function(t, i, j) result[i] = j end, __index = function(t, i) return result[i] end }) setmetatable(env, envMeta) setfenv(construct.constructor, env) construct.constructor(unpack(args)) return result end }) if not noGlobal then _G[name] = constructors[name] end return constructors[name] end _G.new = setmetatable({}, { __metatable = uuid..": Keyword", __index = function(t, i) return function(x, y) if type(x) == "table" and x[1] then return newConstructor(i, x[1], y) else return newConstructor(i, x, y) end end end, __newindex = function() end }) if protect and protect("protect") then -- MORE security protect("setfenv") protect("getfenv") protect("pcall") protect("eval") protect("runSafe") protect("new") protect("getConstructorName") end end --[[ Notes For best security, it is recommended to load newType after varProtector and before any other programs/apis Main feature: custom variable types - Constructors - Prototypes - "this" keyword modelled after javascript - Custom tostring format (examples: "[object Function: 0x12345678]", "[object Constructor: MyCustomType: 0x12345678]") - Allows for custom tostring functions (tostring(x) = x.toString()) - This can be achieved via properties of custom types, values in a table, properties of a prototype or metatables - Prototypes are recommended as they will give access to the "this" keyword, allowing you to give dynamic results based on the variable Eval/RunSafe: execute string in a sandboxed environment - Prevents access to setfenv, getfenv and the os api (use courotine.yield instead of os.pullEventRaw) - Scans for duplicates, items in tables and items in metatables of tables - Filters ALL function calls and return values, modifying the environment of all called functions (even at lower levels) - Prevents modification of all existing global values - Prevents overriding of values in global tables - Prevents access to any local values - ALLOWS adding global values - ALLOWS unlimited editing of global values that didn't exist before runSafe/eval execution started - ALLOWS overwriting global values within it's own environment, HOWEVER, these changes will NOT be applied to the global environment - ALLOWS access to all global values, other than setfenv, getfenv, os and any indexes of os - NOTE: global values added to it's own environment will not affect the global environment until runtime of string is complete - NOTE: will return all values returned by string, plus a message explaining how many global values were removed immediately, and how many function calls were filtered - NOTE: eval adds a return statement, while runSafe does not (e.g, eval = loadstring("return "..x); runSafe = loadstring(x)) - NOTE: functions will be reset to the global environment if they are called - NOTE: functions and tables may be recognized as a custom type even though they are not - This will only apply to tables/functions while they are being used by eval/runSafe ]]
mit
siktirmirza/seed
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
bigdogmat/wire
lua/wire/timedpairs.lua
17
3271
-- Timedpairs by Grocel. (Rewrite by Divran) -- It allows you to go through long tables, but without game freezing. -- Its like a for-pairs loop. -- -- How to use: -- WireLib.Timedpairs(string unique name, table, number ticks done at once, function tickcallback[, function endcallback, ...]) -- -- tickcallback is called every tick, it ticks for each KeyValue of the table. -- Its arguments are the current key and value. -- Return false in the tickcallback function to break the loop. -- tickcallback(key, value, ...) -- -- endcallback is called after the last tickcallback has been called. -- Its arguments are the same as the last arguments of WireLib.Timedpairs -- endcallback(lastkey, lastvalue, ...) if (!WireLib) then return end local next = next local pairs = pairs local unpack = unpack local pcall = pcall local functions = {} function WireLib.TimedpairsGetTable() return functions end function WireLib.TimedpairsStop(name) functions[name] = nil end local function copy( t ) -- custom table copy function to convert to numerically indexed table local ret = {} for k,v in pairs( t ) do ret[#ret+1] = { key = k, value = v } end return ret end local function Timedpairs() if not next(functions) then return end local toremove = {} for name, data in pairs( functions ) do for i=1,data.step do data.currentindex = data.currentindex + 1 -- increment index counter local lookup = data.lookup or {} if data.currentindex <= #lookup then -- If there are any more values.. local kv = lookup[data.currentindex] or {} -- Get the current key and value local ok, err = xpcall( data.callback, debug.traceback, kv.key, kv.value, unpack(data.args) ) -- DO EET if not ok then -- oh noes WireLib.ErrorNoHalt( "Error in Timedpairs '" .. name .. "': " .. err ) toremove[#toremove+1] = name break elseif err == false then -- They returned false inside the function toremove[#toremove+1] = name break end else -- Out of keys. Entire table looped if data.endcallback then -- If we had any end callback function local kv = lookup[data.currentindex-1] or {} -- get previous key & value local ok, err = xpcall( data.endcallback, debug.traceback, kv.key, kv.value, unpack(data.args) ) if not ok then WireLib.ErrorNoHalt( "Error in Timedpairs '" .. name .. "' (in end function): " .. err ) end end toremove[#toremove+1] = name break end end end for i=1,#toremove do -- Remove all that were flagged for removal functions[toremove[i]] = nil end end if (CLIENT) then hook.Add("PostRenderVGUI", "WireLib_Timedpairs", Timedpairs) // Doesn't get paused in single player. Can be important for vguis. else hook.Add("Think", "WireLib_Timedpairs", Timedpairs) // Servers still uses Think. end function WireLib.Timedpairs(name,tab,step,callback,endcallback,...) functions[name] = { lookup = copy(tab), step = step, currentindex = 0, callback = callback, endcallback = endcallback, args = {...} } end function WireLib.Timedcall(callback,...) // calls the given function like simple timer, but isn't affected by game pausing. local dummytab = {true} WireLib.Timedpairs("Timedcall_"..tostring(dummytab),dummytab,1,function(k, v, ...) callback(...) end,nil,...) end
apache-2.0
bizkut/BudakJahat
Rotations/Priest/Discipline/DisciplineAuraV2.lua
1
94772
local rotationName = "Aura" -------------- --- COLORS --- -------------- local colorGreen = "|cff00FF00" local colorRed = "|cffFF0000" local colorWhite = "|cffFFFFFF" --------------- --- Toggles --- --------------- local function createToggles() -- Cooldown Button CooldownModes = { [1] = {mode = "Auto", value = 1, overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.divineStar}, [2] = {mode = "On", value = 2, overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.divineStar}, [3] = {mode = "Off", value = 3, overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.divineStar} } CreateButton("Cooldown", 1, 0) -- Defensive Button DefensiveModes = { [1] = {mode = "On", value = 1, overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.powerWordBarrier}, [2] = {mode = "Off", value = 2, overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.powerWordBarrier} } CreateButton("Defensive", 2, 0) -- Decurse Button DecurseModes = { [1] = {mode = "On", value = 1, overlay = "Decurse Enabled", tip = "Decurse Enabled", highlight = 1, icon = br.player.spell.purify}, [2] = {mode = "Off", value = 2, overlay = "Decurse Disabled", tip = "Decurse Disabled", highlight = 0, icon = br.player.spell.purify} } CreateButton("Decurse", 3, 0) -- Interrupt Button InterruptModes = { [1] = {mode = "On", value = 1, overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.psychicScream}, [2] = {mode = "Off", value = 2, overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.psychicScream} } CreateButton("Interrupt", 4, 0) end --------------- --- OPTIONS --- --------------- local function createOptions() local optionTable local function utilityOptions() ------------------------- -------- UTILITY -------- ------------------------- section = br.ui:createSection(br.ui.window.profile, "Utility - Version 1.03") -- Pull Spell br.ui:createCheckbox(section, "Pull Spell", "Check this to use SW:P to pull when solo.") -- Auto Buff Fortitude br.ui:createCheckbox(section, "Power Word: Fortitude", "Check to auto buff Fortitude on party.") -- OOC Healing br.ui:createCheckbox(section, "OOC Healing", "|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFout of combat healing|cffFFBB00.", 1) br.ui:createSpinner(section, "OOC Penance", 95, 0, 100, 5, "|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFout of combat penance healing|cffFFBB00.") -- Dispel Magic br.ui:createDropdown(section, "Dispel Magic", {"|cffFFFF00Selected Target", "|cffFFBB00Auto"}, 1, "|ccfFFFFFFTarget to Cast On") -- Mass Dispel br.ui:createDropdown(section, "Mass Dispel", br.dropOptions.Toggle, 1, colorGreen .. "Enables" .. colorWhite .. "/" .. colorRed .. "Disables " .. colorWhite .. " Mass Dispel usage.") --Body and Soul br.ui:createSpinner(section, "Body and Soul", 2, 0, 100, 1, "|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFBody and Soul usage|cffFFBB00.") --Angelic Feather br.ui:createSpinner(section, "Angelic Feather", 2, 0, 100, 1, "|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFAngelic Feather usage|cffFFBB00.") --Fade br.ui:createSpinner(section, "Fade", 95, 0, 100, 1, "|cffFFFFFFHealth Percent to Cast At. Default: 95") --Leap Of Faith br.ui:createSpinner(section, "Leap Of Faith", 20, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Will never use on tank. Default: 20") --Dominant Mind br.ui:createSpinner(section, "Dominant Mind", 5, 0, 10, 1, "|cffFFFFFFMinimum Dominant Mind Targets. Default: 5") --Resurrection br.ui:createCheckbox(section, "Resurrection") br.ui:createDropdownWithout(section, "Resurrection - Target", {"|cff00FF00Target", "|cffFF0000Mouseover", "|cffFFBB00Auto"}, 1, "|cffFFFFFFTarget to cast on") br.ui:createCheckbox(section, "Raid Penance", "|cffFFFFFFCheck this to only use Penance when moving.") br.ui:createSpinner(section, "Temple of Seth", 80, 0, 100, 5, "|cffFFFFFFMinimum Average Health to Heal Seth NPC. Default: 80") br.ui:createSpinnerWithout(section, "Bursting", 1, 1, 10, 1, "", "|cffFFFFFFWhen Bursting stacks are above this amount, Trinkets will be triggered.") br.ui:createCheckbox(section, "Pig Catcher", "Catch the freehold Pig in the ring of booty") br.ui:createSpinner(section, "Tank Heal", 30, 0, 100, 5, "|cffFFFFFFMinimum Health to Heal Non-Tank units. Default: 30") br.ui:checkSectionState(section) -- Toggle Key Options section = br.ui:createSection(br.ui.window.profile, "Toggle Keys") -- Cooldown Key Toggle br.ui:createDropdownWithout(section, "Cooldown Mode", br.dropOptions.Toggle, 6) -- Defensive Key Toggle br.ui:createDropdownWithout(section, "Defensive Mode", br.dropOptions.Toggle, 6) -- Decurse Key Toggle br.ui:createDropdownWithout(section, "Decurse Mode", br.dropOptions.Toggle, 6) -- Interrupt Key Toggle br.ui:createDropdownWithout(section, "Interrupt Mode", br.dropOptions.Toggle, 6) br.ui:checkSectionState(section) end local function essenceOptions() ------------------------- ------ ESSENCE -------- ------------------------- section = br.ui:createSection(br.ui.window.profile, "Essence") --Concentrated Flame br.ui:createDropdown(section, "Concentrated Flame", { "DPS", "Heal", "Hybrid"}, 1) br.ui:createSpinnerWithout(section, "Concentrated Flame Heal", 70, 10, 90, 5) --Memory of Lucid Dreams br.ui:createCheckbox(section, "Lucid Dreams") -- Ever-Rising Tide br.ui:createDropdown(section, "Ever-Rising Tide", {"Always", "Pair with CDs", "Based on Health"}, 1, "When to use this Essence") br.ui:createSpinner(section, "Ever-Rising Tide - Mana", 30, 0, 100, 5, "Min mana to use") br.ui:createSpinner(section, "Ever-Rising Tide - Health", 30, 0, 100, 5, "Health threshold to use") br.ui:createCheckbox(section, "Well of Existence") br.ui:createSpinner(section, "Life-Binder's Invocation", 85, 1, 100, 5, "Health threshold to use") br.ui:createSpinnerWithout(section, "Life-Binder's Invocation Targets", 5, 1, 40, 1, "Number of targets to use") br.ui:checkSectionState(section) end local function healingOptions() ------------------------- ---- SINGLE TARGET ------ ------------------------- section = br.ui:createSection(br.ui.window.profile, "Single Target Healing") --Atonement br.ui:createCheckbox(section, "Obey Atonement Limits", "|cffFFFFFFIf checked will obey max atonements when you have rapture buff") br.ui:createSpinnerWithout(section, "Party Atonement HP", 95, 0, 100, 1, "|cffFFFFFFApply Atonement using Power Word: Shield and Power Word: Radiance. Health Percent to Cast At. Default: 95") br.ui:createSpinnerWithout( section, "Tank Atonement HP", 95, 0, 100, 1, "|cffFFFFFFApply Atonement to Tank using Power Word: Shield and Power Word: Radiance. Health Percent to Cast At. Default: 95" ) br.ui:createSpinnerWithout(section, "Max Atonements", 3, 1, 40, 1, "|cffFFFFFFMax Atonements to Keep Up At Once. Default: 3") br.ui:createSpinner(section, "Depths of the Shadows", 5, 0, 40, 1, "Number of stacks to use Shadow Mend instead of Shield") br.ui:createDropdown(section, "Atonement Key", br.dropOptions.Toggle, 6, "|cffFFFFFFSet key to press to spam atonements on everyone.") --Alternate Heal & Damage br.ui:createSpinner(section, "Alternate Heal & Damage", 1, 1, 5, 1, "|cffFFFFFFAlternate Heal & Damage. How many Atonement applied before back to doing damage. Default: 1") --Power Word: Shield -- br.ui:createSpinner(section, "Power Word: Shield", 99, 0, 100, 1, "","Health Percent to Cast At. Default: 99") -- br.ui:createDropdownWithout(section, "PW:S Target", {"|cffFFFFFFPlayer","|cffFFFFFFTarget", "|cffFFFFFFMouseover", "|cffFFFFFFTank", "|cffFFFFFFHealer", "|cffFFFFFFHealer/Tank", "|cffFFFFFFAny"}, 7, "|cffFFFFFFcast Power Word: Shield Target") --Shadow Mend br.ui:createSpinner(section, "Shadow Mend", 65, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 65") --Penance Heal br.ui:createSpinner(section, "Penance Heal", 60, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 60") --Debuff Shadow Mend/Penance Heal br.ui:createCheckbox(section, "Debuff Helper", "|cffFFFFFFHelp mitigate a few known debuff") --Pain Suppression Tank br.ui:createSpinner(section, "Pain Suppression Tank", 30, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 30") br.ui:createSpinner(section, "Revitalizing Voodoo Totem", 75, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 75") br.ui:createSpinner(section, "Inoculating Extract", 75, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 75") br.ui:createSpinner(section, "Ward of Envelopment", 75, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 75") br.ui:checkSectionState(section) ------------------------- ------ AOE HEALING ------ ------------------------- section = br.ui:createSection(br.ui.window.profile, "AOE Healing") --Power Word: Radiance br.ui:createSpinner(section, "Power Word: Radiance", 70, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 70") br.ui:createSpinnerWithout(section, "PWR Targets", 3, 0, 40, 1, "|cffFFFFFFMinimum PWR Targets. Default: 3") --Shadow Covenant br.ui:createSpinner(section, "Shadow Covenant", 85, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 85") br.ui:createSpinnerWithout(section, "Shadow Covenant Targets", 4, 0, 40, 1, "|cffFFFFFFMinimum Shadow Covenant Targets. Default: 4") --Halo br.ui:createSpinner(section, "Halo", 90, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 90") br.ui:createSpinnerWithout(section, "Halo Targets", 5, 0, 40, 1, "|cffFFFFFFMinimum Halo Targets. Default: 5") -- Divine Star br.ui:createSpinner(section, "Divine Star Healing", 95, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 95") br.ui:createSpinnerWithout(section, "DS Healing Targets", 3, 0, 40, 1, "|cffFFFFFFMinimum DS Targets. Default: 3 (Will include enemies in total)") br.ui:checkSectionState(section) end local function damageOptions() ------------------------- ----- DAMAGE OPTIONS ---- ------------------------- section = br.ui:createSection(br.ui.window.profile, "Damage") br.ui:createSpinnerWithout(section, "Damage Mana Threshold") --Shadow Word: Pain/Purge The Wicked br.ui:createCheckbox(section, "Shadow Word: Pain/Purge The Wicked") br.ui:createSpinner(section, "SW:P/PtW Targets", 3, 0, 20, 1, "|cffFFFFFFMaximum SW:P/PtW Targets. Default: 3") --Schism br.ui:createCheckbox(section, "Schism") --Penance br.ui:createCheckbox(section, "Penance") --Power Word: Solace br.ui:createCheckbox(section, "Power Word: Solace") --Smite br.ui:createCheckbox(section, "Smite") --Halo Damage br.ui:createSpinner(section, "Halo Damage", 3, 0, 10, 1, "|cffFFFFFFMinimum Halo Damage Targets. Default: 3") --Mindbender br.ui:createSpinner(section, "Mindbender", 80, 0, 100, 5, "|cffFFFFFFMana Percent to Cast At. Default: 80") --Shadowfiend br.ui:createSpinner(section, "Shadowfiend", 80, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 80") br.ui:checkSectionState(section) end local function cooldownOptions() ------------------------- ------- COOLDOWNS ------- ------------------------- section = br.ui:createSection(br.ui.window.profile, "Cooldowns") --Disable CD during Speed: Slow on Chromatic Anomaly br.ui:createCheckbox(section, "Disable CD during Speed: Slow", "|cffFFFFFFDisable CD during Speed: Slow debuff on Chromatic Anomaly") --High Botanist Tel'arn Parasitic Fetter dispel helper. Dispel 8 yards from allies br.ui:createCheckbox(section, "Parasitic Fetter Dispel Helper", "|cffFFFFFFHigh Botanist Tel'arn Parasitic Fetter dispel helper") --Pre Pot br.ui:createSpinner( section, "Pre-Pot Timer", 3, 1, 10, 1, "|cffFFFFFFSet to desired time for Pre-Pot using Battle Potion of Intellect (DBM Required). Second: Min: 1 / Max: 10 / Interval: 1. Default: 3" ) --Pre-pull Opener br.ui:createSpinner( section, "Pre-pull Opener", 12, 1, 15, 1, "|cffFFFFFFSet to desired time for Pre-pull Atonement blanket (DBM Required). Second: Min: 1 / Max: 15 / Interval: 1. Default: 12" ) br.ui:createSpinner(section, "Azshara's Font Prepull", 6, 0, 10, 1, "Pre pull timer to start channeling Font") --Int Pot br.ui:createSpinner(section, "Int Pot", 50, 0, 100, 5, "|cffFFFFFFUse Battle Potion of Intellect. Default: 50") br.ui:createSpinnerWithout(section, "Pro Pot Targets", 3, 0, 40, 1, "|cffFFFFFFMinimum Prolonged Pot Targets. Default: 3") --Mana Potion br.ui:createSpinner(section, "Mana Potion", 30, 0, 100, 5, "|cffFFFFFFMana Percent to use Ancient Mana Potion. Default: 30") --Trinkets br.ui:createSpinner(section, "Azshara's Font", 40, 0, 100, 5, "Lowest Unit Health to use Font") br.ui:createSpinner(section, "Trinket 1", 70, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Min Trinket 1 Targets", 3, 1, 40, 1, "", "Minimum Trinket 1 Targets(This includes you)", true) br.ui:createDropdownWithout(section, "Trinket 1 Mode", {"|cffFFFFFFNormal", "|cffFFFFFFTarget", "|cffFFFFFFGround"}, 1, "", "") br.ui:createSpinner(section, "Trinket 2", 70, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Min Trinket 2 Targets", 3, 1, 40, 1, "", "Minimum Trinket 2 Targets(This includes you)", true) br.ui:createDropdownWithout(section, "Trinket 2 Mode", {"|cffFFFFFFNormal", "|cffFFFFFFTarget", "|cffFFFFFFGround"}, 1, "", "") --Touch of the Void if hasEquiped(128318) then br.ui:createCheckbox(section, "Touch of the Void") end --Rapture when get Innervate br.ui:createCheckbox(section, "Rapture when get Innervate", "|cffFFFFFFCast Rapture and PWS when get Innervate/Symbol of Hope. Default: Unchecked") --Rapture br.ui:createSpinner(section, "Rapture", 60, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 60") br.ui:createSpinner(section, "Rapture (Tank Only)", 60, 0, 100, 5, "|cffFFFFFFTank Health Percent to Cast At. Default: 60") br.ui:createSpinnerWithout(section, "Rapture Targets", 3, 0, 40, 1, "|cffFFFFFFMinimum Rapture Targets. Default: 3") --Power Word: Barrier/Luminous Barrier br.ui:createSpinner(section, "PW:B/LB", 50, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 50") br.ui:createSpinnerWithout(section, "PW:B/LB Targets", 3, 0, 40, 1, "|cffFFFFFFMinimum PWB Targets. Default: 3") br.ui:createCheckbox(section, "PW:B/LB on Melee", "Only cast on Melee") br.ui:createDropdown(section, "PW:B/LB Key", br.dropOptions.Toggle, 6, colorGreen .. "Enables" .. colorWhite .. "/" .. colorRed .. "Disables " .. colorWhite .. " PW:B/LB manual usage.") --Evangelism br.ui:createDropdown(section, "Evangelism Key", br.dropOptions.Toggle, 6, colorGreen .. "Enables" .. colorWhite .. "/" .. colorRed .. "Disables " .. colorWhite .. " Evangelism manual usage.") br.ui:createSpinner(section, "Evangelism", 70, 0, 100, 1, "|cffFFFFFFHealth Percent to Cast At. Default: 70") br.ui:createSpinnerWithout(section, "Evangelism Targets", 3, 0, 40, 1, "|cffFFFFFFTarget count to Cast At. Default: 3") br.ui:createSpinnerWithout(section, "Atonement for Evangelism", 3, 0, 40, 1, "|cffFFFFFFMinimum Atonement count to Cast At. Default: 3") br.ui:checkSectionState(section) end local function defenseOptions() ------------------------- ------- DEFENSIVE ------- ------------------------- section = br.ui:createSection(br.ui.window.profile, "Defensive") -- Desperate Prayer br.ui:createSpinner(section, "Desperate Prayer", 40, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 40") -- Healthstone br.ui:createSpinner(section, "Pot/Stoned", 35, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 35") -- Heirloom Neck br.ui:createSpinner(section, "Heirloom Neck", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.. Default: 60") -- Gift of The Naaru if br.player.race == "Draenei" then br.ui:createSpinner(section, "Gift of the Naaru", 50, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At. Default: 50") end br.ui:checkSectionState(section) -- Interrupt Options section = br.ui:createSection(br.ui.window.profile, "Interrupts") -- Shining Force - Int br.ui:createCheckbox(section, "Shining Force - Int") -- Psychic Scream - Int br.ui:createCheckbox(section, "Psychic Scream - Int") -- Quaking Palm - Int br.ui:createCheckbox(section, "Quaking Palm - Int") -- Interrupt Percentage br.ui:createSpinner(section, "Interrupt At", 0, 0, 95, 5, "|cffFFFFFFCast Percent to Cast At. Default: 0") br.ui:checkSectionState(section) end optionTable = { { [1] = "Utility", [2] = utilityOptions }, { [1] = "Essence", [2] = essenceOptions }, { [1] = "Healing", [2] = healingOptions }, { [1] = "Damage", [2] = damageOptions }, { [1] = "Cooldowns", [2] = cooldownOptions }, { [1] = "Defensive", [2] = defenseOptions } } return optionTable end ---------------- --- ROTATION --- ---------------- local function runRotation() if br.timer:useTimer("debugDiscipline", 0.1) then --Print("Running: "..rotationName) -------------- --- Locals --- -------------- local artifact = br.player.artifact local buff = br.player.buff local cast = br.player.cast local combatTime = getCombatTime() local cd = br.player.cd local charges = br.player.charges local debuff = br.player.debuff local enemies = br.player.enemies local essence = br.player.essence local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), GetUnitSpeed("player") > 0 local friends = friends or {} local gcd = br.player.gcd local gcdMax = br.player.gcdMax local healPot = getHealthPot() local inCombat = br.player.inCombat local inInstance = br.player.instance == "party" local inRaid = br.player.instance == "raid" local lastSpell = lastSpellCast local level = br.player.level local lootDelay = getOptionValue("LootDelay") local mana = getMana("player") local mode = br.player.ui.mode local perk = br.player.perk local php = br.player.health local power, powmax, powgen = br.player.power.mana.amount(), br.player.power.mana.max(), br.player.power.mana.regen() local pullTimer = br.DBM:getPulltimer() local race = br.player.race local racial = br.player.getRacial() local solo = #br.friend == 1 local spell = br.player.spell local tanks = getTanksTable() local talent = br.player.talent local ttd = getTTD local traits = br.player.traits local ttm = br.player.power.mana.ttm() local units = br.player.units local lowest = {} --Lowest Unit local schismCount = debuff.schism.count() units.get(5) units.get(30) units.get(40) enemies.get(24) enemies.get(30) enemies.get(40) friends.yards40 = getAllies("player", 40) local atonementCount = 0 local maxAtonementCount = 0 --local noAtone = {} for i = 1, #br.friend do local atonementRemain = getBuffRemain(br.friend[i].unit, spell.buffs.atonement, "player") or 0 -- 194384 if atonementRemain > 0 then if (br.friend[i].role ~= "TANK" or UnitGroupRolesAssigned(br.friend[i].unit) ~= "TANK") then maxAtonementCount = maxAtonementCount + 1 atonementCount = atonementCount + 1 else atonementCount = atonementCount + 1 end -- else -- if getBuffRemain(br.friend[i].unit,spell.buffs.powerWordShield,"player") < 1 and getDistance(br.friend[i].unit) < 40 and br.friend[i].hp ~= 250 then -- table.insert(noAtone,br.friend[i].unit) -- end end end if not healCount then healCount = 0 end local freeMana = buff.innervate.exists() or buff.symbolOfHope.exists() local freeCast = freeMana or mana > 90 local epTrinket = hasEquiped(140805) and getBuffRemain("player", 225766) > 1 local norganBuff = not isMoving("player") or UnitBuffID("player", 236373) -- Norgannon's Foresight buff local penanceTarget if leftCombat == nil then leftCombat = GetTime() end if profileStop == nil then profileStop = false end local current local function currTargets() current = 0 for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if debuff.purgeTheWicked.exists(thisUnit) or debuff.shadowWordPain.exists(thisUnit) then current = current + 1 end end return current end local DSUnits = 0 if talent.divineStar then DSUnits = (getEnemiesInRect(5, 24) + getUnitsInRect(5, 24, false, getOptionValue("Divine Star Healing"))) end local DSAtone = 0 if talent.divineStar then local DSTable = select(2, getUnitsInRect(5, 24, false, getOptionValue("Divine Star Healing"))) if #DSTable ~= 0 then for i = 1, #DSTable do --print(DSTable[i].unit) local atonementRemain = getBuffRemain(DSTable[i].unit, spell.buffs.atonement, "player") if atonementRemain > 0 then DSAtone = DSAtone + 1 end end end end if inInstance and select(3, GetInstanceInfo()) == 8 then for i = 1, #tanks do local ourtank = tanks[i].unit local Burststack = getDebuffStacks(ourtank, 240443) if Burststack >= getOptionValue("Bursting") then burst = true break else burst = false end end end --local lowest = {} lowest.unit = "player" lowest.hp = 100 for i = 1, #br.friend do if isChecked("Tank Heal") then if (br.friend[i].role == "TANK" or UnitGroupRolesAssigned(br.friend[i].unit) == "TANK") and (lowest.unit == "player" and lowest.hp > getOptionValue("Tank Heal")) then lowest = br.friend[i] end if ((br.friend[i].role == "TANK" or UnitGroupRolesAssigned(br.friend[i].unit) == "TANK") or br.friend[i].unit == "player" or br.friend[i].hp <= getOptionValue("Tank Heal")) then if br.friend[i].hp < lowest.hp then lowest = br.friend[i] end end elseif not isChecked("Tank Heal") then if br.friend[i].hp < lowest.hp then lowest = br.friend[i] end end end local penanceCheck = isMoving("player") or not isChecked("Raid Penance") or (buff.powerOfTheDarkSide.exists() and inRaid) local dpsCheck = mana >= getOptionValue("Damage Mana Threshold") or (mana <= getOptionValue("Damage Mana Threshold") and atonementCount >= 1) -------------------- --- Action Lists --- -------------------- -- Action List - Interrupts local function actionList_Interrupts() if useInterrupts() then for i = 1, #enemies.yards40 do thisUnit = enemies.yards40[i] if canInterrupt(thisUnit, getOptionValue("Interrupt At")) then -- Shining Force - Int if isChecked("Shining Force - Int") and getDistance(thisUnit) < 40 then if cast.shiningForce() then br.addonDebug("Casting Shining Force") return true end end -- Psychic Scream - Int if isChecked("Psychic Scream - Int") and getDistance(thisUnit) < 8 then if cast.psychicScream() then br.addonDebug("Casting Psychic Scream") return true end end -- Quaking Palm if isChecked("Quaking Palm - Int") and getDistance(thisUnit) < 5 then if cast.quakingPalm(thisUnit) then br.addonDebug("Casting Quaking Palm") return true end end end end end -- End useInterrupts check end -- End Action List - Interrupts local function actionList_Defensive() if useDefensive() then -- Pot/Stoned if isChecked("Pot/Stoned") and php <= getOptionValue("Pot/Stoned") and inCombat and (hasHealthPot() or hasItem(5512) or hasItem(166799)) then if canUseItem(5512) then br.addonDebug("Using Healthstone") useItem(5512) elseif canUseItem(healPot) then br.addonDebug("Using Health Pot") useItem(healPot) elseif hasItem(166799) and canUseItem(166799) then br.addonDebug("Using Emerald of Vigor") useItem(166799) end end -- Heirloom Neck if isChecked("Heirloom Neck") and php <= getOptionValue("Heirloom Neck") then if hasEquiped(122668) then if GetItemCooldown(122668) == 0 then useItem(122668) br.addonDebug("Using Heirloom Neck") end end end -- Gift of the Naaru if isChecked("Gift of the Naaru") and php <= getOptionValue("Gift of the Naaru") and php > 0 and br.player.race == "Draenei" then if cast.giftOfTheNaaru() then br.addonDebug("Casting Gift of Naaru") return true end end if isChecked("Desperate Prayer") and php <= getOptionValue("Desperate Prayer") then if cast.desperatePrayer() then br.addonDebug("Casting Desperate Prayer") return true end end --Leap Of Faith if isChecked("Leap Of Faith") and inCombat then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Leap Of Faith") and not GetUnitIsUnit(br.friend[i].unit, "player") and UnitGroupRolesAssigned(br.friend[i].unit) ~= "TANK" then if cast.leapOfFaith(br.friend[i].unit) then br.addonDebug("Casting Leap of Faith") return true end end end end end -- End Defensive Toggle end -- End Action List - Defensive ----------------- --- COOLDOWNS --- ----------------- local function actionList_Cooldowns() if useCDs() then if hasItem(166801) and canUseItem(166801) then br.addonDebug("Using Sapphire of Brilliance") useItem(166801) end if isChecked("Disable CD during Speed: Slow") and UnitDebuffID("player", 207011) then return true --Speed: Slow debuff during the Chromatic Anomaly encounter else -- Pain Suppression if isChecked("Pain Suppression Tank") and inCombat and useCDs then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Pain Suppression Tank") and UnitGroupRolesAssigned(br.friend[i].unit) == "TANK" then if cast.painSuppression(br.friend[i].unit) then br.addonDebug("Casting Pain Suppression") return true end end end end if isChecked("PW:B/LB") then if isChecked("PW:B/LB on Melee") then -- get melee players for i = 1, #tanks do -- get the tank's target local tankTarget = UnitTarget(tanks[i].unit) if tankTarget ~= nil and getDistance(tankTarget) <= 40 then -- get players in melee range of tank's target local meleeFriends = getAllies(tankTarget, 5) -- get the best ground circle to encompass the most of them local loc = nil local meleeHurt = {} for j = 1, #meleeFriends do if meleeFriends[j].hp < getValue("PW:B/LB") then tinsert(meleeHurt, meleeFriends[j]) end end if #meleeHurt >= getValue("PW:B/LB Targets") then loc = getBestGroundCircleLocation(meleeHurt, getValue("PW:B/LB Targets"), 6, 8) end if loc ~= nil then if talent.luminousBarrier then if castGroundAtLocation(loc, spell.luminousBarrier) then br.addonDebug("Casting Luminous Barrier") return true end else if castGroundAtLocation(loc, spell.powerWordBarrier) then br.addonDebug("Casting Power Word Barrier") return true end end end end end else if talent.luminousBarrier then if castWiseAoEHeal(br.friend, spell.luminousBarrier, 10, getValue("PW:B/LB"), getValue("PW:B/LB Targets"), 6, true, true) then br.addonDebug("Casting Luminous Barrier") return true end else if castWiseAoEHeal(br.friend, spell.powerWordBarrier, 10, getValue("PW:B/LB"), getValue("PW:B/LB Targets"), 6, true, true) then br.addonDebug("Casting Power Word Barrier") return true end end end end if isChecked("Life-Binder's Invocation") and essence.lifeBindersInvocation.active and cd.lifeBindersInvocation.remain() <= gcd and getLowAllies(getOptionValue("Life-Binder's Invocation")) >= getOptionValue("Life-Binder's Invocation Targets") then if cast.lifeBindersInvocation() then br.addonDebug("Casting Life-Binder's Invocation") return true end end if isChecked("Ever-Rising Tide") and essence.overchargeMana.active and cd.overchargeMana.remain() <= gcd and getOptionValue("Ever-Rising Tide - Mana") <= mana then if getOptionValue("Ever-Rising Tide") == 1 then if cast.overchargeMana() then br.addonDebug("Casting Ever-Rising Tide") return true end end if getOptionValue("Ever-Rising Tide") == 2 then if buff.rapture.exists() or cd.evangelism.remain() >= 80 or burst == true then if cast.overchargeMana() then br.addonDebug("Casting Ever-Rising Tide") return true end end end if getOptionValue("Ever-Rising Tide") == 3 then if lowest.hp < getOptionValue("Ever Rising Tide - Health") or burst == true then if cast.overchargeMana() then br.addonDebug("Casting Ever-Rising Tide") return true end end end end -- Rapture when getting Innervate/Symbol if isChecked("Rapture when get Innervate") and freeMana then if cast.rapture() then br.addonDebug("Casting Rapture") return true end end if isChecked("Rapture (Tank Only)") then for i = 1, #br.friend do if (br.friend[i].role == "TANK" or UnitGroupRolesAssigned(br.friend[i].unit) == "TANK") and br.friend[i].hp <= getValue("Rapture (Tank Only)") then if cast.rapture() then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Rapture") return true end end end end end --Rapture if isChecked("Rapture") then if getLowAllies(getValue("Rapture")) >= getValue("Rapture Targets") then if cast.rapture() then br.addonDebug("Casting Rapture") return true end end end -- Mana Potion if isChecked("Mana Potion") and mana <= getValue("Mana Potion") then if hasItem(152495) then useItem(152495) br.addonDebug("Using Mana Potion") return true end end --Racials --blood_fury --arcane_torrent --berserking if (race == "Troll" or race == "Orc" or race == "MagharOrc" or race == "DarkIronDwarf" or race == "LightforgedDraenei") or (mana >= 30 and race == "BloodElf") then if race == "LightforgedDraenei" then if cast.racial("target", "ground") then br.addonDebug("Casting Racial") return true end else if cast.racial("player") then br.addonDebug("Casting Racial") return true end end end --potion,name=Int_power if isChecked("Int Pot") and canUseItem(163222) and not solo then if getLowAllies(getValue("Int Pot")) >= getValue("Int Pot Targets") then useItem(163222) br.addonDebug("Using Int Pot") end end --Touch of the Void if isChecked("Touch of the Void") and getDistance("target") < 5 then if hasEquiped(128318) then if GetItemCooldown(128318) == 0 then useItem(128318) br.addonDebug("Using Touch of Void") end end end -- Trinkets if isChecked("Revitalizing Voodoo Totem") and hasEquiped(158320) and lowest.hp < getValue("Revitalizing Voodoo Totem") then if GetItemCooldown(158320) <= gcdMax then UseItemByName(158320, lowest.unit) br.addonDebug("Using Revitalizing Voodoo Totem") end end if isChecked("Inoculating Extract") and hasEquiped(160649) and lowest.hp < getValue("Inoculating Extract") then if GetItemCooldown(160649) <= gcdMax then UseItemByName(160649, lowest.unit) br.addonDebug("Using Inoculating Extract") end end if isChecked("Ward of Envelopment") and hasEquiped(165569) and GetItemCooldown(165569) <= gcdMax then -- get melee players for i = 1, #tanks do -- get the tank's target local tankTarget = UnitTarget(tanks[i].unit) if tankTarget ~= nil then -- get players in melee range of tank's target local meleeFriends = getAllies(tankTarget, 5) -- get the best ground circle to encompass the most of them local loc = nil if #meleeFriends >= 8 then loc = getBestGroundCircleLocation(meleeFriends, 4, 6, 10) else local meleeHurt = {} for j = 1, #meleeFriends do if meleeFriends[j].hp < 75 then tinsert(meleeHurt, meleeFriends[j]) end end if #meleeHurt >= 2 then loc = getBestGroundCircleLocation(meleeHurt, 2, 6, 10) end end if loc ~= nil then useItem(165569) local px, py, pz = ObjectPosition("player") loc.z = select(3, TraceLine(loc.x, loc.y, loc.z + 5, loc.x, loc.y, loc.z - 5, 0x110)) -- Raytrace correct z, Terrain and WMO hit if loc.z ~= nil and TraceLine(px, py, pz + 2, loc.x, loc.y, loc.z + 1, 0x100010) == nil and TraceLine(loc.x, loc.y, loc.z + 4, loc.x, loc.y, loc.z, 0x1) == nil then -- Check z and LoS, ignore terrain and m2 collisions ClickPosition(loc.x, loc.y, loc.z) br.addonDebug("Using Ward of Envelopment") return end end end end end --Pillar of the Drowned Cabal if hasEquiped(167863) and canUseItem(16) then if not UnitBuffID(lowest.unit, 295411) and lowest.hp < 75 then UseItemByName(167863, lowest.unit) br.addonDebug("Using Pillar of Drowned Cabal") end end if isChecked("Trinket 1") and canTrinket(13) and not hasEquiped(165569, 13) and not hasEquiped(160649, 13) and not hasEquiped(158320, 13) then if hasEquiped(158368, 13) and mana <= 90 then useItem(13) br.addonDebug("Using Fangs of Intertwined Essence") return true elseif getOptionValue("Trinket 1 Mode") == 1 then if getLowAllies(getValue("Trinket 1")) >= getValue("Min Trinket 1 Targets") or burst == true then useItem(13) br.addonDebug("Using Trinket 1") return true end elseif getOptionValue("Trinket 1 Mode") == 2 then if lowest.hp <= getValue("Trinket 1") or (burst == true and lowest.hp ~= 250) then UseItemByName(GetInventoryItemID("player", 13), lowest.unit) br.addonDebug("Using Trinket 1 (Target)") return true end elseif getOptionValue("Trinket 1 Mode") == 3 and #tanks > 0 then for i = 1, #tanks do -- get the tank's target local tankTarget = UnitTarget(tanks[i].unit) if tankTarget ~= nil then -- get players in melee range of tank's target local meleeFriends = getAllies(tankTarget, 5) -- get the best ground circle to encompass the most of them local loc = nil if #meleeFriends < 12 then loc = getBestGroundCircleLocation(meleeFriends, 4, 6, 10) else local meleeHurt = {} for j = 1, #meleeFriends do if meleeFriends[j].hp < getValue("Trinket 1") then tinsert(meleeHurt, meleeFriends[j]) end end if #meleeHurt >= getValue("Min Trinket 1 Targets") or burst == true then loc = getBestGroundCircleLocation(meleeHurt, 2, 6, 10) end end if loc ~= nil then useItem(13) br.addonDebug("Using Trinket 1 (Ground)") local px, py, pz = ObjectPosition("player") loc.z = select(3, TraceLine(loc.x, loc.y, loc.z + 5, loc.x, loc.y, loc.z - 5, 0x110)) -- Raytrace correct z, Terrain and WMO hit if loc.z ~= nil and TraceLine(px, py, pz + 2, loc.x, loc.y, loc.z + 1, 0x100010) == nil and TraceLine(loc.x, loc.y, loc.z + 4, loc.x, loc.y, loc.z, 0x1) == nil then -- Check z and LoS, ignore terrain and m2 collisions ClickPosition(loc.x, loc.y, loc.z) return true end end end end end end if isChecked("Trinket 2") and canTrinket(14) and not hasEquiped(165569, 14) and not hasEquiped(160649, 14) and not hasEquiped(158320, 14) then if hasEquiped(158368, 14) and mana <= 90 then useItem(14) br.addonDebug("Using Fangs of Intertwined Essence") return true elseif getOptionValue("Trinket 2 Mode") == 1 then if getLowAllies(getValue("Trinket 2")) >= getValue("Min Trinket 2 Targets") or burst == true then useItem(14) br.addonDebug("Using Trinket 2") return true end elseif getOptionValue("Trinket 2 Mode") == 2 then if lowest.hp <= getValue("Trinket 2") or (burst == true and lowest.hp ~= 250) then UseItemByName(GetInventoryItemID("player", 14), lowest.unit) br.addonDebug("Using Trinket 2 (Target)") return true end elseif getOptionValue("Trinket 2 Mode") == 3 and #tanks > 0 then for i = 1, #tanks do -- get the tank's target local tankTarget = UnitTarget(tanks[i].unit) if tankTarget ~= nil then -- get players in melee range of tank's target local meleeFriends = getAllies(tankTarget, 5) -- get the best ground circle to encompass the most of them local loc = nil if #meleeFriends < 12 then loc = getBestGroundCircleLocation(meleeFriends, 4, 6, 10) else local meleeHurt = {} for j = 1, #meleeFriends do if meleeFriends[j].hp < getValue("Trinket 2") then tinsert(meleeHurt, meleeFriends[j]) end end if #meleeHurt >= getValue("Min Trinket 2 Targets") or burst == true then loc = getBestGroundCircleLocation(meleeHurt, 2, 6, 10) end end if loc ~= nil then useItem(14) br.addonDebug("Using Trinket 2 (Ground)") ClickPosition(loc.x, loc.y, loc.z) return true end end end end end --Lucid Dreams if isChecked("Lucid Dreams") and essence.memoryOfLucidDreams.active and mana <= 85 and cd.memoryOfLucidDreams.remain() <= gcd then if cast.memoryOfLucidDreams("player") then br.addonDebug("Casting Memory of Lucid Dreams") return end end end end end -- End Action List - Cooldowns -- Action List - Pre-Combat local function actionList_PreCombat() if isChecked("Pig Catcher") then bossHelper() end local prepullOpener = inRaid and isChecked("Pre-pull Opener") and pullTimer <= getOptionValue("Pre-pull Opener") and not buff.rapture.exists("player") if isChecked("Pre-Pot Timer") and (pullTimer <= getOptionValue("Pre-Pot Timer") or prepullOpener) and canUseItem(163222) and not solo then useItem(163222) br.addonDebug("Using Pre-Pot") end -- Pre-pull Opener if isChecked("Azshara's Font Prepull") and pullTimer <= getOptionValue("Azshara's Font Prepull") and not isMoving("player") then if hasEquiped(169314) and canUseItem(169314) and br.timer:useTimer("Font Delay", 4) then br.addonDebug("Using Font Of Azshara") useItem(169314) end end if prepullOpener then if hasItem(166801) and canUseItem(166801) then br.addonDebug("Using Sapphire of Brilliance") useItem(166801) end if charges.powerWordRadiance.count() >= 1 and #br.friend - atonementCount >= 3 and not cast.last.powerWordRadiance() then cast.powerWordRadiance(lowest.unit) br.addonDebug("Casting Power Word Radiance") end end if not isMoving("player") and isChecked("Drink") and mana <= getOptionValue("Drink") and canUseItem(159868) then useItem(159868) br.addonDebug("Drinking") end end -- End Action List - Pre-Combat --OOC local function actionList_OOCHealing() if isChecked("OOC Healing") and (not inCombat or #enemies.yards40 < 1) then -- ooc or in combat but nothing to attack --Resurrection if isChecked("Resurrection") and not inCombat and not isMoving("player") and br.timer:useTimer("Resurrect", 4) then if getOptionValue("Resurrection - Target") == 1 and UnitIsPlayer("target") and UnitIsDeadOrGhost("target") and GetUnitIsFriend("target", "player") then if cast.resurrection("target", "dead") then br.addonDebug("Casting Resurrection (Target)") return true end end if getOptionValue("Resurrection - Target") == 2 and UnitIsPlayer("mouseover") and UnitIsDeadOrGhost("mouseover") and GetUnitIsFriend("mouseover", "player") then if cast.resurrection("mouseover", "dead") then br.addonDebug("Casting Resurrection (Mouseover)") return true end end if getOptionValue("Resurrection - Target") == 3 then local deadPlayers = {} for i =1, #br.friend do if UnitIsPlayer(br.friend[i].unit) and UnitIsDeadOrGhost(br.friend[i].unit) then tinsert(deadPlayers,br.friend[i].unit) end end if #deadPlayers > 1 then if cast.massResurrection() then br.addonDebug("Casting Mass Resurrection") return true end elseif #deadPlayers == 1 then if cast.resurrection(deadPlayers[1],"dead") then br.addonDebug("Casting Ressurection (Auto)") return true end end end end for i = 1, #br.friend do if UnitDebuffID(br.friend[i].unit, 225484) or UnitDebuffID(br.friend[i].unit, 240559) or UnitDebuffID(br.friend[i].unit, 209858) then flagDebuff = br.friend[i].guid end if isChecked("OOC Penance") and getSpellCD(spell.penance) <= 0 then if br.friend[i].hp <= getValue("OOC Penance") then if cast.penance(br.friend[i].unit) then br.addonDebug("Casting Penance") return true end end end if norganBuff and (br.friend[i].hp < 90 or flagDebuff == br.friend[i].guid) and lastSpell ~= spell.shadowMend then if getBuffRemain(br.friend[i].unit, spell.buffs.atonement, "player") < 1 and (maxAtonementCount < getValue("Max Atonements") or (br.friend[i].role == "TANK" or UnitGroupRolesAssigned(br.friend[i].unit) == "TANK")) and not buff.powerWordShield.exists(br.friend[i].unit) then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") if cast.shadowMend(br.friend[i].unit) then br.addonDebug("Casting Shadow Mend") return true end end elseif cast.shadowMend(br.friend[i].unit) then br.addonDebug("Casting Shadow Mend") return true end elseif (br.friend[i].hp < 95 or flagDebuff == br.friend[i].guid) and not buff.powerWordShield.exists(br.friend[i].unit) then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") return true end end flagDebuff = nil end -- Concentrated Flame if isChecked("Concentrated Flame") and essence.concentratedFlame.active and cd.concentratedFlame.remain() <= gcd then if (getOptionValue("Concentrated Flame") == 2 or getOptionValue("Concentrated Flame") == 3) and lowest.hp <= getValue("Concentrated Flame Heal") then if cast.concentratedFlame(lowest.unit) then br.addonDebug("Casting Concentrated Flame (Heal)") return true end end end end end local function actionList_Dispels() if mode.decurse == 1 then if isChecked("Dispel Magic") then if getOptionValue("Dispel Magic") == 1 then if canDispel("target", spell.dispelMagic) and GetObjectExists("target") then if cast.dispelMagic("target") then br.addonDebug("Casting Dispel Magic") return true end end elseif getOptionValue("Dispel Magic") == 2 then for i = 1, #enemies.yards30 do local thisUnit = enemies.yards30[i] if canDispel(thisUnit, spell.dispelMagic) then if cast.dispelMagic(thisUnit) then br.addonDebug("Casting Dispel Magic") return true end end end end end if norganBuff and isChecked("Mass Dispel") and (SpecificToggle("Mass Dispel") and not GetCurrentKeyBoardFocus()) and getSpellCD(spell.massDispel) <= gcdMax then CastSpellByName(GetSpellInfo(spell.massDispel), "cursor") br.addonDebug("Casting Mass Dispel") return true end --Purify for i = 1, #br.friend do --High Botanist Tel'arn Parasitic Fetter dispel helper if isChecked("Parasitic Fetter Dispel Helper Raid") and UnitDebuffID(br.friend[i].unit, 218304) and canDispel(br.friend[i].unit, spell.purify) then if #getAllies(br.friend[i].unit, 15) < 2 then if cast.purify(br.friend[i].unit) then br.addonDebug("Casting Purify") return true end end elseif UnitDebuffID(br.friend[i].unit, 145206) and canDispel(br.friend[i].unit, spell.purify) then if cast.purify(br.friend[i].unit) then br.addonDebug("Casting Purify") return true end else if canDispel(br.friend[i].unit, spell.purify) then if cast.purify(br.friend[i].unit) then br.addonDebug("Casting Purify") return true end end end end end end local function actionList_Extras() -- Angelic Feather if IsMovingTime(getOptionValue("Angelic Feather")) and not IsSwimming() then if not runningTime then runningTime = GetTime() end if isChecked("Angelic Feather") and talent.angelicFeather and (not buff.angelicFeather.exists("player") or GetTime() > runningTime + 5) then if cast.angelicFeather("player") then br.addonDebug("Casting Angelic Feather") runningTime = GetTime() SpellStopTargeting() end end end -- Power Word: Shield Body and Soul if IsMovingTime(getOptionValue("Body and Soul")) then if bnSTimer == nil then bnSTimer = GetTime() - 6 end if isChecked("Body and Soul") and talent.bodyAndSoul and not buff.bodyAndSoul.exists("player") and GetTime() >= bnSTimer + 6 then if cast.powerWordShield("player") then br.addonDebug("Casting Power Word Shield (Body and Soul)") bnSTimer = GetTime() return true end end end if isChecked("Power Word: Fortitude") and br.timer:useTimer("PW:F Delay", math.random(120, 300)) then for i = 1, #br.friend do if not buff.powerWordFortitude.exists(br.friend[i].unit, "any") and getDistance("player", br.friend[i].unit) < 40 and not UnitIsDeadOrGhost(br.friend[i].unit) and UnitIsPlayer(br.friend[i].unit) then if cast.powerWordFortitude() then br.addonDebug("Casting Power Word Fortitude") return true end end end end end local function actionList_AMR() -- Atonement Key if (SpecificToggle("Atonement Key") and not GetCurrentKeyBoardFocus()) and isChecked("Atonement Key") then if talent.evangelism and essence.overchargeMana.active and cd.evangelism.remains() <= gcdMax then if cd.overchargeMana.remains() <= gcdMax then if cast.overchargeMana() then br.addonDebug("Casting Ever-Rising Tide") return end elseif cd.overchargeMana.remains() > 22 then if buff.overchargeMana.stack() < 5 then for i = 1, #br.friend do if getBuffRemain(br.friend[i].unit, spell.buffs.atonement, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") return end end end elseif cast.last.powerWordShield() and buff.overchargeMana.stack() >= 5 then for i = 1, #br.friend do if getBuffRemain(br.friend[i].unit, spell.buffs.atonement, "player") < 1 then if cast.powerWordRadiance(br.friend[i].unit) then br.addonDebug("Casting Power Word Radiance") return end end end elseif cast.last.powerWordRadiance() and buff.overchargeMana.stack() >= 5 then if cast.shadowWordPain("target") then br.addonDebug("Casting Shadow Word Pain") return end end elseif cd.overchargeMana.remains() < 22 then if cast.last.shadowfiend() or cast.last.mindbender() then if cast.powerWordRadiance(lowest.unit) then br.addonDebug("Casting Power Word Radiance") return end elseif cast.last.shadowWordPain() and ((not talent.mindbender and cd.shadowfiend.remains() <= gcdMax) or (talent.mindbender and cd.mindbender.remains() <= gcdMax)) then if isChecked("Shadowfiend") then if cast.shadowfiend() then br.addonDebug("Casting Shadowfiend") return end elseif isChecked("Mindbender") then if cast.mindbender() then br.addonDebug("Casting Mindbender") return end end elseif cast.last.powerWordRadiance() then if cast.evangelism() then br.addonDebug("Casting Evangelism") return end end end else if ((atonementCount < 3 and inInstance) or (atonementCount < 5 and inRaid)) or isMoving("player") then for i = 1, #br.friend do if getBuffRemain(br.friend[i].unit, spell.buffs.atonement, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") return end end end elseif (isChecked("Shadowfiend") or isChecked("Mindbender")) and cast.last.powerWordRadiance() then if isChecked("Shadowfiend") then if cast.shadowfiend() then br.addonDebug("Casting Shadowfiend") return end elseif isChecked("Mindbender") then if cast.mindbender() then br.addonDebug("Casting Mindbender") return end end elseif ((#br.friend - atonementCount >= 3 and inInstance) or (#br.friend - atonementCount >= 5 and inRaid)) and charges.powerWordRadiance.count() >= 1 and norganBuff then for i = 1, #br.friend do if getBuffRemain(br.friend[i].unit, spell.buffs.atonement, "player") < 1 then if cast.powerWordRadiance(br.friend[i].unit) then br.addonDebug("Casting Power Word Radiance") return end end end if cast.powerWordRadiance(lowest.unit) then br.addonDebug("Casting Power Word Radiance") return end elseif isChecked("Evangelism") and talent.evangelism and getSpellCD(spell.evangelism) <= gcdMax and (atonementCount / #br.friend >= 0.8 or charges.powerWordRadiance.count() == 0) then if cast.evangelism() then br.addonDebug("Casting Evangelism") return end end end end -- Evangelism if (SpecificToggle("Evangelism Key") and not GetCurrentKeyBoardFocus()) and isChecked("Evangelism Key") then if cast.evangelism() then br.addonDebug("Casting Evangelism") return true end end -- Power Word: Barrier if (SpecificToggle("PW:B/LB Key") and not GetCurrentKeyBoardFocus()) and isChecked("PW:B/LB Key") then if not talent.luminousBarrier then CastSpellByName(GetSpellInfo(spell.powerWordBarrier), "cursor") br.addonDebug("Casting Power Word Barrier") return true else CastSpellByName(GetSpellInfo(spell.luminousBarrier), "cursor") br.addonDebug("Casting Luminous Barrier") return true end end -- Temple of Seth if inCombat and isChecked("Temple of Seth") and br.player.eID and br.player.eID == 2127 then for i = 1, GetObjectCountBR() do local thisUnit = GetObjectWithIndex(i) if GetObjectID(thisUnit) == 133392 then sethObject = thisUnit if getHP(sethObject) < 100 and getBuffRemain(sethObject, 274148) == 0 and lowest.hp >= getValue("Temple of Seth") then if cd.penance.remain() <= gcdMax then CastSpellByName(GetSpellInfo(spell.penance), sethObject) br.addonDebug("Casting Penance") end CastSpellByName(GetSpellInfo(spell.shadowMend), sethObject) br.addonDebug("Casting Shadow Mend") end end end end if isMoving("player") and isChecked("Shadow Word: Pain/Purge The Wicked") and (getSpellCD(spell.penance) > gcdMax or (getSpellCD(spell.penance) <= gcdMax and debuff.purgeTheWicked.count() == 0 and debuff.shadowWordPain.count() == 0)) then if talent.purgeTheWicked then for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if (isChecked("SW:P/PtW Targets") and currTargets() < getValue("SW:P/PtW Targets")) or not isChecked("SW:P/PtW Targets") then if GetUnitIsUnit(thisUnit, "target") or hasThreat(thisUnit) or isDummy(thisUnit) then if debuff.purgeTheWicked.remain(thisUnit) < 6 then if cast.purgeTheWicked(thisUnit) then br.addonDebug("Casting Purge the Wicked") ptwDebuff = thisUnit healCount = 0 return true end end end end end end if not talent.purgeTheWicked then for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if (isChecked("SW:P/PtW Targets") and currTargets() < getValue("SW:P/PtW Targets")) or not isChecked("SW:P/PtW Targets") then if GetUnitIsUnit(thisUnit, "target") or hasThreat(thisUnit) or isDummy(thisUnit) then if debuff.shadowWordPain.remain(thisUnit) < 4.8 then if cast.shadowWordPain(thisUnit) then br.addonDebug("Casting Shadow Word Pain") healCount = 0 return true end end end end end end end -- Power Word: Shield with Rapture if buff.rapture.exists("player") then if essence.overchargeMana.active and cd.overchargeMana.remains() <= gcdMax then if cast.overchargeMana() then br.addonDebug("Casting Ever-Rising Tide") return end elseif essence.overchargeMana.active and cd.overchargeMana.remains() > 22 then for i = 1, #br.friend do if not buff.atonement.exists(br.friend[i].unit) and getBuffRemain(br.friend[i].unit, spell.buffs.powerWordShield, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") return true end end end end if isChecked("Obey Atonement Limits") then for i = 1, #br.friend do if maxAtonementCount < getValue("Max Atonements") and not buff.atonement.exists(br.friend[i].unit) and getBuffRemain(br.friend[i].unit, spell.buffs.powerWordShield, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") return true end end end for i = 1, #br.friend do if maxAtonementCount < getValue("Max Atonements") or (br.friend[i].role == "TANK" or UnitGroupRolesAssigned(br.friend[i].unit) == "TANK") then if getBuffRemain(br.friend[i].unit, spell.buffs.powerWordShield, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") return true end end end end else for i = 1, #br.friend do if not buff.atonement.exists(br.friend[i].unit) and getBuffRemain(br.friend[i].unit, spell.buffs.powerWordShield, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") return true end end end for i = 1, #br.friend do if getBuffRemain(br.friend[i].unit, spell.buffs.powerWordShield, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") return true end end end end end -- Evangelism if isChecked("Evangelism") and talent.evangelism and (atonementCount >= getValue("Atonement for Evangelism") or (not inRaid and atonementCount >= 3)) and not buff.rapture.exists("player") and not freeMana then if getLowAllies(getValue("Evangelism")) >= getValue("Evangelism Targets") then if cast.evangelism() then br.addonDebug("Casting Evangelism") return true end end end -- Power Word Radiance if ((isChecked("Alternate Heal & Damage") and healCount < getValue("Alternate Heal & Damage")) or not isChecked("Alternate Heal & Damage")) and schismCount < 1 then if isChecked("Power Word: Radiance") and #br.friend - atonementCount >= 2 and norganBuff and not cast.last.powerWordRadiance() and atonementCount < 10 then if charges.powerWordRadiance.count() >= 1 then if getLowAllies(getValue("Power Word: Radiance")) >= getValue("PWR Targets") then for i = 1, #br.friend do if not buff.atonement.exists(br.friend[i].unit) and br.friend[i].hp <= getValue("Power Word: Radiance") then if cast.powerWordRadiance(br.friend[i].unit) then br.addonDebug("Casting Power Word Radiance") healCount = healCount + 1 return true end end end end end end end -- Shadow Covenant if isChecked("Shadow Covenant") and talent.shadowCovenant and schismCount < 1 and atonementCount < 10 then if getLowAllies(getValue("Shadow Covenant")) >= getValue("Shadow Covenant Targets") and lastSpell ~= spell.shadowCovenant then if cast.shadowCovenant(lowest.unit) then br.addonDebug("Casting Shadow Covenant") return true end end end -- Contrition Penance Heal if isChecked("Penance Heal") and penanceCheck and talent.contrition and atonementCount >= 3 and schismCount < 1 then if cast.penance(lowest.unit) then br.addonDebug("Casting Penance (Heal)") return true end end -- Shadow Mend if ((isChecked("Alternate Heal & Damage") and healCount < getValue("Alternate Heal & Damage")) or not isChecked("Alternate Heal & Damage")) and schismCount < 1 then if isChecked("Shadow Mend") and norganBuff and atonementCount < 5 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Shadow Mend") and (not buff.atonement.exists(br.friend[i].unit) or not IsInRaid()) then if cast.shadowMend(br.friend[i].unit) then br.addonDebug("Casting Shadow Mend") healCount = healCount + 1 return true end end end end end -- Power Word: Shield if ((isChecked("Alternate Heal & Damage") and healCount < getValue("Alternate Heal & Damage")) or not isChecked("Alternate Heal & Damage")) and schismCount < 1 then for i = 1, #tanks do if (tanks[i].hp <= getValue("Tank Atonement HP") or getValue("Tank Atonement HP") == 100) and not buff.powerWordShield.exists(tanks[i].unit) and getBuffRemain(tanks[i].unit, spell.buffs.atonement, "player") < 1 then if isChecked("Depths of the Shadows") and buff.depthOfTheShadows.stack() >= getValue("Depths of the Shadows") then if cast.shadowMend(tanks[i].unit) then br.addonDebug("Casting Shadow Mend") healCount = healCount + 1 end elseif cast.powerWordShield(tanks[i].unit) then br.addonDebug("Casting Power Word Shield") healCount = healCount + 1 return true end end end for i = 1, #br.friend do if br.friend[i].role ~= "TANK" and (br.friend[i].hp <= getValue("Party Atonement HP") or getValue("Party Atonement HP") == 100) and not buff.powerWordShield.exists(br.friend[i].unit) and getBuffRemain(br.friend[i].unit, spell.buffs.atonement, "player") < 1 and maxAtonementCount < getValue("Max Atonements") then if isChecked("Depths of the Shadows") and buff.depthOfTheShadows.stack() >= getValue("Depths of the Shadows") then if cast.shadowMend(br.friend[i].unit) then br.addonDebug("Casting Shadow Mend") healCount = healCount + 1 end elseif cast.powerWordShield(br.friend[i].unit) then br.addonDebug("Casting Power Word Shield") healCount = healCount + 1 return true end end end end -- Mindbender if isChecked("Mindbender") and mana <= getValue("Mindbender") and atonementCount >= 3 and talent.mindbender then if debuff.schism.exists(schismBuff) then if cast.mindbender(schismBuff) then br.addonDebug("Casting Mindbender") healCount = 0 end end if cast.mindbender() then br.addonDebug("Casting Mindbender") healCount = 0 end end -- Shadowfiend if isChecked("Shadowfiend") and not talent.mindbender and atonementCount >= 3 then if debuff.schism.exists(schismBuff) then if cast.shadowfiend(schismBuff) then br.addonDebug("Casting Shadowfiend") healCount = 0 end end if cast.shadowfiend() then br.addonDebug("Casting Shadowfiend") healCount = 0 end end -- Purge the Wicked/ Shadow Word: Pain if isChecked("Shadow Word: Pain/Purge The Wicked") and (getSpellCD(spell.penance) > 0 or (getSpellCD(spell.penance) <= 0 and debuff.purgeTheWicked.count() == 0 and debuff.shadowWordPain.count() == 0)) then if talent.purgeTheWicked then for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if (isChecked("SW:P/PtW Targets") and currTargets() < getValue("SW:P/PtW Targets")) or not isChecked("SW:P/PtW Targets") then if GetUnitIsUnit(thisUnit, "target") or hasThreat(thisUnit) or isDummy(thisUnit) then if debuff.purgeTheWicked.remain(thisUnit) < 6 then if cast.purgeTheWicked(thisUnit) then br.addonDebug("Purge the Wicked") ptwDebuff = thisUnit healCount = 0 return true end end end end end end if not talent.purgeTheWicked then for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if (isChecked("SW:P/PtW Targets") and currTargets() < getValue("SW:P/PtW Targets")) or not isChecked("SW:P/PtW Targets") then if GetUnitIsUnit(thisUnit, "target") or hasThreat(thisUnit) or isDummy(thisUnit) then if debuff.shadowWordPain.remain(thisUnit) < 4.8 then if cast.shadowWordPain(thisUnit) then br.addonDebug("Casting Shadow Word Pain") healCount = 0 return true end end end end end end end -- Schism (2+ Atonement) if talent.schism and isChecked("Schism") and atonementCount >= 2 and cd.penance.remain() <= gcdMax and norganBuff and ttd("target") > 9 and not isExplosive("target") then if cast.schism("target") then br.addonDebug("Casting Schism") schismBuff = getUnitID("target") end end -- Power Word: Solace if isChecked("Power Word: Solace") and talent.powerWordSolace then if debuff.schism.exists(schismBuff) then if cast.powerWordSolace(schismBuff) then br.addonDebug("Casting Power Word Solace") healCount = 0 return true end elseif cast.powerWordSolace() then br.addonDebug("Casting Power Word Solace") healCount = 0 return true end end -- Halo if isChecked("Halo") and norganBuff then if getLowAllies(getValue("Halo")) >= getValue("Halo Targets") then if cast.halo(lowest.unit) then br.addonDebug("Casting Halo") return true end end end -- Divine Star if isChecked("Divine Star Healing") and talent.divineStar then --print("DSUnits: "..DSUnits.." DSAtone: "..DSAtone) if DSUnits >= getOptionValue("DS Healing Targets") and DSAtone >= 1 then if cast.divineStar() then br.addonDebug("Casting Divine Star") healCount = 0 end end end -- Penance if isChecked("Penance") and penanceCheck and dpsCheck then if GetUnitExists("target") then penanceTarget = "target" end if penanceTarget ~= nil then if isValidUnit(schismBuff) and debuff.schism.exists(schismBuff) then penanceTarget = schismBuff end if ptwDebuff and isValidUnit(ptwDebuff) then penanceTarget = ptwDebuff end if not GetUnitIsFriend(penanceTarget, "player") then if cast.penance(penanceTarget) then br.addonDebug("Casting Penance") healCount = 0 return true end end else if lowest.hp <= getOptionValue("Penance Heal") then if cast.penance(lowest.unit) then br.addonDebug("Casting Penance") return true end end end end -- Concentrated Flame if isChecked("Concentrated Flame") and essence.concentratedFlame.active and cd.concentratedFlame.remain() <= gcd then if (getOptionValue("Concentrated Flame") == 2 or getOptionValue("Concentrated Flame") == 3) and lowest.hp <= getValue("Concentrated Flame Heal") then if cast.concentratedFlame(lowest.unit) then br.addonDebug("Casting Concentrated Flame (Heal)") return true end else if getOptionValue("Concentrated Flame") == 1 or (getOptionValue("Concentrated Flame") == 3 and not debuff.schism.exists(schismBuff) and lowest.hp > getValue("Concentrated Flame Heal")) then if cast.concentratedFlame("target") then br.addonDebug("Casting Concentrated Flame (Dmg)") return true end end end end -- Refreshment if isChecked("Well of Existence") and essence.refreshment.active and cd.refreshment.remain() <= gcd and UnitBuffID("player", 296138) and select(16, UnitBuffID("player", 296138, "EXACT")) >= 15000 and lowest.hp <= getValue("Shadow Mend") then if cast.refreshment(lowest.unit) then br.addonDebug("Casting Refreshment") return true end end -- Azshara's Font of Power if isChecked("Azshara's Font") and hasEquiped(169314) and lowest.hp > getOptionValue("Azshara's Font") and not UnitBuffID("player", 296962) and br.timer:useTimer("Font Delay", 4) and canUseItem(169314) and not isMoving("player") and ttd("target") > 30 then useItem(169314) br.addonDebug("Using Font of Azshara") return true end -- Shadow Mend if ((isChecked("Alternate Heal & Damage") and healCount < getValue("Alternate Heal & Damage")) or not isChecked("Alternate Heal & Damage")) and schismCount < 1 then if isChecked("Shadow Mend") and norganBuff then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Shadow Mend") then if cast.shadowMend(br.friend[i].unit) then br.addonDebug("Casting Shadow Mend") healCount = healCount + 1 return true end end end end end -- Smite if isChecked("Smite") and norganBuff and (freeCast or dpsCheck) then if debuff.schism.exists(schismBuff) then if cast.smite(schismBuff) then br.addonDebug("Casting Smite") healCount = 0 return true end elseif cast.smite() then br.addonDebug("Casting Smite") healCount = 0 return true end end -- Fade if isChecked("Fade") and not cast.active.penance() then if php <= getValue("Fade") and not solo then if cast.fade() then br.addonDebug("Casting Fade") return true end end end end if br.data.settings[br.selectedSpec][br.selectedProfile]["HE ActiveCheck"] == false and br.timer:useTimer("Error delay", 0.5) then Print("Detecting Healing Engine is not turned on. Please activate Healing Engine to use this profile.") return end ----------------- --- Rotations --- ----------------- -- Pause if pause() or UnitDebuffID("player", 240447) or (getBuffRemain("player", 192001) > 0 and mana < 100) or getBuffRemain("player", 192002) > 10 or (getBuffRemain("player", 192002) > 0 and mana < 100) or getBuffRemain("player", 188023) > 0 or getBuffRemain("player", 175833) > 0 then return true else --------------------------------- --- Out Of Combat - Rotations --- --------------------------------- if not inCombat and not IsMounted() then if actionList_Extras() then return true end if actionList_PreCombat() then return true end if actionList_Dispels() then return true end if actionList_OOCHealing() then return true end if GetUnitExists("target") and isValidUnit("target") and getDistance("target", "player") < 40 and isChecked("Pull Spell") then if cast.shadowWordPain() then br.addonDebug("Casting Shadow Word Pain") return true end end end -- End Out of Combat Rotation ----------------------------- --- In Combat - Rotations --- ----------------------------- if inCombat and not IsMounted() then actionList_Interrupts() actionList_Dispels() if actionList_Extras() then return true end if actionList_Defensive() then return true end if actionList_Cooldowns() then return true end if actionList_AMR() then return true end end -- End In Combat Rotation end -- Pause end -- End Timer end -- End runRotation local id = 256 if br.rotations[id] == nil then br.rotations[id] = {} end tinsert( br.rotations[id], { name = rotationName, toggles = createToggles, options = createOptions, run = runRotation } )
gpl-3.0
adamel/sysdig
userspace/sysdig/chisels/common.lua
2
6833
--[[ Copyright (C) 2013-2014 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] --[[ This file contains a bunch of functions that are helpful in multiple scripts ]]-- --[[ Serialize the content of a table into a tring ]]-- function st(val, name, skipnewlines, depth) skipnewlines = skipnewlines or false depth = depth or 0 local tmp = string.rep(" ", depth) if name then tmp = tmp .. name .. " = " end if type(val) == "table" then tmp = tmp .. "{" .. (not skipnewlines and "\n" or "") for k, v in pairs(val) do tmp = tmp .. st(v, k, skipnewlines, depth + 1) .. "," .. (not skipnewlines and "\n" or "") end tmp = tmp .. string.rep(" ", depth) .. "}" elseif type(val) == "number" then tmp = tmp .. tostring(val) elseif type(val) == "string" then tmp = tmp .. string.format("%q", val) elseif type(val) == "boolean" then tmp = tmp .. (val and "true" or "false") else tmp = tmp .. "\"[inserializeable datatype:" .. type(val) .. "]\"" end return tmp end --[[ Extends a string to newlen with spaces ]]-- function extend_string(s, newlen) if #s < newlen then local ccs = " " s = s .. string.sub(ccs, 0, newlen - #s) return s else if newlen > 0 then return (string.sub(s, 0, newlen - 1) .. " ") else return "" end end end --[[ Basic string split. ]]-- function split(s, delimiter) local result = {} for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match) end return result end --[[ convert a number into a byte representation. E.g. 1230 becomes 1.23K ]]-- function format_bytes(val) if val > (1024 * 1024 * 1024 * 1024 * 1024) then return string.format("%.2fP", val / (1024 * 1024 * 1024 * 1024 * 1024)) elseif val > (1024 * 1024 * 1024 * 1024) then return string.format("%.2fT", val / (1024 * 1024 * 1024 * 1024)) elseif val > (1024 * 1024 * 1024) then return string.format("%.2fG", val / (1024 * 1024 * 1024)) elseif val > (1024 * 1024) then return string.format("%.2fM", val / (1024 * 1024)) elseif val > 1024 then return string.format("%.2fKB", val / (1024)) else return string.format("%dB", val) end end --[[ convert a nanosecond time interval into a s.ns representation. E.g. 1100000000 becomes 1.1s ]]-- ONE_S_IN_NS=1000000000 ONE_MS_IN_NS=1000000 ONE_US_IN_NS=1000 function format_time_interval(val) if val >= (ONE_S_IN_NS) then return string.format("%u.%02us", math.floor(val / ONE_S_IN_NS), (val % ONE_S_IN_NS) / 10000000) elseif val >= (ONE_S_IN_NS / 100) then return string.format("%ums", math.floor(val / (ONE_S_IN_NS / 1000))) elseif val >= (ONE_S_IN_NS / 1000) then return string.format("%u.%02ums", math.floor(val / (ONE_S_IN_NS / 1000)), (val % ONE_MS_IN_NS) / 10000) elseif val >= (ONE_S_IN_NS / 100000) then return string.format("%uus", math.floor(val / (ONE_S_IN_NS / 1000000))) elseif val >= (ONE_S_IN_NS / 1000000) then return string.format("%u.%02uus", math.floor(val / (ONE_S_IN_NS / 1000000)), (val % ONE_US_IN_NS) / 10) else return string.format("%uns", val) end end --[[ extract the top num entries from the table t, after sorting them based on the entry value using the function order() ]]-- function pairs_top_by_val(t, num, order) local keys = {} for k in pairs(t) do keys[#keys+1] = k end table.sort(keys, function(a,b) return order(t, a, b) end) local i = 0 return function() i = i + 1 if (num == 0 or i <= num) and keys[i] then return keys[i], t[keys[i]] end end end --[[ Timestamp <-> string conversion ]]-- function ts_to_str(tshi, tslo) return string.format("%u%.9u", tshi, tslo) end --[[ Pick a key-value table and render it to the console in sorted top format ]]-- json = require ("dkjson") function print_sorted_table(stable, ts_s, ts_ns, timedelta, viz_info) local sorted_grtable = pairs_top_by_val(stable, viz_info.top_number, function(t,a,b) return t[b] < t[a] end) if viz_info.output_format == "json" then local jdata = {} local j = 1 for k,v in sorted_grtable do local vals = split(k, "\001\001") vals[#vals + 1] = v jdata[j] = vals j = j + 1 end local jinfo = {} for i, keyname in ipairs(viz_info.key_fld) do jinfo[i] = {name = keyname, desc = viz_info.key_desc[i], is_key = true} end jinfo[3] = {name = viz_info.value_fld, desc = viz_info.value_desc, is_key = false} local res = {ts = sysdig.make_ts(ts_s, ts_ns), data = jdata, info = jinfo} local str = json.encode(res, { indent = true }) print(str) else -- Same size to extend each string local EXTEND_STRING_SIZE = 16 local header = extend_string(viz_info.value_desc, EXTEND_STRING_SIZE) for i, fldname in ipairs(viz_info.key_desc) do header = header .. extend_string(fldname, EXTEND_STRING_SIZE) end print(header) print("--------------------------------------------------------------------------------") for k,v in sorted_grtable do local keystr = "" local singlekeys = split(k, "\001\001") for i, singlekey in ipairs(singlekeys) do if i < #singlekeys then keystr = keystr .. extend_string(string.sub(singlekey, 0, 10), EXTEND_STRING_SIZE) else keystr = keystr .. singlekey end end if viz_info.value_units == "none" then print(extend_string(tostring(v), EXTEND_STRING_SIZE) .. keystr) elseif viz_info.value_units == "bytes" then print(extend_string(format_bytes(v), EXTEND_STRING_SIZE) .. keystr) elseif viz_info.value_units == "time" then print(extend_string(format_time_interval(v), EXTEND_STRING_SIZE) .. keystr) elseif viz_info.value_units == "timepct" then if timedelta ~= 0 then pctstr = string.format("%.2f%%", v / timedelta * 100) else pctstr = "0.00%" end print(extend_string(pctstr, EXTEND_STRING_SIZE) .. keystr) end end end end --[[ Try to convert user input to a number using tonumber(). If tonumber() returns 'nil', print an error message to the user and exit, otherwise return tonumber(value). ]]-- function parse_numeric_input(value, name) val = tonumber(value) if val == nil then print(string.format("Input %s must be a number.", name)) require ("os") os.exit() end return val end
gpl-2.0
tianxiawuzhei/cocos-quick-lua
quick/cocos/cocos2d/Cocos2dConstants.lua
1
15966
cc = cc or {} cc.SPRITE_INDEX_NOT_INITIALIZED = 0xffffffff cc.TMX_ORIENTATION_HEX = 0x1 cc.TMX_ORIENTATION_ISO = 0x2 cc.TMX_ORIENTATION_ORTHO = 0x0 cc.Z_COMPRESSION_BZIP2 = 0x1 cc.Z_COMPRESSION_GZIP = 0x2 cc.Z_COMPRESSION_NONE = 0x3 cc.Z_COMPRESSION_ZLIB = 0x0 cc.BLEND_DST = 0x303 cc.BLEND_SRC = 0x1 cc.DIRECTOR_IOS_USE_BACKGROUND_THREAD = 0x0 cc.DIRECTOR_MAC_THREAD = 0x0 cc.DIRECTOR_STATS_INTERVAL = 0.1 cc.ENABLE_BOX2_D_INTEGRATION = 0x0 cc.ENABLE_DEPRECATED = 0x1 cc.ENABLE_GL_STATE_CACHE = 0x1 cc.ENABLE_PROFILERS = 0x0 cc.ENABLE_STACKABLE_ACTIONS = 0x1 cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0x0 cc.GL_ALL = 0x0 cc.LABELATLAS_DEBUG_DRAW = 0x0 cc.LABELBMFONT_DEBUG_DRAW = 0x0 cc.MAC_USE_DISPLAY_LINK_THREAD = 0x0 cc.MAC_USE_MAIN_THREAD = 0x2 cc.MAC_USE_OWN_THREAD = 0x1 cc.NODE_RENDER_SUBPIXEL = 0x1 cc.PVRMIPMAP_MAX = 0x10 cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 0x1 cc.SPRITE_DEBUG_DRAW = 0x0 cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0x0 cc.TEXTURE_ATLAS_USE_VAO = 0x1 cc.USE_L_A88_LABELS = 0x1 cc.ACTION_TAG_INVALID = -1 cc.DEVICE_MAC = 0x6 cc.DEVICE_MAC_RETINA_DISPLAY = 0x7 cc.DEVICEI_PAD = 0x4 cc.DEVICEI_PAD_RETINA_DISPLAY = 0x5 cc.DEVICEI_PHONE = 0x0 cc.DEVICEI_PHONE5 = 0x2 cc.DEVICEI_PHONE5_RETINA_DISPLAY = 0x3 cc.DEVICEI_PHONE_RETINA_DISPLAY = 0x1 cc.DIRECTOR_PROJECTION2_D = 0x0 cc.DIRECTOR_PROJECTION3_D = 0x1 cc.DIRECTOR_PROJECTION_CUSTOM = 0x2 cc.DIRECTOR_PROJECTION_DEFAULT = 0x1 cc.FILE_UTILS_SEARCH_DIRECTORY_MODE = 0x1 cc.FILE_UTILS_SEARCH_SUFFIX_MODE = 0x0 cc.FLIPED_ALL = 0xe0000000 cc.FLIPPED_MASK = 0x1fffffff cc.IMAGE_FORMAT_JPEG = 0x0 cc.IMAGE_FORMAT_PNG = 0x1 cc.ITEM_SIZE = 0x20 cc.LABEL_AUTOMATIC_WIDTH = -1 cc.LINE_BREAK_MODE_CHARACTER_WRAP = 0x1 cc.LINE_BREAK_MODE_CLIP = 0x2 cc.LINE_BREAK_MODE_HEAD_TRUNCATION = 0x3 cc.LINE_BREAK_MODE_MIDDLE_TRUNCATION = 0x5 cc.LINE_BREAK_MODE_TAIL_TRUNCATION = 0x4 cc.LINE_BREAK_MODE_WORD_WRAP = 0x0 cc.MAC_VERSION_10_6 = 0xa060000 cc.MAC_VERSION_10_7 = 0xa070000 cc.MAC_VERSION_10_8 = 0xa080000 cc.MENU_HANDLER_PRIORITY = -128 cc.MENU_STATE_TRACKING_TOUCH = 0x1 cc.MENU_STATE_WAITING = 0x0 cc.NODE_TAG_INVALID = -1 cc.PARTICLE_DURATION_INFINITY = -1 cc.PARTICLE_MODE_GRAVITY = 0x0 cc.PARTICLE_MODE_RADIUS = 0x1 cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS = -1 cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE = -1 cc.POSITION_TYPE_FREE = 0x0 cc.POSITION_TYPE_GROUPED = 0x2 cc.POSITION_TYPE_RELATIVE = 0x1 cc.PRIORITY_NON_SYSTEM_MIN = -2147483647 cc.PRIORITY_SYSTEM = -2147483648 cc.PROGRESS_TIMER_TYPE_BAR = 0x1 cc.PROGRESS_TIMER_TYPE_RADIAL = 0x0 cc.REPEAT_FOREVER = 0xfffffffe cc.RESOLUTION_MAC = 0x1 cc.RESOLUTION_MAC_RETINA_DISPLAY = 0x2 cc.RESOLUTION_UNKNOWN = 0x0 cc.TMX_TILE_DIAGONAL_FLAG = 0x20000000 cc.TMX_TILE_HORIZONTAL_FLAG = 0x80000000 cc.TMX_TILE_VERTICAL_FLAG = 0x40000000 cc.TEXT_ALIGNMENT_CENTER = 0x1 cc.TEXT_ALIGNMENT_LEFT = 0x0 cc.TEXT_ALIGNMENT_RIGHT = 0x2 cc.TEXTURE2_D_PIXEL_FORMAT_AUTO = 0x0 cc.TEXTURE2_D_PIXEL_FORMAT_BGR_A8888 = 0x1 cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888 = 0x2 cc.TEXTURE2_D_PIXEL_FORMAT_RG_B888 = 0x3 cc.TEXTURE2_D_PIXEL_FORMAT_RG_B565 = 0x4 cc.TEXTURE2_D_PIXEL_FORMAT_A8 = 0x5 cc.TEXTURE2_D_PIXEL_FORMAT_I8 = 0x6 cc.TEXTURE2_D_PIXEL_FORMAT_A_I88 = 0x7 cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444 = 0x8 cc.TEXTURE2_D_PIXEL_FORMAT_RGB5_A1 = 0x9 cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC4 = 0xa cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC4A = 0xb cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC2 = 0xc cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC2A = 0xd cc.TEXTURE2_D_PIXEL_FORMAT_ETC = 0xe cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT1 = 0xf cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT3 = 0x10 cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT5 = 0x11 cc.TEXTURE2_D_PIXEL_FORMAT_DEFAULT = 0x0 cc.TOUCHES_ALL_AT_ONCE = 0x0 cc.TOUCHES_ONE_BY_ONE = 0x1 cc.TRANSITION_ORIENTATION_DOWN_OVER = 0x1 cc.TRANSITION_ORIENTATION_LEFT_OVER = 0x0 cc.TRANSITION_ORIENTATION_RIGHT_OVER = 0x1 cc.TRANSITION_ORIENTATION_UP_OVER = 0x0 cc.UNIFORM_COS_TIME = 0x5 cc.UNIFORM_MV_MATRIX = 0x1 cc.UNIFORM_MVP_MATRIX = 0x2 cc.UNIFORM_P_MATRIX = 0x0 cc.UNIFORM_RANDOM01 = 0x6 cc.UNIFORM_SAMPLER = 0x7 cc.UNIFORM_SIN_TIME = 0x4 cc.UNIFORM_TIME = 0x3 cc.UNIFORM_MAX = 0x8 cc.VERTEX_ATTRIB_FLAG_COLOR = 0x2 cc.VERTEX_ATTRIB_FLAG_NONE = 0x0 cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = 0x7 cc.VERTEX_ATTRIB_FLAG_POSITION = 0x1 cc.VERTEX_ATTRIB_FLAG_TEX_COORDS = 0x4 cc.VERTEX_ATTRIB_COLOR = 0x1 cc.VERTEX_ATTRIB_MAX = 0x3 cc.VERTEX_ATTRIB_POSITION = 0x0 cc.VERTEX_ATTRIB_TEX_COORD = 0x2 cc.VERTEX_ATTRIB_TEX_COORDS = 0x2 cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM = 0x2 cc.VERTICAL_TEXT_ALIGNMENT_CENTER = 0x1 cc.VERTICAL_TEXT_ALIGNMENT_TOP = 0x0 cc.OS_VERSION_4_0 = 0x4000000 cc.OS_VERSION_4_0_1 = 0x4000100 cc.OS_VERSION_4_1 = 0x4010000 cc.OS_VERSION_4_2 = 0x4020000 cc.OS_VERSION_4_2_1 = 0x4020100 cc.OS_VERSION_4_3 = 0x4030000 cc.OS_VERSION_4_3_1 = 0x4030100 cc.OS_VERSION_4_3_2 = 0x4030200 cc.OS_VERSION_4_3_3 = 0x4030300 cc.OS_VERSION_4_3_4 = 0x4030400 cc.OS_VERSION_4_3_5 = 0x4030500 cc.OS_VERSION_5_0 = 0x5000000 cc.OS_VERSION_5_0_1 = 0x5000100 cc.OS_VERSION_5_1_0 = 0x5010000 cc.OS_VERSION_6_0_0 = 0x6000000 cc.ANIMATION_FRAME_DISPLAYED_NOTIFICATION = 'CCAnimationFrameDisplayedNotification' cc.CHIPMUNK_IMPORT = 'chipmunk.h' cc.ATTRIBUTE_NAME_COLOR = 'a_color' cc.ATTRIBUTE_NAME_POSITION = 'a_position' cc.ATTRIBUTE_NAME_TEX_COORD = 'a_texCoord' cc.SHADER_POSITION_COLOR = 'ShaderPositionColor' cc.SHADER_POSITION_LENGTH_TEXURE_COLOR = 'ShaderPositionLengthTextureColor' cc.SHADER_POSITION_TEXTURE = 'ShaderPositionTexture' cc.SHADER_POSITION_TEXTURE_A8_COLOR = 'ShaderPositionTextureA8Color' cc.SHADER_POSITION_TEXTURE_COLOR = 'ShaderPositionTextureColor' cc.SHADER_POSITION_TEXTURE_COLOR_ALPHA_TEST = 'ShaderPositionTextureColorAlphaTest' cc.SHADER_POSITION_TEXTURE_U_COLOR = 'ShaderPositionTexture_uColor' cc.SHADER_POSITION_U_COLOR = 'ShaderPosition_uColor' cc.UNIFORM_ALPHA_TEST_VALUE_S = 'CC_AlphaValue' cc.UNIFORM_COS_TIME_S = 'CC_CosTime' cc.UNIFORM_MV_MATRIX_S = 'CC_MVMatrix' cc.UNIFORM_MVP_MATRIX_S = 'CC_MVPMatrix' cc.UNIFORM_P_MATRIX_S = 'CC_PMatrix' cc.UNIFORM_RANDOM01_S = 'CC_Random01' cc.UNIFORM_SAMPLER_S = 'CC_Texture0' cc.UNIFORM_SIN_TIME_S = 'CC_SinTime' cc.UNIFORM_TIME_S = 'CC_Time' cc.PLATFORM_OS_WINDOWS = 0 cc.PLATFORM_OS_LINUX = 1 cc.PLATFORM_OS_MAC = 2 cc.PLATFORM_OS_ANDROID = 3 cc.PLATFORM_OS_IPHONE = 4 cc.PLATFORM_OS_IPAD = 5 cc.PLATFORM_OS_BLACKBERRY = 6 cc.PLATFORM_OS_NACL = 7 cc.PLATFORM_OS_EMSCRIPTEN = 8 cc.PLATFORM_OS_TIZEN = 9 cc.LANGUAGE_ENGLISH = 0 cc.LANGUAGE_CHINESE = 1 cc.LANGUAGE_FRENCH = 2 cc.LANGUAGE_ITALIAN = 3 cc.LANGUAGE_GERMAN = 4 cc.LANGUAGE_SPANISH = 5 cc.LANGUAGE_DUTCH = 6 cc.LANGUAGE_RUSSIAN = 7 cc.LANGUAGE_KOREAN = 8 cc.LANGUAGE_JAPANESE = 9 cc.LANGUAGE_HUNGARIAN = 10 cc.LANGUAGE_PORTUGUESE = 11 cc.LANGUAGE_ARABIC = 12 cc.LANGUAGE_NORWEGIAN = 13 cc.LANGUAGE_POLISH = 14 cc.NODE_ON_ENTER = 0 cc.NODE_ON_EXIT = 1 cc.NODE_ON_ENTER_TRANSITION_DID_FINISH = 2 cc.NODE_ON_EXIT_TRANSITION_DID_START = 3 cc.NODE_ON_CLEAN_UP = 4 cc.Handler = cc.Handler or {} cc.Handler.NODE = 0 cc.Handler.MENU_CLICKED = 1 cc.Handler.CALLFUNC = 2 cc.Handler.SCHEDULE = 3 cc.Handler.TOUCHES = 4 cc.Handler.KEYPAD = 5 cc.Handler.ACCELEROMETER = 6 cc.Handler.CONTROL_TOUCH_DOWN = 7 cc.Handler.CONTROL_TOUCH_DRAG_INSIDE = 8 cc.Handler.CONTROL_TOUCH_DRAG_OUTSIDE = 9 cc.Handler.CONTROL_TOUCH_DRAG_ENTER = 10 cc.Handler.CONTROL_TOUCH_DRAG_EXIT = 11 cc.Handler.CONTROL_TOUCH_UP_INSIDE = 12 cc.Handler.CONTROL_TOUCH_UP_OUTSIDE = 13 cc.Handler.CONTROL_TOUCH_UP_CANCEL = 14 cc.Handler.CONTROL_VALUE_CHANGED = 15 cc.Handler.WEBSOCKET_OPEN = 16 cc.Handler.WEBSOCKET_MESSAGE = 17 cc.Handler.WEBSOCKET_CLOSE = 18 cc.Handler.WEBSOCKET_ERROR = 19 cc.Handler.GL_NODE_DRAW = 20 cc.Handler.SCROLLVIEW_SCROLL = 21 cc.Handler.SCROLLVIEW_ZOOM = 22 cc.Handler.TABLECELL_TOUCHED = 23 cc.Handler.TABLECELL_HIGHLIGHT = 24 cc.Handler.TABLECELL_UNHIGHLIGHT = 25 cc.Handler.TABLECELL_WILL_RECYCLE = 26 cc.Handler.TABLECELL_SIZE_FOR_INDEX = 27 cc.Handler.TABLECELL_AT_INDEX = 28 cc.Handler.TABLEVIEW_NUMS_OF_CELLS = 29 cc.Handler.HTTPREQUEST_STATE_CHANGE = 30 cc.Handler.ASSETSMANAGER_PROGRESS = 31 cc.Handler.ASSETSMANAGER_SUCCESS = 32 cc.Handler.ASSETSMANAGER_ERROR = 33 cc.Handler.STUDIO_EVENT_LISTENER = 34 cc.Handler.ARMATURE_EVENT = 35 cc.Handler.EVENT_ACC = 36 cc.Handler.EVENT_CUSTIOM = 37 cc.Handler.EVENT_KEYBOARD_PRESSED = 38 cc.Handler.EVENT_KEYBOARD_RELEASED = 39 cc.Handler.EVENT_TOUCH_BEGAN = 40 cc.Handler.EVENT_TOUCH_MOVED = 41 cc.Handler.EVENT_TOUCH_ENDED = 42 cc.Handler.EVENT_TOUCH_CANCELLED = 43 cc.Handler.EVENT_TOUCHES_BEGAN = 44 cc.Handler.EVENT_TOUCHES_MOVED = 45 cc.Handler.EVENT_TOUCHES_ENDED = 46 cc.Handler.EVENT_TOUCHES_CANCELLED = 47 cc.Handler.EVENT_MOUSE_DOWN = 48 cc.Handler.EVENT_MOUSE_UP = 49 cc.Handler.EVENT_MOUSE_MOVE = 50 cc.Handler.EVENT_MOUSE_SCROLL = 51 cc.Handler.EVENT_SPINE = 52 cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN = 53 cc.Handler.EVENT_PHYSICS_CONTACT_PRESOLVE = 54 cc.Handler.EVENT_PHYSICS_CONTACT_POSTSOLVE = 55 cc.Handler.EVENT_PHYSICS_CONTACT_SEPERATE = 56 cc.Handler.EVENT_FOCUS = 57 cc.Handler.EVENT_CONTROLLER_CONNECTED = 58 cc.Handler.EVENT_CONTROLLER_DISCONNECTED = 59 cc.Handler.EVENT_CONTROLLER_KEYDOWN = 60 cc.Handler.EVENT_CONTROLLER_KEYUP = 61 cc.Handler.EVENT_CONTROLLER_KEYREPEAT = 62 cc.Handler.EVENT_CONTROLLER_AXIS = 63 cc.Handler.EVENT_SPINE_ANIMATION_START = 64 cc.Handler.EVENT_SPINE_ANIMATION_END = 65 cc.Handler.EVENT_SPINE_ANIMATION_COMPLETE = 66 cc.Handler.EVENT_SPINE_ANIMATION_EVENT = 67 cc.EVENT_UNKNOWN = 0 cc.EVENT_TOUCH_ONE_BY_ONE = 1 cc.EVENT_TOUCH_ALL_AT_ONCE = 2 cc.EVENT_KEYBOARD = 3 cc.EVENT_MOUSE = 4 cc.EVENT_ACCELERATION = 5 cc.EVENT_CUSTOM = 6 cc.PHYSICSSHAPE_MATERIAL_DEFAULT = {density = 0.0, restitution = 0.5, friction = 0.5} cc.PHYSICSBODY_MATERIAL_DEFAULT = {density = 0.1, restitution = 0.5, friction = 0.5} cc.GLYPHCOLLECTION_DYNAMIC = 0 cc.GLYPHCOLLECTION_NEHE = 1 cc.GLYPHCOLLECTION_ASCII = 2 cc.GLYPHCOLLECTION_CUSTOM = 3 cc.ResolutionPolicy = { EXACT_FIT = 0, NO_BORDER = 1, SHOW_ALL = 2, FIXED_HEIGHT = 3, FIXED_WIDTH = 4, UNKNOWN = 5, } cc.LabelEffect = { NORMAL = 0, OUTLINE = 1, SHADOW = 2, GLOW = 3, } cc.KeyCodeKey = { "KEY_NONE", "KEY_PAUSE", "KEY_SCROLL_LOCK", "KEY_PRINT", "KEY_SYSREQ", "KEY_BREAK", "KEY_ESCAPE", "KEY_BACKSPACE", "KEY_TAB", "KEY_BACK_TAB", "KEY_RETURN", "KEY_CAPS_LOCK", "KEY_SHIFT", "KEY_RIGHT_SHIFT", "KEY_CTRL", "KEY_RIGHT_CTRL", "KEY_ALT", "KEY_RIGHT_ALT", "KEY_MENU", "KEY_HYPER", "KEY_INSERT", "KEY_HOME", "KEY_PG_UP", "KEY_DELETE", "KEY_END", "KEY_PG_DOWN", "KEY_LEFT_ARROW", "KEY_RIGHT_ARROW", "KEY_UP_ARROW", "KEY_DOWN_ARROW", "KEY_NUM_LOCK", "KEY_KP_PLUS", "KEY_KP_MINUS", "KEY_KP_MULTIPLY", "KEY_KP_DIVIDE", "KEY_KP_ENTER", "KEY_KP_HOME", "KEY_KP_UP", "KEY_KP_PG_UP", "KEY_KP_LEFT", "KEY_KP_FIVE", "KEY_KP_RIGHT", "KEY_KP_END", "KEY_KP_DOWN", "KEY_KP_PG_DOWN", "KEY_KP_INSERT", "KEY_KP_DELETE", "KEY_F1", "KEY_F2", "KEY_F3", "KEY_F4", "KEY_F5", "KEY_F6", "KEY_F7", "KEY_F8", "KEY_F9", "KEY_F10", "KEY_F11", "KEY_F12", "KEY_SPACE", "KEY_EXCLAM", "KEY_QUOTE", "KEY_NUMBER", "KEY_DOLLAR", "KEY_PERCENT", "KEY_CIRCUMFLEX", "KEY_AMPERSAND", "KEY_APOSTROPHE", "KEY_LEFT_PARENTHESIS", "KEY_RIGHT_PARENTHESIS", "KEY_ASTERISK", "KEY_PLUS", "KEY_COMMA", "KEY_MINUS", "KEY_PERIOD", "KEY_SLASH", "KEY_0", "KEY_1", "KEY_2", "KEY_3", "KEY_4", "KEY_5", "KEY_6", "KEY_7", "KEY_8", "KEY_9", "KEY_COLON", "KEY_SEMICOLON", "KEY_LESS_THAN", "KEY_EQUAL", "KEY_GREATER_THAN", "KEY_QUESTION", "KEY_AT", "KEY_CAPITAL_A", "KEY_CAPITAL_B", "KEY_CAPITAL_C", "KEY_CAPITAL_D", "KEY_CAPITAL_E", "KEY_CAPITAL_F", "KEY_CAPITAL_G", "KEY_CAPITAL_H", "KEY_CAPITAL_I", "KEY_CAPITAL_J", "KEY_CAPITAL_K", "KEY_CAPITAL_L", "KEY_CAPITAL_M", "KEY_CAPITAL_N", "KEY_CAPITAL_O", "KEY_CAPITAL_P", "KEY_CAPITAL_Q", "KEY_CAPITAL_R", "KEY_CAPITAL_S", "KEY_CAPITAL_T", "KEY_CAPITAL_U", "KEY_CAPITAL_V", "KEY_CAPITAL_W", "KEY_CAPITAL_X", "KEY_CAPITAL_Y", "KEY_CAPITAL_Z", "KEY_LEFT_BRACKET", "KEY_BACK_SLASH", "KEY_RIGHT_BRACKET", "KEY_UNDERSCORE", "KEY_GRAVE", "KEY_A", "KEY_B", "KEY_C", "KEY_D", "KEY_E", "KEY_F", "KEY_G", "KEY_H", "KEY_I", "KEY_J", "KEY_K", "KEY_L", "KEY_M", "KEY_N", "KEY_O", "KEY_P", "KEY_Q", "KEY_R", "KEY_S", "KEY_T", "KEY_U", "KEY_V", "KEY_W", "KEY_X", "KEY_Y", "KEY_Z", "KEY_LEFT_BRACE", "KEY_BAR", "KEY_RIGHT_BRACE", "KEY_TILDE", "KEY_EURO", "KEY_POUND", "KEY_YEN", "KEY_MIDDLE_DOT", "KEY_SEARCH", "KEY_DPAD_LEFT", "KEY_DPAD_RIGHT", "KEY_DPAD_UP", "KEY_DPAD_DOWN", "KEY_DPAD_CENTER", "KEY_ENTER", "KEY_PLAY", } cc.KeyCode = { } for k,v in ipairs(cc.KeyCodeKey) do cc.KeyCode[v] = k - 1 end cc.KeyCode.KEY_BACK = cc.KeyCode.KEY_ESCAPE cc.KeyCode.KEY_LEFT_SHIFT = cc.KeyCode.KEY_SHIFT cc.KeyCode.KEY_LEFT_CTRL = cc.KeyCode.KEY_CTRL cc.KeyCode.KEY_LEFT_ALT = cc.KeyCode.KEY_ALT cc.EventAssetsManagerEx = { EventCode = { ERROR_NO_LOCAL_MANIFEST = 0, ERROR_DOWNLOAD_MANIFEST = 1, ERROR_PARSE_MANIFEST = 2, NEW_VERSION_FOUND = 3, ALREADY_UP_TO_DATE = 4, UPDATE_PROGRESSION = 5, ASSET_UPDATED = 6, ERROR_UPDATING = 7, UPDATE_FINISHED = 8, }, } cc.AssetsManagerExStatic = { VERSION_ID = "@version", MANIFEST_ID = "@manifest", } cc.EventCode = { BEGAN = 0, MOVED = 1, ENDED = 2, CANCELLED = 3, } cc.DIRECTOR_PROJECTION_2D = 0 cc.DIRECTOR_PROJECTION_3D = 1 cc.ConfigType = { NONE = 0, COCOSTUDIO = 1, } cc.AUDIO_INVAILD_ID = -1 cc.AUDIO_TIME_UNKNOWN = -1.0 cc.CameraFlag = { DEFAULT = 1, USER1 = 2, USER2 = 4, USER3 = 8, USER4 = 16, USER5 = 32, USER6 = 64, USER7 = 128, USER8 = 256, } cc.BillBoard_Mode = { VIEW_POINT_ORIENTED = 0, VIEW_PLANE_ORIENTED = 1, } cc.GLProgram_VERTEX_ATTRIB = { POSITION = 0, COLOR = 1, TEX_COORD = 2, TEX_COORD1 = 3, TEX_COORD2 = 4, TEX_COORD3 = 5, TEX_COORD4 = 6, TEX_COORD5 = 7, TEX_COORD6 = 8, TEX_COORD7 = 9, NORMAL = 10, BLEND_WEIGHT = 11, BLEND_INDEX =12, MAX = 13, --backward compatibility TEX_COORDS = 2, } cc.MATRIX_STACK_TYPE = { MODELVIEW = 0, PROJECTION = 1, TEXTURE = 2, } cc.LightType = { DIRECTIONAL = 0, POINT = 1, SPOT = 2, AMBIENT = 3, } cc.LightFlag = { LIGHT0 = math.pow(2,0), LIGHT1 = math.pow(2,1), LIGHT2 = math.pow(2,2), LIGHT3 = math.pow(2,3), LIGHT4 = math.pow(2,4), LIGHT5 = math.pow(2,5), LIGHT6 = math.pow(2,6), LIGHT7 = math.pow(2,7), LIGHT8 = math.pow(2,8), LIGHT9 = math.pow(2,9), LIGHT10 = math.pow(2,10), LIGHT11 = math.pow(2,11), LIGHT12 = math.pow(2,12), LIGHT13 = math.pow(2,13), LIGHT14 = math.pow(2,14), LIGHT15 = math.pow(2,15), }
mit
hleuwer/luayats
examples/test-1-src.lua
1
4518
require "yats.stdlib" require "yats.core" require "yats.src" require "yats.muxdmx" require "yats.misc" -- Example test-1.lua: Derived from yats example 'tst'. -- -- cbrsrc_1 --> |\ /|--> line_1 --> sink_1 -- cbrsrc_2 --> | | | |--> line_2 --> sink_2 -- cbrsrc_3 --> | | -->| |--> line_3 --> sink_3 -- cbrsrc_4 --> | | | |--> line_4 --> sink_4 -- cbrsrc_n --> |/ \|--> line_n --> sink_n -- mux demux -- Setting test non nil provides additional output. test = true -- Show a list of loaded packages. print("Loaded packages: \n"..ptostring(_LOADED)) -- Init the yats random generator. print("Init random generator.") print("yats.sim=", pretty(yats.sim)) yats._sim:SetRand(10) -- Reset simulation time. print("Reset simulation time.") yats._sim:ResetTime() -- Use any number you like here nsrc = 6 -- Create Sources src = {} i = 1 src[i] = yats.bssrc{"src"..i, ex = 100, es = 200, delta = 2, vci = i, out = {"mux", "in"..i}} print("object '"..src[i].name.."' of class '"..(src[i].clname or "unknown").."' created.", src[i]) i = 2 src[i] = yats.cbrsrc{"src"..i, delta = 2, vci = i, out = {"mux", "in"..i}} print("object '"..src[i].name.."' of class '"..(src[i].clname or "unknown").."' created.", src[i]) i = 3 src[i] = yats.listsrc{"src"..i, ntim = 3, delta = {1,5,6}, vci = i, out = {"mux", "in"..i}} print("object '"..src[i].name.."' of class '"..(src[i].clname or "unknown").."' created.", src[i]) for i = 4, nsrc do src[i] = yats.geosrc{"src"..i, ed = 10, vci = i, out = {"mux", "in"..i}} print("object '"..src[i].name.."' of class '"..(src[i].clname or "unknown").."' created.", src[i]) end -- Create Multiplexer mx = yats.mux{"mux", ninp=nsrc, buff=10, out={"demux", "demux"}} print("object '"..mx.name.."' of class '"..(mx.clname or "unknown").."' created.", mx) -- Create Demultiplexer -- We first create the list of otputs. local dout = {} for i = 1, nsrc do dout[i] = {"line"..i, "line"} end dmx = yats.demux{"demux", maxvci = nsrc, nout = nsrc, out = dout} print("object '"..dmx.name.."' of class '"..(dmx.clname or "unknown").."' created.", dmx) -- Create Lines and Sinks lin, snk = {}, {} for i = 1, nsrc do lin[i] = yats.line{"line"..i, delay = 2, out = {"sink"..i, "sink"}} print("object '"..lin[i].name.."' of class '"..(lin[i].clname or "unknown").."' created.", lin[i]) snk[i] = yats.sink{"sink"..i} print("object '"..snk[i].name.."' of class '"..(snk[i].clname or "unknown").."' created.", snk[i]) -- Provide a routing table entry for this source dmx:signal{i,i,i} end -- Some test output if test then print(yats.sim:list("\nList of objects","\t")) print("List of objects:"..tostring(yats.sim:list())) print("\nA more detailed look on objects:") print(pretty(yats.sim.objectlist)) end -- Connection management --yats.sim:run(0,0) yats.sim:connect() -- Check connection print("Connection check:") for i = 1, nsrc do print("\tsuc of "..src[i].name..": "..src[i]:get_suc().name, src[i]:get_shand()) print("\tsuc "..i.." of "..dmx.name..": "..dmx:get_suc(i).name, dmx:get_shand(i)) print("\tsuc of "..lin[i].name..": "..lin[i]:get_suc().name, lin[i]:get_shand()) end -- Display demux switch table print("demux switch table: "..tostring(dmx:getRouting())) local st, entries st, entries = dmx:getRouting() print("Table has "..entries.." entries.") for i,v in ipairs(st) do print("(from, to, outp) = ("..v.from..", "..v.to..", "..v.outp..")") end result = {} -- Run simulation: 1. path yats.sim:run(1000000, 100000) print("Mux Queue Len: "..mx:getQLen()) table.insert(result, mx:getQLen()) -- Run simulation: 2. path (optional) yats.sim:run(1000000, 100000) -- Display some values from the Multiplexer. print("Mux Queue Len: "..mx:getQLen()) print("Mux Queue MaxLen: "..mx:getQMaxLen()) for i = 1, nsrc do print("Mux "..mx.name.." Loss "..i..": "..mx:getLoss(i).." "..mx:getLossVCI(i)) -- Note: tolua maps lua table index 1 to C index 0. -- Hence, we to add 1 to the vci index in mx.yatsobj.lostVCI[i] -- print("Mux "..mx.name.." Loss "..i..": "..mx.lost[i].." "..mx.lostVCI[i+1]) table.insert(result, mx:getLoss(i)) table.insert(result, mx:getLossVCI(i)) end -- Display source counters. for i = 1, nsrc do print("Source "..src[i].name.." couont: "..src[i]:getCounter()) table.insert(result, src[i]:getCounter()) end -- Display sink counter. for i = 1, nsrc do print("Sink "..snk[i].name.." count: "..snk[i]:getCounter()) table.insert(result, snk[i]:getCounter()) end return result
gpl-2.0
tianxiawuzhei/cocos-quick-lua
quick/framework/cc/utils/Timer.lua
19
4779
local scheduler = require(cc.PACKAGE_NAME .. ".scheduler") --[[-- Timer 实现了一个计时器容器,用于跟踪应用中所有需要计时的事件。 ]] local Timer = {} --[[-- 创建一个计时器。 **Returns:** - Timer 对象 ]] function Timer.new() local timer = {} cc(timer):addComponent("components.behavior.EventProtocol"):exportMethods() ---- local handle = nil local countdowns = {} local timecount = 0 ---- --[[-- @ignore ]] local function onTimer(dt) timecount = timecount + dt for eventName, cd in pairs(countdowns) do cd.countdown = cd.countdown - dt cd.nextstep = cd.nextstep - dt if cd.countdown <= 0 then print(string.format("[finish] %s", eventName)) timer:dispatchEvent({name = eventName, countdown = 0}) timer:removeCountdown(eventName) elseif cd.nextstep <= 0 then print(string.format("[step] %s", eventName)) cd.nextstep = cd.nextstep + cd.interval timer:dispatchEvent({name = eventName, countdown = cd.countdown}) end end end ---- --[[-- 添加一个计时器。 在计时器倒计时完成前,会按照 **interval** 参数指定的时间间隔触发 **eventName** 参数指定的事件。 事件参数则是倒计时还剩余的时间。 在计时器倒计时完成后,同样会触发 **eventName** 参数指定的事件。此时事件的参数是 0,表示倒计时完成。 因此在事件处理函数中,可以通过事件参数判断倒计时是否已经结束: local Timer = require("framework.cc.utils.Timer") local appTimer = Timer.new() -- 响应 CITYHALL_UPGRADE_TIMER 事件 local function onCityHallUpgradeTimer(event) if event.countdown > 0 then -- 倒计时还未结束,更新用户界面上显示的时间 .... else -- 倒计时已经结束,更新用户界面显示升级后的城防大厅 end end -- 注册事件 appTimer:addEventListener("CITYHALL_UPGRADE_TIMER", onCityHallUpgradeTimer) -- 城防大厅升级需要 3600 秒,每 30 秒更新一次界面显示 appTimer:addCountdown("CITYHALL_UPGRADE_TIMER", 3600, 30) 考虑移动设备的特殊性,计时器可能存在一定误差,所以 **interval** 参数的最小值是 2 秒。 在界面上需要显示倒计时的地方,应该以“分”为单位。例如显示为“2 小时 23 分”,这样可以避免误差带来的问题。 ### 注意 计时器在倒计时结束并触发事件后,会自动删除。关联到这个计时器的所有事件处理函数也会被取消。 **Parameters:** - eventName: 计时器事件的名称 - countdown: 倒计时(秒) - interval(可选): 检查倒计时的时间间隔,最小为 2 秒,最长为 120 秒,如果未指定则默认为 30 秒 ]] function timer:addCountdown(eventName, countdown, interval) eventName = tostring(eventName) assert(not countdowns[eventName], "eventName '" .. eventName .. "' exists") assert(type(countdown) == "number" and countdown >= 30, "invalid countdown") if type(interval) ~= "number" then interval = 30 else interval = math.floor(interval) if interval < 2 then interval = 2 elseif interval > 120 then interval = 120 end end countdowns[eventName] = { countdown = countdown, interval = interval, nextstep = interval, } end --[[-- 删除指定事件名称对应的计时器,并取消这个计时器的所有事件处理函数。 **Parameters:** - eventName: 计时器事件的名称 ]] function timer:removeCountdown(eventName) eventName = tostring(eventName) countdowns[eventName] = nil self:removeEventListenersByEvent(eventName) end --[[-- 启动计时器容器。 在开始游戏时调用这个方法,确保所有的计时器事件都正确触发。 ]] function timer:start() if not handle then handle = scheduler.scheduleGlobal(onTimer, 1.0, false) end end --[[-- 停止计时器容器。 ]] function timer:stop() if handle then scheduler.unscheduleGlobal(handle) handle = nil end end return timer end cc = cc or {} cc.utils = cc.utils or {} cc.utils.Timer = Timer return Timer
mit
robert00s/koreader
frontend/optmath.lua
5
1502
--[[-- Simple math helper functions ]] local Math = {} function Math.roundAwayFromZero(num) if num > 0 then return math.ceil(num) else return math.floor(num) end end function Math.round(num) return math.floor(num + 0.5) end function Math.oddEven(number) if number % 2 == 1 then return "odd" else return "even" end end local function tmin_max(tab, func, op) if #tab == 0 then return nil, nil end local index, value = 1, tab[1] for i = 2, #tab do if func then if func(value, tab[i]) then index, value = i, tab[i] end elseif op == "min" then if value > tab[i] then index, value = i, tab[i] end elseif op == "max" then if value < tab[i] then index, value = i, tab[i] end end end return index, value end --[[-- Returns the minimum element of a table. The optional argument func specifies a one-argument ordering function. @tparam table tab @tparam func func @treturn dynamic minimum element of a table ]] function Math.tmin(tab, func) return tmin_max(tab, func, "min") end --[[-- Returns the maximum element of a table. The optional argument func specifies a one-argument ordering function. @tparam table tab @tparam func func @treturn dynamic maximum element of a table ]] function Math.tmax(tab, func) return tmin_max(tab, func, "max") end return Math
agpl-3.0
robert00s/koreader
frontend/device/android/device.lua
2
1671
local Generic = require("device/generic/device") local _, android = pcall(require, "android") local ffi = require("ffi") local logger = require("logger") local function yes() return true end local function no() return false end local Device = Generic:new{ model = "Android", hasKeys = yes, hasDPad = no, isAndroid = yes, hasFrontlight = yes, firmware_rev = "none", display_dpi = ffi.C.AConfiguration_getDensity(android.app.config), } function Device:init() self.screen = require("ffi/framebuffer_android"):new{device = self, debug = logger.dbg} self.powerd = require("device/android/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = require("device/android/event_map"), handleMiscEv = function(this, ev) logger.dbg("Android application event", ev.code) if ev.code == ffi.C.APP_CMD_SAVE_STATE then return "SaveState" elseif ev.code == ffi.C.APP_CMD_GAINED_FOCUS then this.device.screen:refreshFull() elseif ev.code == ffi.C.APP_CMD_WINDOW_REDRAW_NEEDED then this.device.screen:refreshFull() end end, } -- check if we have a keyboard if ffi.C.AConfiguration_getKeyboard(android.app.config) == ffi.C.ACONFIGURATION_KEYBOARD_QWERTY then self.hasKeyboard = yes end -- check if we have a touchscreen if ffi.C.AConfiguration_getTouchscreen(android.app.config) ~= ffi.C.ACONFIGURATION_TOUCHSCREEN_NOTOUCH then self.isTouchDevice = yes end Generic.init(self) end return Device
agpl-3.0
stanfordhpccenter/soleil-x
testcases/legacy/taylor_green_vortex/taylor_green_vortex_particles.lua
1
4674
-- This is a Lua config file for the Soleil code. -- This defines the 64^3 TaylorGreen Vortex problem w/out particles or radiation return { ----------------------------------------------------------- ----------------------------------------------------------- -- Options of interest for Liszt/Legion tests -- completely disable particles, including all data modeParticles = 'ON', -- Number of particles (initially distributed one per cell), 0 turns off num = 10000, -- grid size control to add compute load xnum = 32, -- number of cells in the x-direction ynum = 32, -- number of cells in the y-direction znum = 32, -- number of cells in the z-direction -- I/O control (OFF/ON). Set all to 'OFF' to completely disable I/O. -- frequency/output location is controlled below wrtRestart = 'ON', wrtVolumeSolution = 'ON', wrt1DSlice = 'ON', wrtParticleEvolution = 'ON', -- set a fixed number of iterations max_iter = 100000, -- force a fixed time step to avoid global comms. -- decrease if calculation diverges right away delta_time = 1e-2, -- console writing frequency. Set to a large number, i.e., larger than -- the number of specified iterations to avoid reductions/global comms -- to compute statistics and other outputs consoleFrequency = 1, -- Iterations between console output of statistics ----------------------------------------------------------- ----------------------------------------------------------- -- Flow Initialization Options -- initCase = 'TaylorGreen3DVortex', -- Uniform, Restart, TaylorGreen2DVortex, TaylorGreen3DVortex initParams = {1,100,2,0.0,0.0}, -- for TGV: first three are density, pressure, velocity bodyForce = {0,0.0,0}, -- body force in x, y, z turbForcing = 'OFF', -- Turn turbulent forcing on or off turbForceCoeff = 0.0, -- Turbulent linear forcing coefficient (f = A*rho*u) restartIter = 10000, -- Grid Options -- PERIODICITY origin = {0.0, 0.0, 0.0}, -- spatial origin of the computational domain xWidth = 6.283185307179586, yWidth = 6.283185307179586, zWidth = 6.283185307179586, -- BCs: 'periodic,' 'symmetry,' 'adiabatic_wall,' or 'isothermal_wall' xBCLeft = 'periodic', xBCLeftVel = {0.0, 0.0, 0.0}, xBCLeftTemp = 0.0, xBCRight = 'periodic', xBCRightVel = {0.0, 0.0, 0.0}, xBCRightTemp = 0.0, yBCLeft = 'periodic', yBCLeftVel = {0.0, 0.0, 0.0}, yBCLeftTemp = 0.0, yBCRight = 'periodic', yBCRightVel = {0.0, 0.0, 0.0}, yBCRightTemp = 0.0, zBCLeft = 'periodic', zBCLeftVel = {0.0, 0.0, 0.0}, zBCLeftTemp = 0.0, zBCRight = 'periodic', zBCRightVel = {0.0, 0.0, 0.0}, zBCRightTemp = 0.0, --Time Integration Options -- final_time = 20.00001, cfl = -2.0, -- Negative CFL implies that we will used fixed delta T --- File Output Options -- particleEvolutionIndex = 0, outputEveryTimeSteps = 50, restartEveryTimeSteps = 50, headerFrequency = 20, outputFormat = 'Tecplot', -- Only 'Tecplot' is currently available -- Fluid Options -- gasConstant = 20.4128, gamma = 1.4, prandtl = 0.7, viscosity_model = 'PowerLaw', -- 'Constant', 'PowerLaw', or 'Sutherland' constant_visc = 1.0e-3, -- Value for a constant viscosity [kg/m/s] powerlaw_visc_ref = 0.00044, -- Power-law reference viscosity [kg/m/s] powerlaw_temp_ref = 1.0, -- Power-law reference temperature [K] suth_visc_ref = 1.716E-5, -- Sutherland's Law reference viscosity [kg/m/s] suth_temp_ref = 273.15, -- Sutherland's Law reference temperature [K] suth_s_ref = 110.4, -- Sutherland's Law S constant [K] -- Particle Options -- initParticles = 'Uniform', -- 'Uniform', 'Random', or 'Restart' restartParticleIter = 0, particleType = 'Free', -- Fixed or Free twoWayCoupling = 'OFF', -- ON or OFF maximum_num = 10000, -- upper bound on particles with insertion insertion_rate = 0, -- per face and per time step insertion_mode = {0,0,0,0,0,0}, --bool, MinX MaxX MinY MaxY MinZ MaxZ deletion_mode = {0,0,0,0,0,0}, --bool, MinX MaxX MinY MaxY MinZ MaxZ restitutionCoefficient = 1.0, convectiveCoefficient = 0.7, -- W m^-2 K^-1 heatCapacity = 0.7, -- J Kg^-1 K^-1 initialTemperature = 20, -- K density = 8900, -- kg/m^3 diameter_mean = 5e-3, -- m diameter_maxDeviation = 1e-3, -- m, for statistical distribution bodyForceParticles = {0.0,0.0,0.0}, absorptivity = 1.0, -- Equal to emissivity in thermal equilibrium -- (Kirchhoff law of thermal radiation) -- Radiation Options -- radiationType = 'OFF', -- ON or OFF radiationIntensity = 1e3, zeroAvgHeatSource = 'OFF' }
gpl-2.0
dschoeffm/MoonGen
rfc2544/utils/manual.lua
9
2056
local mod = {} mod.__index = mod local namespaces = require "namespaces" local ns = namespaces.get() function confirm() local answer repeat io.write("continue (y/n)? ") answer = io.read() until answer == "y" or answer == "n" return answer == "y" and 0 or -1 end function mod.addInterfaceIP(interface, ip, pfx) io.write(string.format("configure: add to interface %s ip %s/%d", interface, ip, pfx)) return confirm() end function mod.delInterfaceIP(interface, ip, pfx) io.write(string.format("configure: delete from interface %s ip %s/%d", interface, ip, pfx)) return confirm() end function mod.clearIPFilters() io.write("configure: clear IP Filters") return confirm() end function mod.addIPFilter(src, sPfx, dst, dPfx) io.write(string.format("configure: add ip filter from %s/%d to %s/%d", src, sPfx, dst, dPfx)) return confirm() end function mod.delIPFilter(src, sPfx, dst, dPfx) io.write(string.format("configure: delete ip filter from %s/%d to %s/%d", src, sPfx, dst, dPfx)) return confirm() end function mod.clearIPRoutes() io.write("configure: clear IP Routes") return confirm() end function mod.addIPRoute(dst, pfx, gateway, interface) io.write(string.format("configure: add route to %s/%d via %s dev %s", dst, pfx, gateway, interface)) return confirm() end function mod.delIPRoute(dst, pfx, gateway, interface) io.write(string.format("configure: delte route to %s/%d via %s dev %s", dst, pfx, gateway, interface)) return confirm() end function mod.getIPRouteCount() io.write("configure: get ip route count: ") return tonumber(io.read()) end function mod.getDeviceName() if type(ns.deviceName) ~= string then io.write("configure: get device name: ") ns.deviceName = io.read() end return ns.deviceName end function mod.getDeviceOS() if type(ns.deviceOS) ~= string then io.write("configure: get device OS: ") ns.deviceOS = io.read() end return ns.deviceOS end return mod
mit
wrxck/mattata
plugins/administration/setgrouplang.lua
2
5769
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local setgrouplang = {} local mattata = require('mattata') local redis = require('libs.redis') local json = require('dkjson') function setgrouplang:init() setgrouplang.commands = mattata.commands(self.info.username):command('setgrouplang').table setgrouplang.help = '/setgrouplang - Allows you to force mattata to respond to all members of the current chat in the selected language.' end setgrouplang.languages = { ['ar_ar'] = 'Arabic 🇸🇦', ['en_gb'] = 'British English 🇬🇧', ['en_us'] = 'American English 🇺🇸', ['de_de'] = 'Deutsch 🇩🇪', ['scottish'] = 'Scottish 🏴󠁧󠁢󠁳󠁣󠁴󠁿', ['pl_pl'] = 'Polski 🇵🇱', ['pt_br'] = 'Português do Brasil 🇧🇷', ['pt_pt'] = 'Português 🇵🇹', ['tr_tr'] = 'Türkçe 🇹🇷' } setgrouplang.languages_short = { ['ar_ar'] = '🇸🇦', ['en_gb'] = '🇬🇧', ['en_us'] = '🇺🇸', ['de_de'] = '🇩🇪', ['scottish'] = '🏴', ['pl_pl'] = '🇵🇱', ['pt_br'] = '🇧🇷', ['pt_pt'] = '🇵🇹', ['tr_tr'] = '🇹🇷' } function setgrouplang.get_keyboard(chat_id, language) local keyboard = { ['inline_keyboard'] = { {} } } local total = 0 for _, v in pairs(setgrouplang.languages_short) do total = total + 1 end local count = 0 local rows = math.floor(total / 2) if rows ~= total then rows = rows + 1 end local row = 1 for k, v in pairs(setgrouplang.languages_short) do count = count + 1 if count == rows * row then row = row + 1 table.insert( keyboard.inline_keyboard, {} ) end table.insert( keyboard.inline_keyboard[row], { ['text'] = v, ['callback_data'] = 'setgrouplang:' .. chat_id .. ':' .. k } ) end table.insert( keyboard.inline_keyboard, { { ['text'] = language['setgrouplang']['5'], ['callback_data'] = 'administration:' .. chat_id .. ':force_group_language' } } ) return keyboard end function setgrouplang.set_lang(chat_id, locale, lang, language) redis:hset( 'chat:' .. chat_id .. ':info', 'group language', locale ) return string.format( language['setgrouplang']['1'], lang ) end function setgrouplang.get_lang(chat_id, language) local lang = mattata.get_value( chat_id, 'group language' ) or 'en_gb' for k, v in pairs(setgrouplang.languages) do if k == lang then lang = v break end end return string.format( language['setgrouplang']['2'], lang ) end function setgrouplang:on_callback_query(callback_query, message, configuration, language) if not message or ( message and message.date <= 1493668000 ) then return -- We don't want to process requests from messages before the language -- functionality was re-implemented, it could cause issues! elseif not mattata.is_group_admin( message.chat.id, callback_query.from.id ) then return mattata.answer_callback_query( callback_query.id, language['errors']['admin'] ) end local chat_id, new_language = callback_query.data:match('^(.-)%:(.-)$') if not chat_id or not new_language or tostring(message.chat.id) ~= chat_id then return elseif not mattata.get_setting( message.chat.id, 'force group language' ) then redis:hset( 'chat:' .. message.chat.id .. ':settings', 'force group language', true ) end return mattata.edit_message_text( message.chat.id, message.message_id, setgrouplang.set_lang( chat_id, new_language, setgrouplang.languages[new_language], language ), nil, true, setgrouplang.get_keyboard( chat_id, language ) ) end function setgrouplang:on_message(message, configuration, language) if not mattata.is_group_admin( message.chat.id, message.from.id ) then return mattata.send_reply( message, language['errors']['admin'] ) elseif message.chat.type ~= 'supergroup' then return mattata.send_reply( message, language['errors']['supergroup'] ) end if not mattata.get_setting( message.chat.id, 'force group language' ) then return mattata.send_message( message.chat.id, language['setgrouplang']['3'], nil, true, false, nil, mattata.inline_keyboard():row( mattata.row():callback_data_button( language['setgrouplang']['4'], 'administration:' .. message.chat.id .. ':force_group_language' ) ) ) end return mattata.send_message( message.chat.id, setgrouplang.get_lang( message.chat.id, language ), nil, true, false, nil, setgrouplang.get_keyboard( message.chat.id, language ) ) end return setgrouplang
mit
rickvanbodegraven/nodemcu-firmware
lua_modules/bmp085/bmp085.lua
69
5037
-------------------------------------------------------------------------------- -- BMP085 I2C module for NODEMCU -- NODEMCU TEAM -- LICENCE: http://opensource.org/licenses/MIT -- Christee <Christee@nodemcu.com> -------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M --default value for i2c communication local id=0 --default oversampling setting local oss = 0 --CO: calibration coefficients table. local CO = {} -- read reg for 1 byte local function read_reg(dev_addr, reg_addr) i2c.start(id) i2c.address(id, dev_addr ,i2c.TRANSMITTER) i2c.write(id,reg_addr) i2c.stop(id) i2c.start(id) i2c.address(id, dev_addr,i2c.RECEIVER) local c=i2c.read(id,1) i2c.stop(id) return c end --write reg for 1 byte local function write_reg(dev_addr, reg_addr, reg_val) i2c.start(id) i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.write(id, reg_addr) i2c.write(id, reg_val) i2c.stop(id) end --get signed or unsigned 16 --parameters: --reg_addr: start address of short --signed: if true, return signed16 local function getShort(reg_addr, signed) local tH = string.byte(read_reg(0x77, reg_addr)) local tL = string.byte(read_reg(0x77, (reg_addr + 1))) local temp = tH*256 + tL if (temp > 32767) and (signed == true) then temp = temp - 65536 end return temp end -- initialize i2c --parameters: --d: sda --l: scl function M.init(d, l) if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then sda = d scl = l else print("iic config failed!") return nil end print("init done") i2c.setup(id, sda, scl, i2c.SLOW) --get calibration coefficients. CO.AC1 = getShort(0xAA, true) CO.AC2 = getShort(0xAC, true) CO.AC3 = getShort(0xAE, true) CO.AC4 = getShort(0xB0) CO.AC5 = getShort(0xB2) CO.AC6 = getShort(0xB4) CO.B1 = getShort(0xB6, true) CO.B2 = getShort(0xB8, true) CO.MB = getShort(0xBA, true) CO.MC = getShort(0xBC, true) CO.MD = getShort(0xBE, true) end --get temperature from bmp085 --parameters: --num_10x: bool value, if true, return number of 0.1 centi-degree -- default value is false, which return a string , eg: 16.7 function M.getUT(num_10x) write_reg(0x77, 0xF4, 0x2E); tmr.delay(10000); local temp = getShort(0xF6) local X1 = (temp - CO.AC6) * CO.AC5 / 32768 local X2 = CO.MC * 2048/(X1 + CO.MD) local r = (X2 + X1 + 8)/16 if(num_10x == true) then return r else return ((r/10).."."..(r%10)) end end --get raw data of pressure from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getUP_raw(oss) local os = 0 if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then os = oss end local ov = os * 64 write_reg(0x77, 0xF4, (0x34 + ov)); tmr.delay(30000); --delay 30ms, according to bmp085 document, wait time are: -- 4.5ms 7.5ms 13.5ms 25.5ms respectively according to oss 0,1,2,3 local MSB = string.byte(read_reg(0x77, 0xF6)) local LSB = string.byte(read_reg(0x77, 0xF7)) local XLSB = string.byte(read_reg(0x77, 0xF8)) local up_raw = (MSB*65536 + LSB *256 + XLSB)/2^(8 - os) return up_raw end --get calibrated data of pressure from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getUP(oss) local os = 0 if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then os = oss end local raw = M.getUP_raw(os) local B5 = M.getUT(true) * 16 - 8; local B6 = B5 - 4000 local X1 = CO.B2 * (B6 * B6 /4096)/2048 local X2 = CO.AC2 * B6 / 2048 local X3 = X1 + X2 local B3 = ((CO.AC1*4 + X3)*2^os + 2)/4 X1 = CO.AC3 * B6 /8192 X2 = (CO.B1 * (B6 * B6 / 4096))/65536 X3 = (X1 + X2 + 2)/4 local B4 = CO.AC4 * (X3 + 32768) / 32768 local B7 = (raw -B3) * (50000/2^os) local p = B7/B4 * 2 X1 = (p/256)^2 X1 = (X1 *3038)/65536 X2 = (-7357 *p)/65536 p = p +(X1 + X2 + 3791)/16 return p end --get estimated data of altitude from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getAL(oss) --Altitudi can be calculated by pressure refer to sea level pressure, which is 101325 --pressure changes 100pa corresponds to 8.43m at sea level return (M.getUP(oss) - 101325)*843/10000 end return M
mit
TimVonsee/hammerspoon
extensions/location/init.lua
13
7506
--- === hs.location === --- --- Determine the machine's location and useful information about that location local location = require("hs.location.internal") local internal = {} internal.__callbacks = {} --- hs.location.register(tag, fn[, distance]) --- Function --- Registers a callback function to be called when the system location is updated --- --- Parameters: --- * tag - A string containing a unique tag, used to identify the callback later --- * fn - A function to be called when the system location is updated. The function should accept a single argument, which will be a table containing the same data as is returned by `hs.location.get()` --- * distance - An optional number containing the minimum distance in meters that the system should have moved, before calling the callback. Defaults to 0 --- --- Returns: --- * None location.register = function(tag, fn, distance) if internal.__callbacks[tag] then error("Callback tag '"..tag.."' already registered for hs.location.", 2) else internal.__callbacks[tag] = { fn = fn, distance = distance, last = { latitude = 0, longitude = 0, timestamp = 0, } } end end --- hs.location.unregister(tag) --- Function --- Unregisters a callback --- --- Parameters: --- * tag - A string containing the unique tag a callback was registered with --- --- Returns: --- * None location.unregister = function(tag) internal.__callbacks[tag] = nil end -- Set up callback dispatcher internal.__dispatch = function() local locationNow = location.get() for tag, callback in pairs(internal.__callbacks) do if not(callback.distance and location.distance(locationNow, callback.last) < callback.distance) then callback.last = { latitude = locationNow.latitude, longitude = locationNow.longitude, timestamp = locationNow.timestamp } callback.fn(locationNow) end end -- print("Proof of concept: ",hs.inspect(location.get())) end -- -------- Functions related to sunrise/sunset times ----------------- local rad = math.rad local deg = math.deg local floor = math.floor local frac = function(n) return n - floor(n) end local cos = function(d) return math.cos(rad(d)) end local acos = function(d) return deg(math.acos(d)) end local sin = function(d) return math.sin(rad(d)) end local asin = function(d) return deg(math.asin(d)) end local tan = function(d) return math.tan(rad(d)) end local atan = function(d) return deg(math.atan(d)) end local function fit_into_range(val, min, max) local range = max - min local count if val < min then count = floor((min - val) / range) + 1 return val + count * range elseif val >= max then count = floor((val - max) / range) + 1 return val - count * range else return val end end local function day_of_year(date) local n1 = floor(275 * date.month / 9) local n2 = floor((date.month + 9) / 12) local n3 = (1 + floor((date.year - 4 * floor(date.year / 4) + 2) / 3)) return n1 - (n2 * n3) + date.day - 30 end local function sunturn_time(date, rising, latitude, longitude, zenith, local_offset) local n = day_of_year(date) -- Convert the longitude to hour value and calculate an approximate time local lng_hour = longitude / 15 local t if rising then -- Rising time is desired t = n + ((6 - lng_hour) / 24) else -- Setting time is desired t = n + ((18 - lng_hour) / 24) end -- Calculate the Sun's mean anomaly local M = (0.9856 * t) - 3.289 -- Calculate the Sun's true longitude local L = fit_into_range(M + (1.916 * sin(M)) + (0.020 * sin(2 * M)) + 282.634, 0, 360) -- Calculate the Sun's right ascension local RA = fit_into_range(atan(0.91764 * tan(L)), 0, 360) -- Right ascension value needs to be in the same quadrant as L local Lquadrant = floor(L / 90) * 90 local RAquadrant = floor(RA / 90) * 90 RA = RA + Lquadrant - RAquadrant -- Right ascension value needs to be converted into hours RA = RA / 15 -- Calculate the Sun's declination local sinDec = 0.39782 * sin(L) local cosDec = cos(asin(sinDec)) -- Calculate the Sun's local hour angle local cosH = (cos(zenith) - (sinDec * sin(latitude))) / (cosDec * cos(latitude)) if rising and cosH > 1 then return "N/R" -- The sun never rises on this location on the specified date elseif cosH < -1 then return "N/S" -- The sun never sets on this location on the specified date end -- Finish calculating H and convert into hours local H if rising then H = 360 - acos(cosH) else H = acos(cosH) end H = H / 15 -- Calculate local mean time of rising/setting local T = H + RA - (0.06571 * t) - 6.622 -- Adjust back to UTC local UT = fit_into_range(T - lng_hour, 0, 24) -- Convert UT value to local time zone of latitude/longitude local LT = UT + local_offset return os.time({ day = date.day, month = date.month, year = date.year, hour = floor(LT), min = frac(LT) * 60}) end --- hs.location.sunrise(latitude, longitude, offset[, date]) -> number or string --- Function --- Returns the time of official sunrise for the supplied location --- --- Parameters: --- * latitude - A number containing a latitude --- * longitude - A number containing a longitude --- * offset - A number containing the offset from UTC (in hours) for the given latitude/longitude --- * date - An optional table containing date information (equivalent to the output of ```os.date("*t")```). Defaults to the current date --- --- Returns: --- * A number containing the time of sunrise (represented as seconds since the epoch) for the given date. If no date is given, the current date is used. If the sun doesn't rise on the given day, the string "N/R" is returned. --- --- Notes: --- * You can turn the return value into a more useful structure, with ```os.date("*t", returnvalue)``` location.sunrise = function (lat, lon, offset, date) local zenith = 90.83 if not date then date = os.date("*t") end return sunturn_time(date, true, lat, lon, zenith, offset) end --- hs.location.sunset(latitude, longitude, offset[, date]) -> number or string --- Function --- Returns the time of official sunset for the supplied location --- --- Parameters: --- * latitude - A number containing a latitude --- * longitude - A number containing a longitude --- * offset - A number containing the offset from UTC (in hours) for the given latitude/longitude --- * date - An optional table containing date information (equivalent to the output of ```os.date("*t")```). Defaults to the current date --- --- Returns: --- * A number containing the time of sunset (represented as seconds since the epoch) for the given date. If no date is given, the current date is used. If the sun doesn't set on the given day, the string "N/S" is returned. --- --- Notes: --- * You can turn the return value into a more useful structure, with ```os.date("*t", returnvalue)``` location.sunset = function (lat, lon, offset, date) local zenith = 90.83 if not date then date = os.date("*t") end return sunturn_time(date, false, lat, lon, zenith, offset) end local meta = getmetatable(location) meta.__index = function(_, key) return internal[key] end setmetatable(location, meta) return location
mit
amirsafa/bot-superGps
plugins/weather.lua
29
1436
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b' url = url..'&units=metric' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'دمای شهر '..city..' هم اکنون '..weather.main.temp..' درجه سانتی گراد می باشد' local conditions = 'شرایط فعلی آب و هوا : ' if weather.weather[1].main == 'Clear' then conditions = conditions .. 'آفتابی ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. 'ابری ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. 'بارانی ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. 'طوفانی ☔☔☔☔' elseif weather.weather[1].main == 'Mist' then conditions = conditions .. 'مه 💨' end return temp .. '\n' .. conditions end local function run(msg, matches) city = matches[1] local wtext = get_weather(city) if not wtext then wtext = 'مکان وارد شده صحیح نیست' end return wtext end return { patterns = { "^#weather (.*)$", }, run = run }
gpl-2.0
rickvanbodegraven/nodemcu-firmware
lua_modules/ds3231/ds3231-web.lua
84
1338
require('ds3231') port = 80 -- ESP-01 GPIO Mapping gpio0, gpio2 = 3, 4 days = { [1] = "Sunday", [2] = "Monday", [3] = "Tuesday", [4] = "Wednesday", [5] = "Thursday", [6] = "Friday", [7] = "Saturday" } months = { [1] = "January", [2] = "Febuary", [3] = "March", [4] = "April", [5] = "May", [6] = "June", [7] = "July", [8] = "August", [9] = "September", [10] = "October", [11] = "November", [12] = "December" } ds3231.init(gpio0, gpio2) srv=net.createServer(net.TCP) srv:listen(port, function(conn) second, minute, hour, day, date, month, year = ds3231.getTime() prettyTime = string.format("%s, %s %s %s %s:%s:%s", days[day], date, months[month], year, hour, minute, second) conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" .. "<!DOCTYPE HTML>" .. "<html><body>" .. "<b>ESP8266</b></br>" .. "Time and Date: " .. prettyTime .. "<br>" .. "Node ChipID : " .. node.chipid() .. "<br>" .. "Node MAC : " .. wifi.sta.getmac() .. "<br>" .. "Node Heap : " .. node.heap() .. "<br>" .. "Timer Ticks : " .. tmr.now() .. "<br>" .. "</html></body>") conn:on("sent",function(conn) conn:close() end) end )
mit
feiltom/domoticz
scripts/dzVents/runtime/HistoricalStorage.lua
3
11178
local Time = require('Time') local MAXLIMIT = 100 local utils = require('Utils') if (_G.TESTMODE) then MAXLIMIT = 10 end local function setIterators(object, collection) local res object['forEach'] = function(func) for i, item in ipairs(collection) do res = func(item, i, collection) if (res == false) then -- abort return end end end object['reduce'] = function(func, accumulator) for i, item in ipairs(collection) do accumulator = func(accumulator, item, i, collection) end return accumulator end object['find'] = function(func, direction) local stop = false local from, to if (direction == -1) then from = #collection -- last index in table to = 1 else direction = 1 -- to be sure from = 1 to = #collection end for i = from, to, direction do local item = collection[i] stop = func(item, i, collection) if (stop) then return item, i end end return nil, nil end object['filter'] = function(filter) local res = {} for i, item in ipairs(collection) do if (filter(item, i, collection)) then res[i] = item end end setIterators(res, res) return res end end local function HistoricalStorage(data, maxItems, maxHours, maxMinutes, getData) -- IMPORTANT: data must be time-stamped in UTC format local newAdded = false if (maxItems == nil or maxItems > MAXLIMIT) then maxItems = MAXLIMIT end -- maybe we should make a limit anyhow in the number of items local self = { newData = nil, storage = {} -- youngest first, oldest last } -- setup our internal list of history items -- already pruned to the bounds as set by maxItems and/or maxHours maxMinutes = maxMinutes and maxMinutes or 0 maxHours = maxHours and maxHours or 0 maxMinutes = maxMinutes + maxHours * 60 if (data == nil) then self.storage = {} self.size = 0 else -- transfer to self -- that way we can easily prune or ditch based -- on maxItems and/or maxHours local count = 0 for i, sample in ipairs(data) do local t = Time(sample.time, true) -- UTC if (count < maxItems) then local add = true if (maxMinutes > 0 and t.minutesAgo>maxMinutes) then add = false end if (add) then table.insert(self.storage, { time = t, data = sample.data }) count = count + 1 end end end self.size = count end -- extend with filter and forEach setIterators(self, self.storage) local function getSecondsAgo(t) local hoursAgo, minsAgo, secsAgo = string.match(t, "(%d+):(%d+):(%d+)") secsAgo = secsAgo~=nil and secsAgo or 0 minsAgo = minsAgo~=nil and minsAgo or 0 hoursAgo = hoursAgo~=nil and hoursAgo or 0 return hoursAgo*3600 + minsAgo*60 + secsAgo end function self.subset(from, to, _setIterators) local res = {} local skip = false local len = 0 if (from == nil or from < 1 ) then from = 1 end if (from and from > self.size) then skip = true end if (to and from and to < from) then skip = true end if (to==nil or to > self.size) then to = self.size end if (not skip) then for i = from, to do table.insert(res, self.storage[i]) len = len + 1 end end if(_setIterators or _setIterators==nil) then setIterators(res, res) end return res, len end function self.subsetSince(timeAgo, _setIterators) local totalSecsAgo = getSecondsAgo(timeAgo) local res = {} local len = 0 for i = 1, self.size do if (self.storage[i].time.secondsAgo<=totalSecsAgo) then table.insert(res, self.storage[i]) len = len + 1 end end if(_setIterators or _setIterators==nil) then setIterators(res, res) end return res, len end function self._getForStorage() -- create a new table with string time stamps local res = {} self.forEach(function(item) table.insert(res,{ time = item.time.raw, data = item.data }) end) return res end function self.setNew(data) utils.log('setNew is deprecated. Please use add().', utils.LOG_INFO) self.add(data) end function self.add(data) -- see if we have reached the limit -- the oldest item like still fals within the range of maxMinutes/maxHours if (self.size == maxItems) then -- drop the last item table.remove(self.storage) self.size = self.size - 1 end -- add the new one local t = Time(os.date('!%Y-%m-%d %H:%M:%S'), true) table.insert(self.storage, 1, { time = t, data = data }) self.size = self.size + 1 end function self.getNew() utils.log('getNew is deprecated. Please use getLatest().', utils.LOG_INFO) return self.getLatest() end function self.get(itemsAgo) local item = self.storage[itemsAgo] if (item == nil) then return nil else return item end end function self.getAtTime(timeAgo) -- find the item closest to minsAgo+hoursAgo local totalSecsAgo = getSecondsAgo(timeAgo) local res = {} for i = 1, self.size do if (self.storage[i].time.secondsAgo > totalSecsAgo) then if (i>1) then local deltaWithPrevious = totalSecsAgo - self.storage[i-1].time.secondsAgo local deltaWithCurrent = self.storage[i].time.secondsAgo - totalSecsAgo if (deltaWithPrevious < deltaWithCurrent) then -- the previous one was closer to the time we were looking for return self.storage[i-1], i-1 else return self.storage[i], i end else return self.storage[i], i end end end return nil, nil end function self.getLatest() return self.get(1) end function self.getOldest() return self.get(self.size) end function self.reset() for k, v in pairs(self.storage) do self.storage[k] = nil end self.size = 0 self.newData = nil end local function _getItemData(item) if (type(getData) == 'function') then local ok, res = pcall(getData, item) if (ok) then if (type(res) == 'number') then return res else utils.log('Return value for getData function is not a number: ' .. tostring(res), utils.LOG_ERROR) return nil end else utils.log('getData function returned an error. ' .. tostring(res), utils.LOG_ERROR) end else if (type(item.data) == 'number') then return item.data else utils.log('Item data is not a number type. Type is ' .. type(res), utils.LOG_ERROR) return nil end end end local function _sum(items) local count = 0 local sum = items.reduce(function(acc, item) local val = _getItemData(item) if (val == nil) then return nil end count = count + 1 return acc + val end, 0) return sum, count end local function _avg(items) local sum, count = _sum(items) return sum/count end function self.avg(from, to, default) local subset, length = self.subset(from, to) if (length == 0) then return default else return _avg(subset) end end function self.avgSince(timeAgo, default) local subset, length = self.subsetSince(timeAgo) if (length == 0) then return default else return _avg(subset) end end local function _min(items) local itm = nil local min = items.reduce(function(acc, item) local val = _getItemData(item) if (val == nil) then return nil end if (acc == nil) then acc = val itm = item else if (val < acc) then acc = val itm = item end end return acc end, nil) return min, itm end function self.min(from, to) local subset, length = self.subset(from, to) if (length == 0) then return nil, nil else return _min(subset) end end function self.minSince(timeAgo) local subset, length = self.subsetSince(timeAgo) if (length==0) then return nil, nil else return _min(subset) end end local function _max(items) local itm local max = items.reduce(function(acc, item) local val = _getItemData(item) if (val == nil) then return nil end if (acc == nil) then acc = val itm = item else if (val > acc) then acc = val itm = item end end return acc end, nil) return max, itm end function self.max(from, to) local subset, length = self.subset(from, to) if (length==0) then return nil, nil else return _max(subset) end end function self.maxSince(timeAgo) local subset, length = self.subsetSince(timeAgo) if (length==0) then return nil, nil else return _max(subset) end end function self.sum(from, to) local subset, length = self.subset(from, to) if (length==0) then return nil else return _sum(subset) end end function self.sumSince(timeAgo) local subset, length = self.subsetSince(timeAgo) if (length==0) then return nil else return _sum(subset) end end function self.smoothItem(itemIndex, smoothRange) if (itemIndex<1 or itemIndex > self.size) then return nil end if (smoothRange == nil or smoothRange < 0) then smoothRange = 0 end if (smoothRange == 0) then if (itemIndex >= 1 and itemIndex <= self.size) then return _getItemData(self.storage[itemIndex]) else return nil end end local from, to if ((itemIndex - smoothRange)< 1) then from = 1 else from = itemIndex - smoothRange end if ((itemIndex + smoothRange) > self.size) then to = self.size else to = itemIndex + smoothRange end local avg = self.avg(from, to) return avg end function self.delta(fromIndex, toIndex, smoothRange, default) if (fromIndex < 1 or fromIndex > self.size-1 or toIndex > self.size or toIndex < 1 or fromIndex > toIndex or toIndex < fromIndex) then return default end local value, item, referenceValue if (smoothRange ~= nil) then value = self.smoothItem(toIndex, smoothRange) referenceValue = self.smoothItem(fromIndex, smoothRange) else value = _getItemData(self.storage[toIndex]) if (value == nil) then return nil end referenceValue = _getItemData(self.storage[fromIndex]) if (referenceValue == nil) then return nil end end return tonumber(referenceValue - value) end function self.deltaSince(timeAgo, smoothRange, default) local item, index = self.getAtTime(timeAgo) if (item ~= nil) then return self.delta(1, index, smoothRange, default) end return default end function self.localMin(smoothRange, default) local min, minVal self.forEach(function(item, i, collection) local val = self.smoothItem(i, smoothRange) if (min == nil) then -- first one min = item minVal = val else if (val < minVal) then -- we got one that is even lower min = item minVal = val elseif (val > minVal) then -- we ignore equals -- rising again -- skip return false -- abort end end end) return minVal, min end function self.localMax(smoothRange, default) local max, maxVal self.forEach(function(item, i, collection) local val = self.smoothItem(i, smoothRange) if (max == nil) then -- first one max = item maxVal = val else if (val > maxVal) then -- we got one that is even higher max = item maxVal = val elseif (val < maxVal) then -- we ignore equals -- lowering again -- skip return false -- abort end end end) return maxVal, max end return self end return HistoricalStorage
gpl-3.0
silverhammermba/awesome
lib/awful/layout/suit/max.lua
1
1435
--------------------------------------------------------------------------- --- Maximized and fullscreen layouts module for awful -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @copyright 2008 Julien Danjou -- @release @AWESOME_VERSION@ -- @module awful.layout.suit.max --------------------------------------------------------------------------- -- Grab environment we need local pairs = pairs local max = {} --- The max layout layoutbox icon. -- @beautiful beautiful.layout_max -- @param surface -- @see gears.surface --- The fullscreen layout layoutbox icon. -- @beautiful beautiful.layout_fullscreen -- @param surface -- @see gears.surface local function fmax(p, fs) -- Fullscreen? local area if fs then area = p.geometry else area = p.workarea end for _, c in pairs(p.clients) do local g = { x = area.x, y = area.y, width = area.width, height = area.height } p.geometries[c] = g end end --- Maximized layout. -- @param screen The screen to arrange. max.name = "max" function max.arrange(p) return fmax(p, false) end --- Fullscreen layout. -- @param screen The screen to arrange. max.fullscreen = {} max.fullscreen.name = "fullscreen" function max.fullscreen.arrange(p) return fmax(p, true) end return max -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
wrxck/mattata
configuration.example.lua
2
16702
--[[ _ _ _ _ __ ___ __ _| |_| |_ __ _| |_ __ _ | '_ ` _ \ / _` | __| __/ _` | __/ _` | | | | | | | (_| | |_| || (_| | || (_| | |_| |_| |_|\__,_|\__|\__\__,_|\__\__,_| Configuration file for mattata v1.5 Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. Each value in an array should be comma separated, with the exception of the last value! Make sure you always update your configuration file after pulling changes from GitHub! ]] local configuration = { -- Rename this file to configuration.lua for the bot to work! ['bot_token'] = '', -- In order for the bot to actually work, you MUST insert the Telegram -- bot API token you received from @BotFather. ['connected_message'] = 'Connected to the Telegram bot API!', -- The message to print when the bot is connected to the Telegram bot API ['version'] = '1.5', -- the version of mattata, don't change this! -- The following two tokens will require you to have setup payments with @BotFather, and -- a Stripe account with @stripe! ['stripe_live_token'] = '', -- Payment token you receive from @BotFather. ['stripe_test_token'] = '', -- Test payment token you receive from @BotFather. ['admins'] = { -- Here you need to specify the numerical ID of the users who shall have -- FULL control over the bot, this includes access to server files via the lua and shell plugins. 221714512 }, ['allowlist_plugin_exceptions'] = { -- An array of plugins that will still be used for allowlisted users. 'antispam' }, ['beta_plugins'] = { -- An array of plugins that only the configured bot admins are able to use. 'array_of_beta_plugins' }, ['permanent_plugins'] = { -- An array of plugins that can't be disabled with /plugins. 'plugins', 'help', 'administration', 'about' }, ['updates'] = { ['timeout'] = 3, -- timeout in seconds for api.get_updates() ['limit'] = 100 -- message limit for api.get_updates() - must be between 1-100 }, ['language'] = 'en', -- The two character locale to set your default language to. ['log_chat'] = nil, -- This needs to be the numerical identifier of the chat you wish to log -- errors into. If it's not a private chat it should begin with a '-' symbol. ['log_admin_actions'] = true, -- Should administrative actions be logged? [true/false] ['log_channel'] = nil, -- This needs to be the numerical identifier of the channel you wish -- to log administrative actions in by default. It should begin with a '-' symbol. ['bug_reports_chat'] = nil, -- This needs to be the numerical identifier of the chat you wish to send -- bug reports into. If it's not a private chat it should begin with a '-' symbol. ['counter_channel'] = nil, -- This needs to be the numerical identifier of the channel you wish -- to forward messages into, for use with the /counter command. It should begin with a '-' symbol. -- The following directory values should NOT have a "/" at the end! ['bot_directory'] = '/path/to/bot', ['download_location'] = '/path/to/downloads', -- The location to save all downloaded media to. ['fonts_directory'] = '/path/to/fonts', -- The location where fonts are stored for CAPTCHAs ['debug'] = true, -- Turn this on to print EVEN MORE information to the terminal. ['redis'] = { -- Configurable options for connecting the bot to redis. Do NOT modify -- these settings if you don't know what you're doing! ['host'] = '127.0.0.1', ['port'] = 6379, ['password'] = nil, ['db'] = 2 }, ['keys'] = { -- API keys needed for the full functionality of several plugins. ['cats'] = '', -- http://thecatapi.com/api-key-registration.html ['translate'] = '', -- https://tech.yandex.com/keys/get/?service=trnsl ['lyrics'] = '', -- https://developer.musixmatch.com/admin/applications ['lastfm'] = '', -- http://www.last.fm/api/account/create ['weather'] = '', -- https://darksky.net/dev/register ['youtube'] = '', -- https://console.developers.google.com/apis ['maps'] = '', -- https://console.cloud.google.com/google/maps-apis ['location'] = '', -- https://opencagedata.com/api ['bing'] = '', -- https://datamarket.azure.com/account/keys ['flickr'] = '', -- https://www.flickr.com/services/apps/create/noncommercial/ ['news'] = '', -- https://newsapi.org/ ['twitch'] = '', -- https://twitchapps.com/tmi/ ['pastebin'] = '', -- https://pastebin.com/api ['dictionary'] = { -- https://developer.oxforddictionaries.com/ ['id'] = '', ['key'] = '' }, ['adfly'] = { -- https://ay.gy/publisher/tools#tools-api ['api_key'] = '', ['user_id'] = '', ['secret_key'] = '' }, ['pasteee'] = '', -- https://paste.ee/ ['google'] = { -- https://console.developers.google.com/apis ['api_key'] = '', ['cse_key'] = '' }, ['steam'] = '', -- https://steamcommunity.com/dev/apikey ['spotify'] = { -- https://developer.spotify.com/my-applications/#!/applications/create ['client_id'] = '', ['client_secret'] = '', ['redirect_uri'] = 'https://t.me/mattatabot?start=' }, ['twitter'] = { -- https://apps.twitter.com/app/new ['consumer_key'] = '', ['consumer_secret'] = '' }, ['imgur'] = { -- https://api.imgur.com/oauth2/addclient ['client_id'] = '', ['client_secret'] = '' }, ['spamwatch'] = '', -- https://t.me/SpamWatchSupport ['wolframalpha'] = '', -- https://developer.wolframalpha.com/portal/myapps/ ['movies'] = { ['omdb'] = '', -- http://www.omdbapi.com/apikey.aspx ['poster'] = '' -- https://www.myapifilms.com/token.do }, ['transcribe'] = '' -- https://wit.ai/v2 }, ['errors'] = { -- Messages to provide a more user-friendly approach to errors. ['connection'] = 'Connection error.', ['results'] = 'I couldn\'t find any results for that.', ['supergroup'] = 'This command can only be used in supergroups.', ['admin'] = 'You need to be a moderator or an administrator in this chat in order to use this command.', ['unknown'] = 'I don\'t recognise that user. If you would like to teach me who they are, forward a message from them to any chat that I\'m in.', ['generic'] = 'An unexpected error occured. Please report this error using /bugreport.' }, ['limits'] = { ['bing'] = { ['private'] = 15, ['public'] = 7 }, ['stackoverflow'] = { ['private'] = 12, ['public'] = 8 }, ['reddit'] = { ['private'] = 8, ['public'] = 4 }, ['chatroulette'] = 512, ['copypasta'] = 300, ['drawtext'] = 1000, ['help'] = { ['per_page'] = 4 }, ['nick'] = 128, ['plugins'] = { ['per_page'] = 18, ['columns'] = 2 } }, ['administration'] = { -- Values used in administrative plugins ['warnings'] = { ['maximum'] = 10, ['minimum'] = 2, ['default'] = 3 }, ['captcha'] = { ['length'] = { ['min'] = 4, ['max'] = 10, ['default'] = 7 }, ['size'] = { ['min'] = 20, ['max'] = 50, ['default'] = 40 }, ['timeout'] = { ['min'] = 1, ['max'] = 60, ['default'] = 5 } }, ['allowed_links'] = { 'username', 'telegram', 'mattata', 'admin', 'admins' }, ['aliases'] = { ['length'] = { ['min'] = 1, ['max'] = 64 }, ['total'] = 150 }, ['store_chat_members'] = true, ['global_antispam'] = { -- normal antispam is processed in plugins/antispam.mattata ['ttl'] = 5, -- amount of seconds to process the messages in ['message_warning_amount'] = 10, -- amount of messages a user can send in the TTL until they're warned ['message_allowlist_amount'] = 25, -- amount of messages a user can send in the TTL until they're allowlisted ['allowlist_length'] = 86400, -- amount (in seconds) to allowlist the user for (set it to -1 if you want it forever) ['max_code_length'] = 64 -- maximum length of code or pre entities that are allowed with "remove pasted code" setting on }, ['default'] = { ['antispam'] = { ['text'] = 8, ['forwarded'] = 16, ['sticker'] = 4, ['photo'] = 4, ['video'] = 4, ['location'] = 4, ['voice'] = 4, ['game'] = 2, ['venue'] = 4, ['video_note'] = 4, ['invoice'] = 2, ['contact'] = 2, ['dice'] = 1, ['poll'] = 1 } }, ['feds'] = { ['group_limit'] = 3, ['shortened_feds'] = { ['name'] = 'uuid' } } }, ['join_messages'] = { -- Values used in plugins/administration.lua. 'Welcome, NAME!', 'Hello, NAME!', 'Enjoy your stay, NAME!', 'I\'m glad you joined, NAME!', 'Howdy, NAME!', 'Hi, NAME!' }, ['groups'] = { ['name'] = 't.me/username' }, ['sort_groups'] = true, -- Decides whether groups will be sorted by name in /groups. ['stickers'] = { -- Values used in mattata.lua, for administrative plugin functionality. -- These are the file_id values for stickers which are binded to the relevant command. ['ban'] = { 'AgAD0AIAAlAYNw0', 'AgADzwIAAlAYNw0' }, ['warn'] = { 'AgAD0QIAAlAYNw0', 'AgAD0gIAAlAYNw0' }, ['kick'] = { 'AgAD0wIAAlAYNw0' } }, ['slaps'] = { '{THEM} was shot by {ME}.', '{THEM} was pricked to death.', '{THEM} walked into a cactus while trying to escape {ME}.', '{THEM} drowned.', '{THEM} drowned whilst trying to escape {ME}.', '{THEM} blew up.', '{THEM} was blown up by {ME}.', '{THEM} hit the ground too hard.', '{THEM} fell from a high place.', '{THEM} fell off a ladder.', '{THEM} fell into a patch of cacti.', '{THEM} was doomed to fall by {ME}.', '{THEM} was blown from a high place by {ME}.', '{THEM} was squashed by a falling anvil.', '{THEM} went up in flames.', '{THEM} burned to death.', '{THEM} was burnt to a crisp whilst fighting {ME}.', '{THEM} walked into a fire whilst fighting {ME}.', '{THEM} tried to swim in lava.', '{THEM} tried to swim in lava whilst trying to escape {ME}.', '{THEM} was struck by lightning.', '{THEM} was slain by {ME}.', '{THEM} got finished off by {ME}.', '{THEM} was killed by magic.', '{THEM} was killed by {ME} using magic.', '{THEM} starved to death.', '{THEM} suffocated in a wall.', '{THEM} fell out of the world.', '{THEM} was knocked into the void by {ME}.', '{THEM} withered away.', '{THEM} was pummeled by {ME}.', '{THEM} was fragged by {ME}.', '{THEM} was desynchronized.', '{THEM} was wasted.', '{THEM} was busted.', '{THEM}\'s bones are scraped clean by the desolate wind.', '{THEM} has died of dysentery.', '{THEM} fainted.', '{THEM} is out of usable Pokemon! {THEM} whited out!', '{THEM} is out of usable Pokemon! {THEM} blacked out!', '{THEM} whited out!', '{THEM} blacked out!', '{THEM} says goodbye to this cruel world.', '{THEM} got rekt.', '{THEM} was sawn in half by {ME}.', '{THEM} died. I blame {ME}.', '{THEM} was axe-murdered by {ME}.', '{THEM}\'s melon was split by {ME}.', '{THEM} was sliced and diced by {ME}.', '{THEM} was split from crotch to sternum by {ME}.', '{THEM}\'s death put another notch in {ME}\'s axe.', '{THEM} died impossibly!', '{THEM} died from {ME}\'s mysterious tropical disease.', '{THEM} escaped infection by dying.', '{THEM} played hot-potato with a grenade.', '{THEM} was knifed by {ME}.', '{THEM} fell on his sword.', '{THEM} ate a grenade.', '{THEM}\'s parents got shot by {ME}.', '{THEM} practiced being {ME}\'s clay pigeon.', '{THEM} is what\'s for dinner!', '{THEM} was terminated by {ME}.', '{THEM} was shot before being thrown out of a plane.', '{THEM} was not invincible.', '{THEM} has encountered an error.', '{THEM} died and reincarnated as a goat.', '{ME} threw {THEM} off a building.', '{THEM} is sleeping with the fishes.', '{THEM} got a premature burial.', '{ME} replaced all of {THEM}\'s music with Nickelback.', '{ME} spammed {THEM}\'s email.', '{ME} cut {THEM}\'s genitals off with a rusty pair of scissors!', '{ME} made {THEM} a knuckle sandwich.', '{ME} slapped {THEM} with pure nothing.', '{ME} hit {THEM} with a small, interstellar spaceship.', '{THEM} was quickscoped by {ME}.', '{ME} put {THEM} in check-mate.', '{ME} RSA-encrypted {THEM} and deleted the private key.', '{ME} put {THEM} in the friendzone.', '{ME} molested {THEM} in a shed.', '{ME} slaps {THEM} with a DMCA takedown request!', '{THEM} became a corpse blanket for {ME}.', 'Death is when the monsters get you. Death comes for {THEM}.', 'Cowards die many times before their death. {THEM} never tasted death but once.', '{THEM} died of hospital gangrene.', '{THEM} got a house call from Doctor {ME}.', '{ME} beheaded {THEM}.', '{THEM} got stoned...by an angry mob.', '{ME} sued the pants off {THEM}.', '{THEM} was impeached.', '{THEM} was beaten to a pulp by {ME}.', '{THEM} was forced to have cheeky bum sex with {ME}!', '{THEM} was one-hit KO\'d by {ME}.', '{ME} sent {THEM} to /dev/null.', '{ME} sent {THEM} down the memory hole.', '{THEM} was a mistake.', '{THEM} is a failed abortion.', '{THEM}\'s birth certificate is just an apology letter from their local condom dispensary.', '\'{THEM} was a mistake.\' - {ME}', '{ME} checkmated {THEM} in two moves.', '{THEM} was brutally raped by {ME}.' } } local get_plugins = function(extension, directory) extension = extension and tostring(extension) or 'lua' if extension:match('^%.') then extension = extension:match('^%.(.-)$') end directory = directory and tostring(directory) or 'plugins' if directory:match('/$') then directory = directory:match('^(.-)/$') end local plugins = {} local list = io.popen('ls ' .. directory .. '/') local all = list:read('*all') list:close() for plugin in all:gmatch('[%w_-]+%.' .. extension .. ' ?') do plugin = plugin:match('^([%w_-]+)%.' .. extension .. ' ?$') table.insert(plugins, plugin) end return plugins end local get_fonts = function() local fonts = {} local list = io.popen('ls fonts/') local all = list:read('*all') list:close() for font in all:gmatch('%a+') do table.insert(fonts, font) end return fonts end configuration.plugins = get_plugins() configuration.administrative_plugins = get_plugins(nil, 'plugins/administration') configuration.administration.captcha.files = get_fonts() for _, v in pairs(configuration.administrative_plugins) do table.insert(configuration.plugins, v) end return configuration --[[ End of configuration, you're good to go. Use `./launch.sh` to start the bot. If you can't execute the script, try running `chmod +x launch.sh` ]]
mit
135yshr/Holocraft-server
world/Plugins/APIDump/Hooks/OnWeatherChanging.lua
42
1369
return { HOOK_WEATHER_CHANGING = { CalledWhen = "The weather is about to change", DefaultFnName = "OnWeatherChanging", -- also used as pagename Desc = [[ This hook is called when the current weather has expired and a new weather is selected. Plugins may override the new weather being set.</p> <p> The new weather setting is sent to the clients only after this hook has been processed.</p> <p> See also the {{OnWeatherChanged|HOOK_WEATHER_CHANGED}} hook for a similar hook called after the change. ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "World for which the weather is changing" }, { Name = "Weather", Type = "number", Notes = "The newly selected weather. One of wSunny, wRain, wStorm" }, }, Returns = [[ The hook handler can return up to two values. If the first value is false or not present, the server calls other plugins' callbacks and finally sets the weather. If it is true, the server doesn't call any more callbacks for this hook. The second value returned is used as the new weather. If no value is given, the weather from the parameters is used as the weather. Returning false as the first value and a specific weather constant as the second value makes the server call the rest of the hook handlers with the new weather value. ]], }, -- HOOK_WEATHER_CHANGING }
mit
bizkut/BudakJahat
Rotations/Demon Hunter/Havoc/HavocCuteOne.lua
1
58025
local rotationName = "CuteOne" --------------- --- Toggles --- --------------- local function createToggles() -- Rotation Button RotationModes = { [1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "Swaps between Single and Multiple based on number of targets in range.", highlight = 1, icon = br.player.spell.bladeDance}, [2] = { mode = "Mult", value = 2 , overlay = "Multiple Target Rotation", tip = "Multiple target rotation used.", highlight = 0, icon = br.player.spell.bladeDance}, [3] = { mode = "Sing", value = 3 , overlay = "Single Target Rotation", tip = "Single target rotation used.", highlight = 0, icon = br.player.spell.chaosStrike}, [4] = { mode = "Off", value = 4 , overlay = "DPS Rotation Disabled", tip = "Disable DPS Rotation", highlight = 0, icon = br.player.spell.spectralSight} }; CreateButton("Rotation",1,0) -- Cooldown Button CooldownModes = { [1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.metamorphosis}, [2] = { mode = "On", value = 2 , overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.metamorphosis}, [3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.metamorphosis} }; CreateButton("Cooldown",2,0) -- Defensive Button DefensiveModes = { [1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.darkness}, [2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.darkness} }; CreateButton("Defensive",3,0) -- Interrupt Button InterruptModes = { [1] = { mode = "On", value = 1 , overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.consumeMagic}, [2] = { mode = "Off", value = 2 , overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.consumeMagic} }; CreateButton("Interrupt",4,0) -- Mover MoverModes = { [1] = { mode = "AC", value = 1 , overlay = "Movement Animation Cancel Enabled", tip = "Will Cancel Movement Animation.", highlight = 1, icon = br.player.spell.felRush}, [2] = { mode = "On", value = 2 , overlay = "Auto Movement Enabled", tip = "Will Cast Movement Abilities.", highlight = 0, icon = br.player.spell.felRush}, [3] = { mode = "Off", value = 3 , overlay = "Auto Movement Disabled", tip = "Will NOT Cast Movement Abilities", highlight = 0, icon = br.player.spell.felRush} }; CreateButton("Mover",5,0) -- Hold Eye Beam EyeBeamModes = { [1] = { mode = "On", value = 1 , overlay = "Use Eye beam", tip = "Use Eye beam", highlight = 1, icon = br.player.spell.eyeBeam}, [2] = { mode = "Off", value = 2 , overlay = "Don't use Eye beam", tip = "Don't use Eye beam", highlight = 0, icon = br.player.spell.eyeBeam} }; CreateButton("EyeBeam",6,0) -- Hold Fel Barrage FelBarrageModes = { [1] = { mode = "On", value = 1 , overlay = "Use Fel Barrage", tip = "Use Fel Barrage", highlight = 1, icon = br.player.spell.felBarrage}, [2] = { mode = "Off", value = 2 , overlay = "Don't use Fel Barrage", tip = "Don't use Fel Barrage", highlight = 0, icon = br.player.spell.felBarrage} }; CreateButton("FelBarrage",7,0) end --------------- --- OPTIONS --- --------------- local function createOptions() local optionTable local function rotationOptions() local section -- General Options section = br.ui:createSection(br.ui.window.profile, "General") -- APL br.ui:createDropdownWithout(section, "APL Mode", {"|cffFFFFFFSimC"}, 1, "|cffFFFFFFSet APL Mode to use.") -- Dummy DPS Test br.ui:createSpinner(section, "DPS Testing", 5, 5, 60, 5, "|cffFFFFFFSet to desired time for test in minuts. Min: 5 / Max: 60 / Interval: 5") -- Pre-Pull Timer br.ui:createSpinner(section, "Pre-Pull Timer", 5, 1, 10, 1, "|cffFFFFFFSet to desired time to start Pre-Pull (DBM Required). Min: 1 / Max: 10 / Interval: 1") -- M+ Meta Pre-Pull Timer br.ui:createSpinner(section, "M+ Pre-Pull", 3, 1, 10, 1, "|cffFFFFFFSet to desired time to Meta Pre-Pull (DBM Required). Min: 1 / Max: 10 / Interval: 1") -- Auto Engage br.ui:createCheckbox(section, "Auto Engage") -- Eye Beam Targets br.ui:createDropdownWithout(section,"Eye Beam Usage",{"|cff00FF00Per APL","|cffFFFF00AoE Only","|cffFF0000Never"}, 1, "|cffFFFFFFWhen to use Eye Beam.") br.ui:createSpinnerWithout(section, "Units To AoE", 3, 1, 10, 1, "|cffFFBB00Number of Targets to use AoE spells on.") -- Fel Rush Charge Hold br.ui:createSpinnerWithout(section, "Hold Fel Rush Charge", 1, 0, 2, 1, "|cffFFBB00Number of Fel Rush charges the bot will hold for manual use."); -- Fel Rush Only In Melee br.ui:createCheckbox(section, "Fel Rush Only In Melee") -- Fel Rush After Vengeful Retreat br.ui:createCheckbox(section, "Auto Fel Rush After Retreat") -- Throw Glaive br.ui:createCheckbox(section, "Throw Glaive") -- Vengeful Retreat br.ui:createCheckbox(section, "Vengeful Retreat") -- Glide Fall Time br.ui:createSpinner(section, "Glide", 2, 0, 10, 1, "|cffFFBB00Seconds until Glide will be used while falling.") br.ui:checkSectionState(section) -- Cooldown Options section = br.ui:createSection(br.ui.window.profile, "Cooldowns") -- Augment Rune br.ui:createCheckbox(section,"Augment Rune") -- Potion br.ui:createCheckbox(section,"Potion") -- Elixir br.ui:createDropdownWithout(section,"Elixir", {"Greater Currents","Repurposed Fel Focuser","Inquisitor's Menacing Eye","None"}, 1, "|cffFFFFFFSet Elixir to use.") -- Racial br.ui:createCheckbox(section,"Racial") -- Trinkets br.ui:createDropdownWithout(section, "Trinkets", {"|cff00FF001st Only","|cff00FF002nd Only","|cffFFFF00Both","|cffFF0000None"}, 1, "|cffFFFFFFSelect Trinket Usage.") -- Metamorphosis br.ui:createCheckbox(section,"Metamorphosis") -- Heart Essences br.ui:createCheckbox(section,"Use Essence") -- Azerite Beam Units br.ui:createSpinnerWithout(section, "Azerite Beam Units", 3, 1, 10, 1, "|cffFFBB00Number of Targets to use Azerite Beam on.") br.ui:checkSectionState(section) -- Defensive Options section = br.ui:createSection(br.ui.window.profile, "Defensive") -- Healthstone br.ui:createSpinner(section, "Pot/Stoned", 60, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At") -- Heirloom Neck br.ui:createSpinner(section, "Heirloom Neck", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at."); -- Blur br.ui:createSpinner(section, "Blur", 50, 0, 100, 5, "|cffFFBB00Health Percentage to use at.") -- Darkness br.ui:createSpinner(section, "Darkness", 30, 0, 100, 5, "|cffFFBB00Health Percentage to use at.") -- Chaos Nova br.ui:createSpinner(section, "Chaos Nova - HP", 30, 0, 100, 5, "|cffFFBB00Health Percentage to use at.") br.ui:createSpinner(section, "Chaos Nova - AoE", 3, 1, 10, 1, "|cffFFBB00Number of Targets to use at.") -- Consume Magic br.ui:createCheckbox(section, "Consume Magic") br.ui:checkSectionState(section) -- Interrupt Options section = br.ui:createSection(br.ui.window.profile, "Interrupts") -- Chaos Nova br.ui:createCheckbox(section, "Chaos Nova") -- Disrupt br.ui:createCheckbox(section, "Disrupt") -- Fel Eruption br.ui:createCheckbox(section, "Fel Eruption") -- Interrupt Percentage br.ui:createSpinner(section, "Interrupt At", 0, 0, 95, 5, "|cffFFFFFFCast Percent to Cast At") br.ui:checkSectionState(section) -- Toggle Key Options section = br.ui:createSection(br.ui.window.profile, "Toggle Keys") -- Single/Multi Toggle br.ui:createDropdownWithout(section, "Rotation Mode", br.dropOptions.Toggle, 4) -- Cooldown Key Toggle br.ui:createDropdownWithout(section, "Cooldown Mode", br.dropOptions.Toggle, 3) -- Defensive Key Toggle br.ui:createDropdownWithout(section, "Defensive Mode", br.dropOptions.Toggle, 6) -- Interrupts Key Toggle br.ui:createDropdownWithout(section, "Interrupt Mode", br.dropOptions.Toggle, 6) -- Mover Key Toggle br.ui:createDropdownWithout(section, "Mover Mode", br.dropOptions.Toggle, 6) -- Pause Toggle br.ui:createDropdown(section, "Pause Mode", br.dropOptions.Toggle, 6) br.ui:checkSectionState(section) end optionTable = {{ [1] = "Rotation Options", [2] = rotationOptions, }} return optionTable end -------------- --- Locals --- -------------- local buff local cast local cd local charges local debuff local enemies local essence local equiped local fury local furyDeficit local gcd local has local item local race local talent local traits local ui local unit local units local use local var = {} var.felBarrageSync = false var.leftCombat = GetTime() var.lastRune = GetTime() var.profileStop = false -- Custom Functions local function cancelRushAnimation() if cast.able.felRush() and GetUnitSpeed("player") == 0 then MoveBackwardStart() JumpOrAscendStart() cast.felRush() MoveBackwardStop() AscendStop() end return end local function cancelRetreatAnimation() if cast.able.vengefulRetreat() then -- C_Timer.After(.001, function() SetHackEnabled("NoKnockback", true) end) -- C_Timer.After(.35, function() cast.vengefulRetreat() end) -- C_Timer.After(.55, function() SetHackEnabled("NoKnockback", false) end) -- SetHackEnabled("NoKnockback", true) if cast.vengefulRetreat() then C_Timer.After(.35, function() StopFalling(); end) C_Timer.After(.55, function() MoveForwardStart(); end) C_Timer.After(.75, function() MoveForwardStop(); end) -- SetHackEnabled("NoKnockBack", false) end end return end local function eyebeamTTD() local length = talent.blindFury and 3 or 2 if enemies.yards20r > 0 then for i = 1, enemies.yards20r do if unit.ttd(enemies.yards20rTable[i]) >= length then return true end end end return false end -------------------- --- Action Lists --- -------------------- -- Action List - Extras local actionList = {} actionList.Extras = function() -- Dummy Test if ui.checked("DPS Testing") then if unit.exists("target") then if getCombatTime() >= (tonumber(ui.value("DPS Testing"))*60) and unit.isDummy("target") then StopAttack() ClearTarget() Print(tonumber(ui.value("DPS Testing")) .." Minute Dummy Test Concluded - Profile Stopped") var.profileStop = true end end end -- End Dummy Test -- Glide if ui.checked("Glide") and cast.able.glide() and not buff.glide.exists() then if var.falling >= ui.value("Glide") then if cast.glide("player") then ui.debug("Casting Glide") return true end end end end -- End Action List - Extras -- Action List - Defensive actionList.Defensive = function() if ui.useDefensive() then -- Pot/Stoned if ui.checked("Pot/Stoned") and unit.hp()<= ui.value("Pot/Stoned") and unit.inCombat() and (var.hasHealPot() or has.healthstone() or has.legionHealthstone()) then if has.healthstone() then if use.healthstone() then ui.debug("Using Healthstone") return true end elseif has.legionHealthstone() then --Legion Healthstone if use.legionHealthstone() then ui.debug("Using Legion Healthstone") return true end elseif has.item(var.healPot) then use.item(var.healPot) ui.debug("Using "..GetItemInfo(var.healPot)) return true end end -- Heirloom Neck if ui.checked("Heirloom Neck") and unit.hp()<= ui.value("Heirloom Neck") then if use.able.heirloomNeck() and item.heirloomNeck ~= 0 and item.heirloomNeck ~= item.manariTrainingAmulet then if use.heirloomNeck() then ui.debug("Using Heirloom Neck") return true end end end -- Blur if ui.checked("Blur") and cast.able.blur() and unit.hp()<= ui.value("Blur") and unit.inCombat() then if cast.blur() then ui.debug("Casting Blur") return true end end -- Darkness if ui.checked("Darkness") and cast.able.darkness() and unit.hp()<= ui.value("Darkness") and unit.inCombat() then if cast.darkness() then ui.debug("Casting Darkness") return true end end -- Chaos Nova if ui.checked("Chaos Nova - HP") and cast.able.chaosNova() and not buff.metamorphosis.exists() and unit.hp()<= ui.value("Chaos Nova - HP") and unit.inCombat() and #enemies.yards5 > 0 then if cast.chaosNova() then ui.debug("Casting Chaos Nova [HP]") return true end end if ui.checked("Chaos Nova - AoE") and cast.able.chaosNova() and not buff.metamorphosis.exists() and #enemies.yards5 >= ui.value("Chaos Nova - AoE") then if cast.chaosNova() then ui.debug("Casting Chaos Nova [AoE]") return true end end if ui.checked("Consume Magic") then for i=1, #enemies.yards10 do local thisUnit = enemies.yards10[i] if cast.able.consumeMagic(thisUnit) and cast.dispel.consumeMagic(thisUnit) and not unit.isBoss(thisUnit) and unit.exists(thisUnit) then if cast.consumeMagic(thisUnit) then ui.debug("Casting Consume Magic") return true end end end end end -- End Defensive Toggle end -- End Action List - Defensive -- Action List - Interrupts actionList.Interrupts = function() if ui.useInterrupt() then -- Fel Eruption if ui.checked("Fel Eruption") and talent.felEruption then for i=1, #enemies.yards20 do local thisUnit = enemies.yards20[i] if canInterrupt(thisUnit,ui.value("Interrupt At")) and cast.able.felEruption(thisUnit) then if cast.felEruption(thisUnit) then ui.debug("Casting Fel Eruption") return true end end end end -- Disrupt if ui.checked("Disrupt") then for i=1, #enemies.yards10 do local thisUnit = enemies.yards10[i] if canInterrupt(thisUnit,ui.value("Interrupt At")) and cast.able.disrupt(thisUnit) then if cast.disrupt(thisUnit) then ui.debug("Disrupt") return true end end end end -- Chaos Nova if ui.checked("Chaos Nova") then for i=1, #enemies.yards5 do local thisUnit = enemies.yards5[i] if canInterrupt(thisUnit,ui.value("InterruptAt")) and cast.able.chaosNova(thisUnit) then if cast.chaosNova(thisUnit) then ui.debug("Chaos Nova [Int]") return true end end end end end -- End useInterrupts check end -- End Action List - Interrupts -- Action List - Cooldowns actionList.Cooldowns = function() if ui.useCDs() and unit.distance(units.dyn5) < 5 then -- Racial: Orc Blood Fury | Troll Berserking | Blood Elf Arcane Torrent if ui.checked("Racial") and cast.able.racial() and (race == "Orc" or race == "Troll" or race == "BloodElf") then if cast.racial() then ui.debug("Casting Racial Ability") return true end end -- Metamorphosis if ui.checked("Metamorphosis") then -- metamorphosis,if=!(talent.demonic.enabled|variable.pooling_for_meta)|target.time_to_die<25 if cast.able.metamorphosis() and (not (talent.demonic or var.poolForMeta) and unit.ttd(units.dyn5) >= 25) and #enemies.yards8 > 0 then if cast.metamorphosis("player") then ui.debug("Casting Metamorphosis") return true end end -- metamorphosis,if=talent.demonic.enabled&(!azerite.chaotic_transformation.enabled|(cooldown.eye_beam.remains>20&(!variable.blade_dance|cooldown.blade_dance.remains>gcd.max))) if cast.able.metamorphosis() and talent.demonic and (not traits.chaoticTransformation.active or (cd.eyeBeam.remain() > 20 and (not var.bladeDance or cd.bladeDance.remain() > gcd))) and #enemies.yards8 > 0 then if cast.metamorphosis("player") then ui.debug("Casting Metamorphosis [Demonic]") return true end end end -- sinful_brand,if=!dot.sinful_brand.ticking -- the_hunt -- fodder_to_the_flame -- elysian_decree -- Potion -- potion,if=buff.metamorphosis.remains>25|target.time_to_die<60 if ui.checked("Potion") and use.able.potionOfUnbridledFury() and var.inRaid then if buff.metamorphosis.remain() > 25 and unit.ttd(units.dyn5) >= 60 then use.potionOfUnbridledFury() ui.debug("Unit Postiion of Unbridaled Fury") return end end -- Trinkets for i = 13, 14 do local opValue = ui.value("Trinkets") local iValue = i - 12 if (opValue == iValue or opValue == 3) and use.able.slot(i) then -- use_item,name=galecallers_boon,if=!talent.fel_barrage.enabled|cooldown.fel_barrage.ready if use.able.galecallersBoon(i) and equiped.galecallersBoon(i) and (not talent.felBarrage or cd.felBarrage.ready()) then use.slot(i) ui.debug("Using Galecaller's Boon") return end -- use_item,effect_name=cyclotronic_blast,if=buff.metamorphosis.up&buff.memory_of_lucid_dreams.down&(!variable.blade_dance|!cooldown.blade_dance.ready) if use.able.pocketSizedComputationDevice(i) and equiped.pocketSizedComputationDevice(i) and buff.metamorphosis.exists() and not buff.memoryOfLucidDreams.exists() and (var.bladeDance or not cd.bladeDance.ready()) then use.slot(i) ui.debug("Using Cyclotronic Blast") return end -- use_item,name=ashvanes_razor_coral,if=debuff.razor_coral_debuff.down|(debuff.conductive_ink_debuff.up|buff.metamorphosis.remains>20)&target.health.pct<31|target.time_to_die<20 if use.able.ashvanesRazorCoral(i) and equiped.ashvanesRazorCoral(i) and (not debuff.razorCoral.exists(units.dyn5) or (debuff.conductiveInk.exists(units.dyn5) or buff.metamorphosis.remain() > 20)) and (unit.hp(units.dyn5) or unit.ttd(units.dyn5) < 20) then use.slot(i) ui.debug("Ashvane's Razor Coral") return end -- use_item,name=azsharas_font_of_power,if=cooldown.metamorphosis.remains<10|cooldown.metamorphosis.remains>60 if use.able.azsharasFontOfPower(i) and equiped.azsharasFontOfPower(i) and (cd.metamorphosis.remain() < 10 or cd.metamorphosis.remain() > 60) then use.slot(i) ui.debug("Azshara's Font of Power") return end -- use_items,if=buff.metamorphosis.up if use.able.slot(i) and buff.metamorphosis.exists() and not (equiped.galecallersBoon(i) or equiped.pocketSizedComputationDevice(i) or equiped.ashvanesRazorCoral(i) or equiped.azsharasFontOfPower(i)) then use.slot(i) ui.debug("Using Trinket in Slot "..i) return end end end end -- End useCDs check -- Heart Essences -- call_action_list,name=essences if ui.checked("Use Essence") then if actionList.Essence() then return true end end end -- End Action List - Cooldowns -- Action List - Essence Break actionList.EssenceBreak = function() -- Essence Break -- essence_break,if=fury>=80&(cooldown.blade_dance.ready|!variable.blade_dance) if cast.able.essenceBreak() and fury >= 80 and (cd.bladeDance.ready() or not var.bladeDance) then if cast.essenceBreak() then ui.debug("Casting Essence Break") return true end end if buff.essenceBreak.exists() then if var.bladeDance then -- Death Sweep -- death_sweep,if=variable.blade_dance&debuff.essence_break.up if cast.able.deathSweep() and buff.metamorphosis.exists() and var.bladeDance and buff.essenceBreak.exists() then if cast.deathSweep() then ui.debug("Casting Death Sweep [Essence Break]") return true end end -- Blade Dance -- blade_dance,if=variable.blade_dance&debuff.essence_break.up if cast.able.bladeDance() and not buff.metamorphosis.exists() and var.bladeDance and buff.essenceBreak.exists() then if cast.bladeDance() then ui.debug("Casting Blade Dance [Essence Break]") return true end end end -- Annihilation -- annihilation,if=debuff.essence_break.up if cast.able.annihilation() and buff.metamorphosis.exists() then if cast.annihilation() then ui.debug("Casting Annihilation [Essence Break]") return true end end -- Chaos Strike -- chaos_strike,if=debuff.essence_break.up if cast.able.chaosStrikle() and not buff.metamorphosis.exists() then if cast.chaosStrike() then ui.debug("Casting Chaos Strike [Essence Break]") return true end end end end -- End Action List - Essence Break -- Action List - Heart Essence actionList.Essence = function() -- Essence: Concentrated Flame -- concentrated_flame,if=(!dot.concentrated_flame_burn.ticking&!action.concentrated_flame.in_flight|full_recharge_time<gcd.max) if cast.able.concentratedFlame() and (not debuff.concentratedFlame.exists(units.dyn5) and not cast.last.concentratedFlame() or charges.concentratedFlame.timeTillFull() < gcd) then if cast.concentratedFlame() then ui.debug("Casting Concentrated Flame") return true end end -- Essence: Blood of the Enemy -- blood_of_the_enemy,if=(!talent.fel_barrage.enabled|cooldown.fel_barrage.remains>45)&!variable.waiting_for_momentum&((!talent.demonic.enabled|buff.metamorphosis.up&!cooldown.blade_dance.ready)|target.time_to_die<=10) if cast.able.bloodOfTheEnemy() and (not talent.felBarrage or cd.felBarrage.remain() > 45) and not var.waitingForMomentum and ((not talent.demonic or buff.metamorphosis.exists() and not cd.bladeDance.ready() or unit.ttd(units.dyn5) <= 10 and ui.useCDs())) then if cast.bloodOfTheEnemy() then ui.debug("Casting Blood of the Enemy") return true end end -- blood_of_the_enemy,if=talent.fel_barrage.enabled&variable.fel_barrage_sync if cast.able.bloodOfTheEnemy() and talent.felBarrage and var.felBarrageSync and ui.useCDs() then if cast.bloodOfTheEnemy() then ui.debug("Casting Blood of the Enemy [Fel Barrage Sync]") return true end end -- Essence: Guardian of Azeroth -- guardian_of_azeroth,if=(buff.metamorphosis.up&cooldown.metamorphosis.ready)|buff.metamorphosis.remains>25|target.time_to_die<=30 if ui.useCDs() and cast.able.guardianOfAzeroth() and ((buff.metamorphosis.exists() and cd.metamorphosis.ready()) or buff.metamorphosis.remain() > 25 or unit.ttd(units.dyn5) <= 30) then if cast.guardianOfAzeroth() then ui.debug("Casting Guardian of Azeroth") return true end end -- Essence: Focused Azerite Beam -- focused_azerite_beam,if=spell_targets.blade_dance1>=2|raid_event.adds.in>60 if cast.able.focusedAzeriteBeam() and not unit.isExplosive("target") and (enemies.yards25r >= ui.value("Azerite Beam Units") or (ui.useCDs() and enemies.yards25r > 0)) then local minBeamCount = ui.useCDs() and 1 or ui.value("Azerite Beam Units") if cast.focusedAzeriteBeam(nil,"rect",minBeamCount,30) then ui.debug("Casting Focused Azerite Beam") return true end end -- Essence: Purifying Blast -- purifying_blast,if=spell_targets.blade_dance1>=2|raid_event.adds.in>60 if cast.able.purifyingBlast() and not unit.isExplosive("target") and (#enemies.yards8t >= 3 or ui.useCDs()) then local minCount = ui.useCDs() and 1 or 3 if cast.purifyingBlast("best", nil, minCount, 8) then ui.debug("Casting Purifying Blast") return true end end -- Essence: The Unbound Force -- the_unbound_force,if=buff.reckless_force.up|buff.reckless_force_counter.stack<10 if cast.able.theUnboundForce() and (buff.recklessForce.exist() or buff.recklessForceCounter.stack() < 10) then if cast.theUnboundForce() then ui.debug("Casting The Unbound Force") return true end end -- Essence: Ripple In Space -- ripple_in_space if cast.able.rippleInSpace() then if cast.rippleInSpace() then ui.debug("Casting Ripple In Space") return true end end -- Essence: Worldvein Resonance -- worldvein_resonance,if=buff.metamorphosis.up|variable.fel_barrage_sync if cast.able.worldveinResonance() and (buff.metamorphosis.exists() or var.felBarrageSync) then if cast.worldveinResonance() then ui.debug("Casting Worldvein Resonance") return true end end -- Essence: Memory of Lucid Dreams -- memory_of_lucid_dreams,if=fury<40&buff.metamorphosis.up if ui.useCDs() and cast.able.memoryOfLucidDreams() and buff.metamorphosis.exists() and fury < 40 then if cast.memoryOfLucidDreams() then ui.debug("Casting Memory of Lucid Dreams") return true end end -- Essence: Reaping Flames -- reaping_flames,target_if=target.time_to_die<1.5|((target.health.pct>80|target.health.pct<=20)&(active_enemies=1|variable.reaping_delay>29))|(target.time_to_pct_20>30&(active_enemies=1|variable.reaping_delay>44)) if cast.able.reapingFlames() then for i = 1, #enemies.yards40f do local thisUnit = enemies.yards40f[i] local thisHP = unit.hp(thisUnit) if unit.ttd(thisUnit) < 1.5 or (((essence.reapingFlames.rank >= 2 and thisHP > 80) or thisHP <= 20 ) and (#enemies.yards40 == 1 or var.reapingDelay() > 29)) or (unit.ttd(thisUnit,20) > 30 and (#enemies.yards40 == 1 or var.reapingDelay() > 44)) then if cast.reapingFlames(thisUnit) then ui.debug("Casting Reaping Flames") return true end end end end end -- Action List - Demonic actionList.Demonic = function() -- Fel Rush -- fel_rush,if=(talent.unbound_chaos.enabled&buff.unbound_chaos.up)&(charges=2|(raid_event.movement.in>10&raid_event.adds.in>10)) if cast.able.felRush() and not unit.isExplosive("target") and unit.facing("player","target",10) and charges.felRush.count() > ui.value("Hold Fel Rush Charge") and talent.unboundChaos and buff.innerDemon.exists() and charges.felRush.count() == 2 then if ui.mode.mover == 1 and unit.distance("target") < 8 then cancelRushAnimation() elseif not ui.checked("Fel Rush Only In Melee") and (ui.mode.mover == 2 or (unit.distance("target") >= 8 and ui.mode.mover ~= 3)) then if cast.felRush() then ui.debug("Casting Fel Rusg [Unbound Chaos]") return true end end end -- Death Sweep -- death_sweep,if=variable.blade_dance if cast.able.deathSweep() and not unit.isExplosive("target") and #enemies.yards8 > 0 and buff.metamorphosis.exists() and var.bladeDance then if cast.deathSweep("player","aoe",1,8) then ui.debug("Casting Death Sweep") return true end end -- Glaive Tempest -- glaive_tempest,if=active_enemies>desired_targets|raid_event.adds.in>10 if cast.able.glaiveTempest() and ((ui.mode.rotation == 1 and #enemeies.yards8 > ui.value("Units To AoE")) or ui.mode.rotation == 2 or unit.isBoss(units.dyn5)) then if cast.glaiveTempest("player","aoe",1,8) then ui.debug("Casting Glaive Tempest") return true end end -- Throw Glaive -- throw_glaive,if=conduit.serrated_glaive.enabled&cooldown.eye_beam.remains<6&!buff.metamorphosis.up&!debuff.exposed_wound.up -- if ui.checked("Throw Glaive") and cast.able.throwGlaive() then -- if cast.throwGlaive(nil,"aoe",1,10) then ui.debug("Casting Throw Glaive [Serrated Glaive]") return true end -- end -- Eye Beam -- eye_beam,if=raid_event.adds.up|raid_event.adds.in>25 if ui.mode.eyeBeam == 1 and not unit.isExplosive("target") and cast.able.eyeBeam() and not unit.moving() and enemies.yards20r > 0 and ((ui.value("Eye Beam Usage") == 1 and ui.mode.rotation == 1) or (ui.value("Eye Beam Usage") == 2 and ui.mode.rotation == 1 and enemies.yards20r >= ui.value("Units To AoE")) or ui.mode.rotation == 2) and (eyebeamTTD() or unit.isDummy(units.dyn8)) then if cast.eyeBeam(nil,"rect",1,20) then ui.debug("Casting Eye Beam") return true end end -- Blade Dance -- blade_dance,if=variable.blade_dance&!cooldown.metamorphosis.ready&(cooldown.eye_beam.remains>(5-azerite.revolving_blades.rank*3)|(raid_event.adds.in>cooldown&raid_event.adds.in<25)) if cast.able.bladeDance() and not unit.isExplosive("target") and #enemies.yards8 > 0 and var.bladeDance and (cd.metamorphosis.remain() > gcd or not ui.useCDs() or not ui.checked("Metamorphosis")) and ((cd.eyeBeam.remain() > gcd) or ui.mode.eyeBeam == 2) then if cast.bladeDance("player","aoe",1,8) then ui.debug("Casting Blade Dance") return true end end -- Immolation Aura -- immolation_aura if cast.able.immolationAura() and not unit.isExplosive("target") and #enemies.yards8 > 0 then if cast.immolationAura("player","aoe",1,8) then ui.debug("Casting Immolation Aura") return true end end -- Annihilation -- annihilation,if=!variable.pooling_for_blade_dance if cast.able.annihilation() and buff.metamorphosis.exists() and not var.poolForBladeDance then if cast.annihilation() then ui.debug("Casting Annihilation") return true end end -- Felblade -- felblade,if=fury.deficit>=40 if cast.able.felblade() and furyDeficit >= 40 and not cast.last.vengefulRetreat() and unit.distance(units.dyn15) < 5 then if cast.felblade() then ui.debug("Casting Felblade") return true end end -- Chaos Strike -- chaos_strike,if=!variable.pooling_for_blade_dance&!variable.pooling_for_eye_beam if cast.able.chaosStrike() and not var.poolForBladeDance and not var.poolForEyeBeam then if cast.chaosStrike() then ui.debug("Casting Chaos Strike") return true end end -- Fel Rush -- fel_rush,if=talent.demon_blades.enabled&!cooldown.eye_beam.ready&(charges=2|(raid_event.movement.in>10&raid_event.adds.in>10)) if cast.able.felRush() and not unit.isExplosive("target") and unit.facing("player","target",10) and charges.felRush.count() > ui.value("Hold Fel Rush Charge") and talent.demonBlades and cd.eyeBeam.remain() > gcd and charges.felRush.count() == 2 then if ui.mode.mover == 1 and unit.distance("target") < 8 then cancelRushAnimation() elseif not ui.checked("Fel Rush Only In Melee") and (ui.mode.mover == 2 or (unit.distance("target") >= 8 and ui.mode.mover ~= 3)) then if cast.felRush() then ui.debug("Casting Fel Rush [Demon Blades]") return true end end end -- Demon's Bite -- demons_bite if cast.able.demonsBite(units.dyn5) and not talent.demonBlades and furyDeficit >= 30 then if cast.demonsBite(units.dyn5) then ui.debug("Casting Demon's Bite") return true end end -- Throw Glaive -- throw_glaive,if=buff.out_of_range.up if ui.checked("Throw Glaive") and cast.able.throwGlaive() and unit.distance(units.dyn30) > 8 then if cast.throwGlaive(nil,"aoe",1,10) then ui.debug("Casting Throw Glaive [Out of Range]") return true end end -- Fel Rush -- fel_rush,if=movement.distance>15|(buff.out_of_range.up&!talent.momentum.enabled) if not ui.checked("Fel Rush Only In Melee") and not unit.isExplosive("target") and cast.able.felRush() and ui.mode.mover ~= 3 and charges.felRush.count() > ui.value("Hold Fel Rush Charge") and (unit.distance("target") > 15 or (unit.distance("target") > 8 and not talent.momentum)) then if cast.felRush() then ui.debug("Casting Fel Rush [Out of Range]") return true end end -- Throw Glaive -- throw_glaive,if=talent.demon_blades.enabled if ui.checked("Throw Glaive") and cast.able.throwGlaive() and talent.demonBlades then if cast.throwGlaive(nil,"aoe",1,10) then ui.debug("Casting Throw Glaive [Demon Blades]") return true end end end -- End Action List - Demonic -- Action List - Normal actionList.Normal = function() -- Vengeful Retreat -- vengeful_retreat,if=talent.momentum.enabled&buff.prepared.down&time>1 if ui.checked("Vengeful Retreat") and cast.able.vengefulRetreat() and talent.momentum and not buff.prepared.exists() and var.combatTime > 1 and unit.distance(units.dyn5) < 5 then if ui.mode.mover == 1 then cancelRetreatAnimation() elseif ui.mode.mover == 2 then if cast.vengefulRetreat() then ui.debug("Casting Vengeful Retreat [Momentum]") return true end end end -- Fel Rush -- fel_rush,if=(variable.waiting_for_momentum|talent.unbound_chaos.enabled&buff.unbound_chaos.up)&(charges=2|(raid_event.movement.in>10&raid_event.adds.in>10)) if cast.able.felRush() and not unit.isExplosive("target") and unit.facing("player","target",10) and charges.felRush.count() > ui.value("Hold Fel Rush Charge") and (var.waitingForMomentum or (talent.unboundChaos and buff.innerDemon.exists())) then if ui.mode.mover == 1 and unit.distance("target") < 8 then cancelRushAnimation() elseif not ui.checked("Fel Rush Only In Melee") and (ui.mode.mover == 2 or (unit.distance("target") >= 8 and ui.mode.mover ~= 3)) then if cast.felRush() then ui.debug("Casting Fel Rush [Momentum/Unbound Chaos]") return true end end end -- Fel Barrage -- fel_barrage,if=active_enemies>desired_targets|raid_event.adds.in>30 if ui.mode.felBarrage == 1 and not unit.isExplosive("target") and cast.able.felBarrage() -- and (not traits.furiousGaze or (cd.eyeBeam.remain() > 20 and cd.bladeDance > gcd)) and ((ui.mode.rotation == 1 and #enemies.yards8 >= ui.value("Units To AoE")) or (ui.mode.rotation == 2 and #enemies.yards8 > 0)) then if cast.felBarrage("player","aoe",1,8) then ui.debug("Casting Fel Barrage") return true end end -- Death Sweep -- death_sweep,if=variable.blade_dance if cast.able.deathSweep() and not unit.isExplosive("target") and #enemies.yards8 > 0 and buff.metamorphosis.exists() and var.bladeDance then if cast.deathSweep("player","aoe",1,8) then ui.debug("Casting Death Sweep") return true end end -- Immolation Aura -- immolation_aura if cast.able.immolationAura() and not unit.isExplosive("target") and #enemies.yards8 > 0 then if cast.immolationAura("player","aoe",1,8) then ui.debug("Casting Immolation Aura") return true end end -- Glaive Tempest -- glaive_tempest,if=!variable.waiting_for_momentum&(active_enemies>desired_targets|raid_event.adds.in>10) if cast.able.glaiveTempest() and not var.waitingForMomentum and ((ui.mode.rotation == 1 and #enemeies.yards8 > ui.value("Units To AoE")) or ui.mode.rotation == 2 or unit.isBoss(units.dyn5)) then if cast.glaiveTempest("player","aoe",1,8) then ui.debug("Casting Glaive Tempest") return true end end -- Throw Glaive -- throw_glaive,if=conduit.serrated_glaive.enabled&cooldown.eye_beam.remains<6&!buff.metamorphosis.up&!debuff.exposed_wound.up -- if ui.checked("Throw Glaive") and cast.able.throwGlaive() then -- if cast.throwGlaive(nil,"aoe",1,10) then ui.debug("Casting Throw Glaive [Serrated Glaive]") return true end -- end -- Eye Beam -- eye_beam,if=active_enemies>1&(!raid_event.adds.exists|raid_event.adds.up)&!variable.waiting_for_momentum if ui.mode.eyeBeam == 1 and not unit.isExplosive("target") and cast.able.eyeBeam() and enemies.yards20r > 1 and not unit.moving() and not var.waitingForMomentum and (eyebeamTTD() or unit.isDummy(units.dyn8)) then if cast.eyeBeam(nil,"rect",1,20) then ui.debug("Casting Eye Beam [Multi]") return true end end -- Blade Dance -- blade_dance,if=variable.blade_dance if cast.able.bladeDance() and not unit.isExplosive("target") and #enemies.yards8 > 0 and not buff.metamorphosis.exists() and var.bladeDance then if cast.bladeDance("player","aoe",1,8) then ui.debug("Casting Blade Dance") return true end end -- Felblade -- felblade,if=fury.deficit>=40 if cast.able.felblade() and furyDeficit >= 40 and not cast.last.vengefulRetreat() and unit.distance(units.dyn15) < 5 then if cast.felblade() then ui.debug("Casting Fel Blade") return true end end -- Eye Beam -- eye_beam,if=!talent.blind_fury.enabled&!variable.waiting_for_essence_break&raid_event.adds.in>cooldown if ui.mode.eyeBeam == 1 and not unit.isExplosive("target") and cast.able.eyeBeam() and enemies.yards20r > 0 and not unit.moving() and not talent.blindFury and not var.waitingForEssenceBreak and (not talent.momentum or buff.momentum.exists()) and (eyebeamTTD() or unit.isDummy(units.dyn8)) then if cast.eyeBeam(nil,"rect",1,20) then ui.debug("Casting Eye Beam") return true end end -- Annihilation -- annihilation,if=(talent.demon_blades.enabled|!variable.waiting_for_momentum|fury.deficit<30|buff.metamorphosis.remains<5)&!variable.pooling_for_blade_dance&!variable.waiting_for_essence_break if cast.able.annihilation() and buff.metamorphosis.exists() and (talent.demonBlades or not var.waitingForMomentum or furyDeficit < 30 or buff.metamorphosis.remain() < 5) and not var.poolForBladeDance and not var.waitingForEssenceBreak then if cast.annihilation() then ui.debug("Casting Annihilation") return true end end -- Chaos Strike -- chaos_strike,if=(talent.demon_blades.enabled|!variable.waiting_for_momentum|fury.deficit<30)&!variable.pooling_for_meta&!variable.pooling_for_blade_dance&!variable.waiting_for_dark_slash if cast.able.chaosStrike() and not buff.metamorphosis.exists() and (talent.demonBlades or not var.waitingForMomentum or furyDeficit < 30) and not var.poolForMeta and not var.poolForBladeDance and not var.waitingForEssenceBreak then if cast.chaosStrike() then ui.debug("Casting Chaos Strike") return true end end -- Eye Beam -- eye_beam,if=talent.blind_fury.enabled&raid_event.adds.in>cooldown if ui.mode.eyeBeam == 1 and not unit.isExplosive("target") and cast.able.eyeBeam() and enemies.yards20r > 0 and not unit.moving() and talent.blindFury and (not talent.momentum or buff.momentum.exists()) and (eyebeamTTD() or unit.isDummy(units.dyn8)) then if cast.eyeBeam(nil,"rect",1,20) then ui.debug("Casting Eye Beam [Blind Fury]") return true end end -- Demon's Bite -- demons_bite if cast.able.demonsBite(units.dyn5) and not talent.demonBlades and furyDeficit >= 30 then if cast.demonsBite(units.dyn5) then ui.debug("Casting Demon's Bite") return true end end -- Fel Rush -- fel_rush,if=!talent.momentum.enabled&raid_event.movement.in>charges*10&talent.demon_blades.enabled if cast.able.felRush() and not unit.isExplosive("target") and unit.facing("player","target",10) and not talent.momentum and talent.demonBlades and charges.felRush.count() > ui.value("Hold Fel Rush Charge") then if ui.mode.mover == 1 and unit.distance("target") < 8 then cancelRushAnimation() elseif not ui.checked("Fel Rush Only In Melee") and (ui.mode.mover == 2 or (unit.distance("target") >= 8 and ui.mode.mover ~= 3)) then if cast.felRush() then ui.debug("Casting Fel Rush [Demon Blades]") return true end end end -- Felblade -- felblade,if=movement.distance|buff.out_of_range.up if cast.able.felblade() and unit.distance("target") > 8 and not cast.last.vengefulRetreat() and unit.distance("target") >= 10 and unit.distance("target") < 15 then if cast.felblade("target") then ui.debug("Casting Fel Blade [Out of Range") return true end end -- Fel Rush -- fel_rush,if=movement.distance>15|(buff.out_of_range.up&!talent.momentum.enabled) if not ui.checked("Fel Rush Only In Melee") and not unit.isExplosive("target") and cast.able.felRush() and ui.mode.mover ~= 3 and charges.felRush.count() > ui.value("Hold Fel Rush Charge") and (unit.distance("target") > 15 or (unit.distance("target") > 8 and not talent.momentum)) then if cast.felRush() then ui.debug("Casting Fel Rush [Out of Range]") return true end end -- Throw Glaive -- throw_glaive,if=talent.demon_blades.enabled if ui.checked("Throw Glaive") and cast.able.throwGlaive() and talent.demonBlades then if cast.throwGlaive(nil,"aoe",1,10) then ui.debug("Casting Throw Glaive [Demon Blades]") return true end end end -- End Action List - Normal -- Action List - PreCombat actionList.PreCombat = function() if not unit.inCombat() and not (IsFlying() or IsMounted()) then -- Fel Crystal Fragments if not buff.felCrystalInfusion.exists() and use.able.felCrystalFragments() and has.felCrystalFragments() then if use.felCrystalFragments() then ui.debug("Using Fel Crystal Fragments") return true end end -- Flask / Crystal -- flask if ui.value("Elixir") == 1 and var.inRaid and not buff.greaterFlaskOfTheCurrents.exists() and use.able.greaterFlaskOfTheCurrents() then if buff.felFocus.exists() then buff.felFocus.cancel() end if use.greaterFlaskOfTheCurrents() then ui.debug("Using Greater Flask of the Currents") return true end end if ui.value("Elixir") == 2 and not buff.felFocus.exists() and use.able.repurposedFelFocuser() then if not buff.greaterFlaskOfTheCurrents.exists() then if use.repurposedFelFocuser() then ui.debug("Using Repurposed Fel Focuser") return true end end end if ui.value("Elixir") == 3 and not buff.gazeOfTheLegion.exists() and use.able.inquisitorsMenacingEye() then if not buff.greaterFlaskOfTheCurrents.exists() then if use.inquisitorsMenacingEye() then ui.debug("Using Inquisitor's Menacing Eye") return true end end end -- Battle Scarred Augment Rune if ui.checked("Augment Rune") and var.inRaid and not buff.battleScarredAugmentation.exists() and use.able.battleScarredAugmentRune() and var.lastRune + gcd < GetTime() then if use.battleScarredAugmentRune() then ui.debug("Using Battle Scarred Augment Rune") var.lastRune = GetTime() return true end end if ui.checked("Pre-Pull Timer") and ui.pullTimer <= ui.value("Pre-Pull Timer") then -- Potion if ui.value("Potion") ~= 5 and ui.pullTimer <= 1 and (var.inRaid or var.inInstance) then if ui.value("Potion") == 1 and use.able.potionOfUnbridledFury() then use.potionOfUnbridledFury() ui.debug("Using Potion of Unbridled Fury") end end -- Metamorphosis -- metamorphosis,if=!azerite.chaotic_transformation.enabled if ui.useCDs() and ui.checked("Metamorphosis") and cast.able.metamorphosis() and ui.pullTimer <= 1 and not traits.chaoticTransformation.active then if cast.metamorphosis("player") then ui.debug("Casting Metamorphosis [No Chaotic Transformation]") return true end end -- Azshara's Font of Power for i = 13, 14 do local opValue = ui.value("Trinkets") local iValue = i - 12 if (opValue == iValue or opValue == 3) and use.able.slot(i) then if use.able.azsharasFontOfPower(i) and equiped.azsharasFontOfPower(i) and ui.pullTimer <= 5 then use.slot(i) ui.debug("Using Azshara's Font of Power [Pre-Pull]") return end end end end -- End Pre-Pull if ui.checked("M+ Pre-Pull") and var.inMythic and ui.pullTimer <= ui.value("M+ Meta Pre-Pull") then -- Eye Beam if cast.able.eyeBeam() then cast.eyeBeam() ui.debug("Castin Eye Beam [Pre-Pull]") end -- Metamorphosis if ui.checked("Metamorphosis") and cast.able.metamorphosis() then if cast.metamorphosis("player") then ui.debug("Casting Metamorphosis [Pre-Pull]") return true end end end -- End M+ Pre-Pull if unit.valid("target") then if unit.reaction("target","player") < 4 then -- Throw Glaive if ui.checked("Throw Glaive") and cast.able.throwGlaive("target") and #enemies.get(10,"target",true) == 1 and var.solo and ui.checked("Auto Engage") then if cast.throwGlaive("target","aoe") then ui.debug("Casting Throw Glaive [Pre-Pull]") return true end end -- Torment if cast.able.torment("target") and var.solo and ui.checked("Auto Engage") then if cast.torment("target") then ui.debug("Casting Torment [Pre-Pull]") return true end end end -- Start Attack -- auto_attack if unit.distance("target") < 5 then StartAttack() end end end -- End No Combat end -- End Action List - PreCombat ---------------- --- ROTATION --- ---------------- local function runRotation() -------------- --- BR API --- -------------- buff = br.player.buff cast = br.player.cast cd = br.player.cd charges = br.player.charges debuff = br.player.debuff enemies = br.player.enemies equiped = br.player.equiped essence = br.player.essence fury = br.player.power.fury.amount() furyDeficit = br.player.power.fury.deficit() gcd = br.player.unit.gcd(true) has = br.player.has item = br.player.items race = br.player.race ui = br.player.ui unit = br.player.unit units = br.player.units use = br.player.use talent = br.player.talent traits = br.player.traits ------------ --- Vars --- ------------ var.combatTime = getCombatTime() var.falling = getFallTime() var.getHealPot = getHealthPot() var.hasHealPot = hasHealthPot() var.inInstance = unit.instance=="party" var.inMythic = select(3,GetInstanceInfo())==23 var.inRaid = unit.instance=="raid" var.solo = #br.friend == 1 var.flood = (equiped.soulOfTheSlayer() or talent.firstBlood) and 1 or 0 units.get(5) units.get(8) units.get(30) enemies.get(5) enemies.get(8) enemies.get(8,"player",false,true) -- makes enemies.yards8f enemies.get(8,"target") -- makes enemies.yards8t enemies.get(10) enemies.get(20) enemies.get(40) enemies.get(40,"player",false,true) enemies.get(50) enemies.yards20r, enemies.yards20rTable = getEnemiesInRect(10,20,false) enemies.yards25r = getEnemiesInRect(8,25,false) or 0 if cast.active.eyeBeam("player") and buff.metamorphosis.exists() then var.metaExtended = true elseif not buff.metamorphosis.exists() then var.metaExtended = false end -- Blade Dance Variable -- variable,name=blade_dance,value=talent.first_blood.enabled|spell_targets.blade_dance1>=(3-talent.trail_of_ruin.enabled) var.bladeDance = (talent.cycleOfHatred or talent.firstBlood or (ui.mode.rotation == 1 and #enemies.yards8 >= ui.value("Units To AoE")) or ui.mode.rotation == 2) and #enemies.yards8 > 0 and not unit.isExplosive("target") -- Pool for Meta Variable -- variable,name=pooling_for_meta,value=!talent.demonic.enabled&cooldown.metamorphosis.remains<6&fury.deficit>30 var.poolForMeta = ui.checked("Metamorphosis") and ui.useCDs() and not talent.demonic and cd.metamorphosis.remain() < 6 and furyDeficit >= 30 -- Pool for Blade Dance Variable -- variable,name=pooling_for_blade_dance,value=variable.blade_dance&(fury<75-talent.first_blood.enabled*20) var.poolForBladeDance = var.bladeDance and fury < 75 - var.flood * 20 and not unit.isExplosive("target") -- Pool for Eye Beam -- variable,name=pooling_for_eye_beam,value=talent.demonic.enabled&!talent.blind_fury.enabled&cooldown.eye_beam.remains<(gcd.max*2)&fury.deficit>20 var.poolForEyeBeam = talent.demonic and not talent.blindFury and cd.eyeBeam.remain() < (gcd * 2) and furyDeficit >= 20 and not unit.isExplosive("target") -- Waiting for Essence Break -- variable,name=waiting_for_essence_break,value=talent.essence_break.enabled&!variable.pooling_for_blade_dance&!variable.pooling_for_meta&cooldown.essence_break.up var.waitingForEssenceBreak = talent.essenceBreak and not var.poolForBladeDance and not var.poolingForMeta and cd.essenceBreak.ready() -- Wait for Momentum -- variable,name=waiting_for_momentum,value=talent.momentum.enabled&!buff.momentum.up var.waitingForMomentum = talent.momentum and not buff.momentum.exists() -- Reaping Delay -- cycling_variable,name=reaping_delay,op=min,if=essence.breath_of_the_dying.major,value=target.time_to_die var.reapingDelay = function() local lowestTTD = 99 for i = 1, #enemies.yards40f do local thisUnit = enemies.yards40f[i] local thisTTD = unit.ttd(thisUnit) if unit.ttd(thisUnit) < lowestTTD then lowestTTD = thisTTD end end return lowestTTD end -- Fel Barrage Sync Variable -- variable,name=fel_barrage_sync,if=talent.fel_barrage.enabled,value=cooldown.fel_barrage.ready&(((!talent.demonic.enabled|buff.metamorphosis.up)&!variable.waiting_for_momentum&raid_event.adds.in>30)|active_enemies>desired_targets) if talent.felBarrage then var.felBarrageSync = cd.felBarrage.ready() and (((not talent.demonic or buff.metamorphosis.exists()) and not var.waitingForMomentum) or ((ui.mode.rotation == 1 and #enemies.yards8 >= ui.value("Units To AoE")) or (ui.mode.rotation == 2 and #enemies.yards8 > 0))) end -- if ui.mode.mover == 1 and cast.last.vengefulRetreat() then StopFalling(); end -- if IsHackEnabled("NoKnockback") then -- SetHackEnabled("NoKnockback", false) -- end -- Fel Rush Special if unit.inCombat() and ui.checked("Auto Fel Rush After Retreat") and cast.able.felRush() and buff.prepared.exists() and not buff.momentum.exists() and charges.felRush.count() > ui.value("Hold Fel Rush Charge") then if ui.mode.mover == 1 and unit.distance("target") < 8 then cancelRushAnimation() elseif not ui.checked("Fel Rush Only In Melee") and (ui.mode.mover == 2 or (unit.distance("target") >= 8 and ui.mode.mover ~= 3)) then if cast.felRush() then ui.debug("Casting Fel Rush [Special]") return true end end end --------------------- --- Begin Profile --- --------------------- -- Profile Stop | Pause if not unit.inCombat() and not IsMounted() and not unit.exists("target") and var.profileStop then var.profileStop = false elseif (unit.inCombat() and var.profileStop) or (IsMounted() or IsFlying()) or pause() or ui.mode.rotation==4 or cast.active.eyeBeam() then return true else ----------------------- --- Extras Rotation --- ----------------------- if actionList.Extras() then return true end -------------------------- --- Defensive Rotation --- -------------------------- if actionList.Defensive() then return true end ------------------------------ --- Out of Combat Rotation --- ------------------------------ if actionList.PreCombat() then return true end -------------------------- --- In Combat Rotation --- -------------------------- if unit.inCombat() and not IsMounted() and not var.profileStop and unit.valid("target") then ------------------------------ --- In Combat - Interrupts --- ------------------------------ if actionList.Interrupts() then return true end --------------------------- --- SimulationCraft APL --- --------------------------- if ui.value("APL Mode") == 1 then -- Start Attack if unit.distance(units.dyn5) < 5 then StartAttack() end -- Cooldowns -- call_action_list,name=cooldown,if=gcd.remains=0 if cd.global.remain() == 0 then if actionList.Cooldowns() then return true end end -- Pickup Fragments -- pick_up_fragment,if=demon_soul_fragments>0 -- pick_up_fragment,if=fury.deficit>=35&(!azerite.eyes_of_rage.enabled|cooldown.eye_beam.remains>1.4) -- if furyDeficit >= 35 and (not traits.eyesOfRage.active or cd.eyeBeam.remain() > 1.4) then -- ChatOverlay("Low Fury - Pickup Fragments!") -- end -- Throw Glaive -- throw_glaive,if=buff.fel_bombardment.stack=5&(buff.immolation_aura.up|!buff.metamorphosis.up) -- if ui.checked("Throw Glaive") and cast.able.throwGlaive() then -- if cast.throwGlaive(nil,"aoe",1,10) then ui.debug("Casting Throw Glaive [Demon Blades]") return true end -- end -- Call Action List - Dark Slash -- call_action_list,name=essence_break,if=talent.essence_break.enabled&(variable.waiting_for_essence_break|debuff.essence_break.up) if talent.essenceBreak and (var.waitingForEssenceBreak or debuff.essenceBreak.exists(units.dyn5)) then if actionList.EssenceBreak() then return true end end -- Call Action List - Demonic -- run_action_list,name=demonic,if=talent.demonic.enabled if talent.demonic then if actionList.Demonic() then return true end else -- Call Action List - Normal -- run_action_list,name=normal if actionList.Normal() then return true end end end -- End SimC APL end --End In Combat end --End Rotation Logic end -- End runRotation local id = 577 if br.rotations[id] == nil then br.rotations[id] = {} end tinsert(br.rotations[id],{ name = rotationName, toggles = createToggles, options = createOptions, run = runRotation, })
gpl-3.0
arventwei/WioEngine
Tools/jamplus/src/luaplus/Src/Modules/getopt/test/testgetopt.lua
1
2573
getopt = require 'getopt' do local options = getopt.makeOptions{ getopt.Option {{"gen"}, "Set a project generator", "Req", 'GENERATOR'}, getopt.Option {{"gui"}, "Pop up a GUI to set options"}, getopt.Option {{"compiler"}, "Set the default compiler used to build with", "Req", 'COMPILER'}, getopt.Option {{"postfix"}, "Extra text for the IDE project name"}, getopt.Option {{"config"}, "Filename of additional configuration file", "Req", 'CONFIG'}, getopt.Option {{"jamflags"}, "Extra flags to make available for each invocation of Jam. Specify in KEY=VALUE form.", "Req", 'JAMBASE_FLAGS' }, getopt.Option {{"jamexepath"}, "The full path to the Jam executable when the default location won't suffice.", "Req", 'JAMEXEPATH' }, } local nonOpts, opts, errors = getopt.getOpt (arg, options) if #errors > 0 or (#nonOpts ~= 1 and #nonOpts ~= 2) then print (table.concat (errors, "\n") .. "\n" .. getopt.usageInfo ("Usage: jam --workspace [options] <source-jamfile> <path-to-destination>", options)) os.exit(-1) end end if false then options = getopt.makeOptions ({ getopt.Option {{"verbose", "v"}, "verbosely list files"}, getopt.Option {{"output", "o"}, "dump to FILE", "Opt", "FILE"}, getopt.Option {{"name", "n"}, "only dump USER's files", "Req", "USER"}, }) function test (cmdLine) local nonOpts, opts, errors = getopt.getOpt (cmdLine, options) if #errors == 0 then print ("options=" .. tostring (opts) .. " args=" .. tostring (nonOpts) .. "\n") else print (table.concat (errors, "\n") .. "\n" .. getopt.usageInfo ("Usage: foobar [OPTION...] FILE...", options)) end end -- FIXME: Turn the following documentation into unit tests prog = {name = "foobar"} -- for errors -- Example runs: test {"foo", "-v"} -- options={verbose={1}} args={1=foo} test {"foo", "--", "-v"} -- options={} args={1=foo,2=-v} test {"-o", "-V", "-name", "bar", "--name=baz"} -- options={name={"baz"},version={1},output={1}} args={} test {"-foo"} -- unrecognized option `-foo' -- Usage: foobar [OPTION]... [FILE]... -- -- -v, -verbose verbosely list files -- -o, -output[=FILE] dump to FILE -- -n, -name=USER only dump USER's files -- -V, -version output version information and exit -- -h, -help display this help and exit getopt.usage() end
mit
guard163/tarantool
test/app/lua/serializer_test.lua
7
11702
local ffi = require('ffi') local function rt(test, s, x, t) local buf1 = s.encode(x) local x1, offset1 = s.decode(buf1) local xstr if type(x) == "table" then xstr = "table" elseif ffi.istype('float', x) then xstr = string.format('%0.2f (ffi float)', tonumber(x)) elseif ffi.istype('double', x) then xstr = string.format('%0.2f (ffi double)', tonumber(x)) elseif ffi.istype("bool", x) then xstr = string.format("%s (ffi bool)", x == 1 and "true" or "false") elseif type(x) == "cdata" then xstr = tostring(x) xstr = xstr:match("cdata<.+>:") or xstr else xstr = tostring(x) end test:is_deeply(x, x1, "encode/decode for "..xstr) if t ~= nil then test:is(type(x1), t, "encode/decode type for "..xstr) end end local function test_unsigned(test, s) test:plan(118) rt(test, s, 0, "number") rt(test, s, 0LL, "number") rt(test, s, 0ULL, "number") rt(test, s, 1, "number") rt(test, s, 1LL, "number") rt(test, s, 1ULL, "number") rt(test, s, 127, "number") rt(test, s, 127LL, "number") rt(test, s, 127ULL, "number") rt(test, s, 128, "number") rt(test, s, 128LL, "number") rt(test, s, 128ULL, "number") rt(test, s, 255, "number") rt(test, s, 255LL, "number") rt(test, s, 255ULL, "number") rt(test, s, 256, "number") rt(test, s, 256LL, "number") rt(test, s, 256ULL, "number") rt(test, s, 65535, "number") rt(test, s, 65535LL, "number") rt(test, s, 65535ULL, "number") rt(test, s, 65536, "number") rt(test, s, 65536LL, "number") rt(test, s, 65536ULL, "number") rt(test, s, 4294967294, "number") rt(test, s, 4294967294LL, "number") rt(test, s, 4294967294ULL, "number") rt(test, s, 4294967295, "number") rt(test, s, 4294967295LL, "number") rt(test, s, 4294967295ULL, "number") rt(test, s, 4294967296, "number") rt(test, s, 4294967296LL, "number") rt(test, s, 4294967296ULL, "number") rt(test, s, 4294967297, "number") rt(test, s, 4294967297LL, "number") rt(test, s, 4294967297ULL, "number") -- 1e52 - maximum int that can be stored to double without losing precision rt(test, s, 4503599627370495, "number") rt(test, s, 4503599627370495LL, "number") rt(test, s, 4503599627370495ULL, "number") rt(test, s, 4503599627370496, "cdata") rt(test, s, 4503599627370496LL, "cdata") rt(test, s, 4503599627370496ULL, "cdata") rt(test, s, 9223372036854775807LL, "cdata") rt(test, s, 9223372036854775807ULL, "cdata") rt(test, s, 9223372036854775808ULL, "cdata") rt(test, s, 9223372036854775809ULL, "cdata") rt(test, s, 18446744073709551614ULL, "cdata") rt(test, s, 18446744073709551615ULL, "cdata") rt(test, s, -1ULL, "cdata") rt(test, s, ffi.new('uint8_t', 128), 'number') rt(test, s, ffi.new('int8_t', -128), 'number') rt(test, s, ffi.new('uint16_t', 128), 'number') rt(test, s, ffi.new('int16_t', -128), 'number') rt(test, s, ffi.new('uint32_t', 128), 'number') rt(test, s, ffi.new('int32_t', -128), 'number') rt(test, s, ffi.new('uint64_t', 128), 'number') rt(test, s, ffi.new('int64_t', -128), 'number') rt(test, s, ffi.new('char', 128), 'number') rt(test, s, ffi.new('char', -128), 'number') end local function test_signed(test, s) test:plan(48) rt(test, s, -1, 'number') rt(test, s, -1LL, 'number') rt(test, s, -31, 'number') rt(test, s, -31LL, 'number') rt(test, s, -32, 'number') rt(test, s, -32LL, 'number') rt(test, s, -127, 'number') rt(test, s, -127LL, 'number') rt(test, s, -128, 'number') rt(test, s, -128LL, 'number') rt(test, s, -32767, 'number') rt(test, s, -32767LL, 'number') rt(test, s, -32768, 'number') rt(test, s, -32768LL, 'number') rt(test, s, -2147483647, 'number') rt(test, s, -2147483647LL, 'number') rt(test, s, -2147483648, 'number') rt(test, s, -2147483648LL, 'number') -- 1e52 - maximum int that can be stored to double without losing precision rt(test, s, -4503599627370495, "number") rt(test, s, -4503599627370495LL, "number") rt(test, s, -4503599627370496, "cdata") rt(test, s, -4503599627370496LL, "cdata") rt(test, s, -9223372036854775806LL, 'cdata') rt(test, s, -9223372036854775807LL, 'cdata') end local function test_double(test, s) test:plan(s.cfg and 15 or 9) rt(test, s, -1.1) rt(test, s, 3.1415926535898) rt(test, s, -3.1415926535898) rt(test, s, -1e100) rt(test, s, 1e100) rt(test, s, ffi.new('float', 123456)) rt(test, s, ffi.new('double', 123456)) rt(test, s, ffi.new('float', 12.121)) rt(test, s, ffi.new('double', 12.121)) if not s.cfg then return end -- -- cfg: encode_invalid_numbers / decode_invalid_numbers -- local nan = 0/0 local inf = 1/0 local ss = s.new() ss.cfg{encode_invalid_numbers = false} test:ok(not pcall(ss.encode, nan), "encode exception on nan") test:ok(not pcall(ss.encode, inf), "encode exception on inf") ss.cfg{encode_invalid_numbers = true} local xnan = ss.encode(nan) local xinf = ss.encode(inf) ss.cfg{decode_invalid_numbers = false} test:ok(not pcall(ss.decode, xnan), "decode exception on nan") test:ok(not pcall(ss.decode, xinf), "decode exception on inf") ss.cfg{decode_invalid_numbers = true} rt(test, s, nan) rt(test, s, inf) ss = nil end local function test_boolean(test, s) test:plan(4) rt(test, s, false) rt(test, s, true) rt(test, s, ffi.new('bool', true)) rt(test, s, ffi.new('bool', false)) end local function test_string(test, s) test:plan(8) rt(test, s, "") rt(test, s, "abcde") rt(test, s, "Кудыкины горы") -- utf-8 rt(test, s, string.rep("x", 33)) rt(test, s, '$a\t $') rt(test, s, '$a\t $') rt(test, s, [[$a\t $]]) rt(test, s, [[$a\\t $]]) end local function test_nil(test, s) test:plan(6) rt(test, s, nil) rt(test, s, s.NULL) test:iscdata(s.NULL, 'void *', '.NULL is cdata') test:ok(s.NULL == nil, '.NULL == nil') rt(test, s, {1, 2, 3, s.NULL, 5}) local t = s.decode(s.encode({1, 2, 3, [5] = 5})) test:is(t[4], s.NULL, "sparse array with NULL") end local function test_table(test, s, is_array, is_map) test:plan(s.cfg and 26 or 8) rt(test, s, {}) test:ok(is_array(s.encode({})), "empty table is array") rt(test, s, {1, 2, 3}) test:ok(is_array(s.encode({1, 2, 3})), "array is array") rt(test, s, {k1 = 'v1', k2 = 'v2', k3 = 'v3'}) test:ok(is_map(s.encode({k1 = 'v1', k2 = 'v2', k3 = 'v3'})), "map is map") -- utf-8 pairs rt(test, s, {Метапеременная = { 'Метазначение' }}) rt(test, s, {test = { 'Результат' }}) if not s.cfg then return end -- -- encode_load_metatables -- local arr = setmetatable({1, 2, 3, k1 = 'v1', k2 = 'v2', 4, 5}, { __serialize = 'seq'}) local map = setmetatable({1, 2, 3, 4, 5}, { __serialize = 'map'}) local obj = setmetatable({}, { __serialize = function(x) return 'serialize' end }) local ss = s.new() ss.cfg{encode_load_metatables = false} -- map test:ok(is_map(ss.encode(arr)), "array ignore __serialize") -- array test:ok(is_array(ss.encode(map)), "map ignore __serialize") -- array test:ok(is_array(ss.encode(obj)), "object ignore __serialize") ss.cfg{encode_load_metatables = true} -- array test:ok(is_array(ss.encode(arr)), "array load __serialize") -- map test:ok(is_map(ss.encode(map)), "map load __serialize") -- string (from __serialize hook) test:is(ss.decode(ss.encode(obj)), "serialize", "object load __serialize") ss = nil -- -- decode_save_metatables -- local arr = {1, 2, 3} local map = {k1 = 'v1', k2 = 'v2', k3 = 'v3'} ss = s.new() ss.cfg{decode_save_metatables = false} test:isnil(getmetatable(ss.decode(ss.encode(arr))), "array __serialize") test:isnil(getmetatable(ss.decode(ss.encode(map))), "map __serialize") ss.cfg{decode_save_metatables = true} test:is(getmetatable(ss.decode(ss.encode(arr))).__serialize, "seq", "array save __serialize") test:is(getmetatable(ss.decode(ss.encode(map))).__serialize, "map", "map save __serialize") ss = nil -- -- encode_sparse_convert / encode_sparse_ratio / encode_sparse_safe -- local ss = s.new() ss.cfg{encode_sparse_ratio = 2, encode_sparse_safe = 10} ss.cfg{encode_sparse_convert = false} test:ok(is_array(ss.encode({[1] = 1, [3] = 3, [4] = 4, [6] = 6, [9] = 9, [12] = 12})), "sparse convert off") test:ok(is_array(ss.encode({[1] = 1, [3] = 3, [4] = 4, [6] = 6, [10] = 10})), "sparse convert off") test:ok(not pcall(ss.encode, {[1] = 1, [3] = 3, [4] = 4, [6] = 6, [12] = 12}), "excessively sparse array") ss.cfg{encode_sparse_convert = true} test:ok(is_array(ss.encode({[1] = 1, [3] = 3, [4] = 4, [6] = 6, [9] = 9, [12] = 12})), "sparse convert on") test:ok(is_array(ss.encode({[1] = 1, [3] = 3, [4] = 4, [6] = 6, [10] = 10})), "sparse convert on") test:ok(is_map(ss.encode({[1] = 1, [3] = 3, [4] = 4, [6] = 6, [12] = 12})), "sparse convert on") -- map test:ok(is_map(ss.encode({1, 2, 3, 4, 5, [100] = 100})), "sparse safe 1") ss.cfg{encode_sparse_safe = 100} -- array test:ok(is_array(ss.encode({1, 2, 3, 4, 5, [100] = 100})), "sparse safe 2") ss = nil end local function test_ucdata(test, s) test:plan(10) -- -- encode_use_unpack / encode_use_tostring -- ffi.cdef[[struct serializer_cdata_test {}]] local ctype = ffi.typeof('struct serializer_cdata_test') --# setopt delimiter ';' ffi.metatype(ctype, { __index = { __serialize = function(obj) return 'unpack' end, }, __tostring = function(obj) return 'tostring' end }); --# setopt delimiter '' local cdata = ffi.new(ctype) -- use fiber's userdata for test (supports both __serialize and __tostring) local udata = require('fiber').self() local ss = s.new() ss.cfg{ encode_load_metatables = false, encode_use_tostring = false, encode_invalid_as_nil = false } test:ok(not pcall(ss.encode, cdata), "encode exception on cdata") test:ok(not pcall(ss.encode, udata), "encode exception on udata") ss.cfg{encode_invalid_as_nil = true} test:ok(ss.decode(ss.encode(cdata)) == nil, "encode_invalid_as_nil") test:ok(ss.decode(ss.encode(udata)) == nil, "encode_invalid_as_nil") ss.cfg{encode_load_metatables = true, encode_use_tostring = false} test:is(ss.decode(ss.encode(cdata)), 'unpack', 'cdata __serialize') test:istable(ss.decode(ss.encode(udata)), 'udata __serialize') ss.cfg{encode_load_metatables = false, encode_use_tostring = true} test:is(ss.decode(ss.encode(cdata)), 'tostring', 'cdata __tostring') test:isstring(ss.decode(ss.encode(udata)), 'udata __tostring') ss.cfg{encode_load_metatables = true, encode_use_tostring = true} test:is(ss.decode(ss.encode(cdata)), 'unpack', 'cdata hook priority') test:istable(ss.decode(ss.encode(udata)), 'udata hook priority') ss = nil end return { test_unsigned = test_unsigned; test_signed = test_signed; test_double = test_double; test_boolean = test_boolean; test_string = test_string; test_nil = test_nil; test_table = test_table; test_ucdata = test_ucdata; }
bsd-2-clause
tianxiawuzhei/cocos-quick-lua
quick/bin/mac/jit/bcsave.lua
41
18267
---------------------------------------------------------------------------- -- LuaJIT module to save/list bytecode. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module saves or lists the bytecode for an input file. -- It's run by the -b command line option. -- ------------------------------------------------------------------------------ local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local bit = require("bit") -- Symbol name prefix for LuaJIT bytecode. local LJBC_PREFIX = "luaJIT_BC_" ------------------------------------------------------------------------------ local function usage() io.stderr:write[[ Save LuaJIT bytecode: luajit -b[options] input output -l Only list bytecode. -s Strip debug info (default). -g Keep debug info. -n name Set module name (default: auto-detect from input name). -t type Set output file type (default: auto-detect from output name). -a arch Override architecture for object files (default: native). -o os Override OS for object files (default: native). -e chunk Use chunk string as input. -- Stop handling options. - Use stdin as input and/or stdout as output. File types: c h obj o raw (default) ]] os.exit(1) end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function readfile(input) if type(input) == "function" then return input end if input == "-" then input = nil end return check(loadfile(input)) end local function savefile(name, mode) if name == "-" then return io.stdout end return check(io.open(name, mode)) end ------------------------------------------------------------------------------ local map_type = { raw = "raw", c = "c", h = "h", o = "obj", obj = "obj", } local map_arch = { x86 = true, x64 = true, arm = true, arm64 = true, ppc = true, mips = true, mipsel = true, } local map_os = { linux = true, windows = true, osx = true, freebsd = true, netbsd = true, openbsd = true, dragonfly = true, solaris = true, } local function checkarg(str, map, err) str = string.lower(str) local s = check(map[str], "unknown ", err) return s == true and str or s end local function detecttype(str) local ext = string.match(string.lower(str), "%.(%a+)$") return map_type[ext] or "raw" end local function checkmodname(str) check(string.match(str, "^[%w_.%-]+$"), "bad module name") return string.gsub(str, "[%.%-]", "_") end local function detectmodname(str) if type(str) == "string" then local tail = string.match(str, "[^/\\]+$") if tail then str = tail end local head = string.match(str, "^(.*)%.[^.]*$") if head then str = head end str = string.match(str, "^[%w_.%-]+") else str = nil end check(str, "cannot derive module name, use -n name") return string.gsub(str, "[%.%-]", "_") end ------------------------------------------------------------------------------ local function bcsave_tail(fp, output, s) local ok, err = fp:write(s) if ok and output ~= "-" then ok, err = fp:close() end check(ok, "cannot write ", output, ": ", err) end local function bcsave_raw(output, s) local fp = savefile(output, "wb") bcsave_tail(fp, output, s) end local function bcsave_c(ctx, output, s) local fp = savefile(output, "w") if ctx.type == "c" then fp:write(string.format([[ #ifdef _cplusplus extern "C" #endif #ifdef _WIN32 __declspec(dllexport) #endif const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname)) else fp:write(string.format([[ #define %s%s_SIZE %d static const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) end local t, n, m = {}, 0, 0 for i=1,#s do local b = tostring(string.byte(s, i)) m = m + #b + 1 if m > 78 then fp:write(table.concat(t, ",", 1, n), ",\n") n, m = 0, #b + 1 end n = n + 1 t[n] = b end bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n") end local function bcsave_elfobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint32_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF32header; typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint64_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF64header; typedef struct { uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize; } ELF32sectheader; typedef struct { uint32_t name, type; uint64_t flags, addr, ofs, size; uint32_t link, info; uint64_t align, entsize; } ELF64sectheader; typedef struct { uint32_t name, value, size; uint8_t info, other; uint16_t sectidx; } ELF32symbol; typedef struct { uint32_t name; uint8_t info, other; uint16_t sectidx; uint64_t value, size; } ELF64symbol; typedef struct { ELF32header hdr; ELF32sectheader sect[6]; ELF32symbol sym[2]; uint8_t space[4096]; } ELF32obj; typedef struct { ELF64header hdr; ELF64sectheader sect[6]; ELF64symbol sym[2]; uint8_t space[4096]; } ELF64obj; ]] local symname = LJBC_PREFIX..ctx.modname local is64, isbe = false, false if ctx.arch == "x64" or ctx.arch == "arm64" then is64 = true elseif ctx.arch == "ppc" or ctx.arch == "mips" then isbe = true end -- Handle different host/target endianess. local function f32(x) return x end local f16, fofs = f32, f32 if ffi.abi("be") ~= isbe then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end if is64 then local two32 = ffi.cast("int64_t", 2^32) function fofs(x) return bit.bswap(x)*two32 end else fofs = f32 end end -- Create ELF object and fill in header. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj") local hdr = o.hdr if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi. local bf = assert(io.open("/bin/ls", "rb")) local bs = bf:read(9) bf:close() ffi.copy(o, bs, 9) check(hdr.emagic[0] == 127, "no support for writing native object files") else hdr.emagic = "\127ELF" hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0 end hdr.eclass = is64 and 2 or 1 hdr.eendian = isbe and 2 or 1 hdr.eversion = 1 hdr.type = f16(1) hdr.machine = f16(({ x86=3, x64=62, arm=40, arm64=183, ppc=20, mips=8, mipsel=8 })[ctx.arch]) if ctx.arch == "mips" or ctx.arch == "mipsel" then hdr.flags = 0x50001006 end hdr.version = f32(1) hdr.shofs = fofs(ffi.offsetof(o, "sect")) hdr.ehsize = f16(ffi.sizeof(hdr)) hdr.shentsize = f16(ffi.sizeof(o.sect[0])) hdr.shnum = f16(6) hdr.shstridx = f16(2) -- Fill in sections and symbols. local sofs, ofs = ffi.offsetof(o, "space"), 1 for i,name in ipairs{ ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack", } do local sect = o.sect[i] sect.align = fofs(1) sect.name = f32(ofs) ffi.copy(o.space+ofs, name) ofs = ofs + #name+1 end o.sect[1].type = f32(2) -- .symtab o.sect[1].link = f32(3) o.sect[1].info = f32(1) o.sect[1].align = fofs(8) o.sect[1].ofs = fofs(ffi.offsetof(o, "sym")) o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0])) o.sect[1].size = fofs(ffi.sizeof(o.sym)) o.sym[1].name = f32(1) o.sym[1].sectidx = f16(4) o.sym[1].size = fofs(#s) o.sym[1].info = 17 o.sect[2].type = f32(3) -- .shstrtab o.sect[2].ofs = fofs(sofs) o.sect[2].size = fofs(ofs) o.sect[3].type = f32(3) -- .strtab o.sect[3].ofs = fofs(sofs + ofs) o.sect[3].size = fofs(#symname+1) ffi.copy(o.space+ofs+1, symname) ofs = ofs + #symname + 2 o.sect[4].type = f32(1) -- .rodata o.sect[4].flags = fofs(2) o.sect[4].ofs = fofs(sofs + ofs) o.sect[4].size = fofs(#s) o.sect[5].type = f32(1) -- .note.GNU-stack o.sect[5].ofs = fofs(sofs + ofs + #s) -- Write ELF object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_peobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint16_t arch, nsects; uint32_t time, symtabofs, nsyms; uint16_t opthdrsz, flags; } PEheader; typedef struct { char name[8]; uint32_t vsize, vaddr, size, ofs, relocofs, lineofs; uint16_t nreloc, nline; uint32_t flags; } PEsection; typedef struct __attribute((packed)) { union { char name[8]; uint32_t nameref[2]; }; uint32_t value; int16_t sect; uint16_t type; uint8_t scl, naux; } PEsym; typedef struct __attribute((packed)) { uint32_t size; uint16_t nreloc, nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel, unused[3]; } PEsymaux; typedef struct { PEheader hdr; PEsection sect[2]; // Must be an even number of symbol structs. PEsym sym0; PEsymaux sym0aux; PEsym sym1; PEsymaux sym1aux; PEsym sym2; PEsym sym3; uint32_t strtabsize; uint8_t space[4096]; } PEobj; ]] local symname = LJBC_PREFIX..ctx.modname local is64 = false if ctx.arch == "x86" then symname = "_"..symname elseif ctx.arch == "x64" then is64 = true end local symexport = " /EXPORT:"..symname..",DATA " -- The file format is always little-endian. Swap if the host is big-endian. local function f32(x) return x end local f16 = f32 if ffi.abi("be") then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end end -- Create PE object and fill in header. local o = ffi.new("PEobj") local hdr = o.hdr hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch]) hdr.nsects = f16(2) hdr.symtabofs = f32(ffi.offsetof(o, "sym0")) hdr.nsyms = f32(6) -- Fill in sections and symbols. o.sect[0].name = ".drectve" o.sect[0].size = f32(#symexport) o.sect[0].flags = f32(0x00100a00) o.sym0.sect = f16(1) o.sym0.scl = 3 o.sym0.name = ".drectve" o.sym0.naux = 1 o.sym0aux.size = f32(#symexport) o.sect[1].name = ".rdata" o.sect[1].size = f32(#s) o.sect[1].flags = f32(0x40300040) o.sym1.sect = f16(2) o.sym1.scl = 3 o.sym1.name = ".rdata" o.sym1.naux = 1 o.sym1aux.size = f32(#s) o.sym2.sect = f16(2) o.sym2.scl = 2 o.sym2.nameref[1] = f32(4) o.sym3.sect = f16(-1) o.sym3.scl = 2 o.sym3.value = f32(1) o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant. ffi.copy(o.space, symname) local ofs = #symname + 1 o.strtabsize = f32(ofs + 4) o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs) ffi.copy(o.space + ofs, symexport) ofs = ofs + #symexport o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs) -- Write PE object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_machobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags; } mach_header; typedef struct { mach_header; uint32_t reserved; } mach_header_64; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint32_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint64_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command_64; typedef struct { char sectname[16], segname[16]; uint32_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2; } mach_section; typedef struct { char sectname[16], segname[16]; uint64_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2, reserved3; } mach_section_64; typedef struct { uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; } mach_symtab_command; typedef struct { int32_t strx; uint8_t type, sect; int16_t desc; uint32_t value; } mach_nlist; typedef struct { uint32_t strx; uint8_t type, sect; uint16_t desc; uint64_t value; } mach_nlist_64; typedef struct { uint32_t magic, nfat_arch; } mach_fat_header; typedef struct { uint32_t cputype, cpusubtype, offset, size, align; } mach_fat_arch; typedef struct { struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[1]; mach_nlist sym_entry; uint8_t space[4096]; } mach_obj; typedef struct { struct { mach_header_64 hdr; mach_segment_command_64 seg; mach_section_64 sec; mach_symtab_command sym; } arch[1]; mach_nlist_64 sym_entry; uint8_t space[4096]; } mach_obj_64; typedef struct { mach_fat_header fat; mach_fat_arch fat_arch[2]; struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[2]; mach_nlist sym_entry; uint8_t space[4096]; } mach_fat_obj; ]] local symname = '_'..LJBC_PREFIX..ctx.modname local isfat, is64, align, mobj = false, false, 4, "mach_obj" if ctx.arch == "x64" then is64, align, mobj = true, 8, "mach_obj_64" elseif ctx.arch == "arm" then isfat, mobj = true, "mach_fat_obj" elseif ctx.arch == "arm64" then is64, align, isfat, mobj = true, 8, true, "mach_fat_obj" else check(ctx.arch == "x86", "unsupported architecture for OSX") end local function aligned(v, a) return bit.band(v+a-1, -a) end local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE. -- Create Mach-O object and fill in header. local o = ffi.new(mobj) local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12}, arm64={0x01000007,0x0100000c} })[ctx.arch] local cpusubtype = ({ x86={3}, x64={3}, arm={3,9}, arm64={3,0} })[ctx.arch] if isfat then o.fat.magic = be32(0xcafebabe) o.fat.nfat_arch = be32(#cpusubtype) end -- Fill in sections and symbols. for i=0,#cpusubtype-1 do local ofs = 0 if isfat then local a = o.fat_arch[i] a.cputype = be32(cputype[i+1]) a.cpusubtype = be32(cpusubtype[i+1]) -- Subsequent slices overlap each other to share data. ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0]) a.offset = be32(ofs) a.size = be32(mach_size-ofs+#s) end local a = o.arch[i] a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface a.hdr.cputype = cputype[i+1] a.hdr.cpusubtype = cpusubtype[i+1] a.hdr.filetype = 1 a.hdr.ncmds = 2 a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym) a.seg.cmd = is64 and 0x19 or 0x1 a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec) a.seg.vmsize = #s a.seg.fileoff = mach_size-ofs a.seg.filesize = #s a.seg.maxprot = 1 a.seg.initprot = 1 a.seg.nsects = 1 ffi.copy(a.sec.sectname, "__data") ffi.copy(a.sec.segname, "__DATA") a.sec.size = #s a.sec.offset = mach_size-ofs a.sym.cmd = 2 a.sym.cmdsize = ffi.sizeof(a.sym) a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs a.sym.nsyms = 1 a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs a.sym.strsize = aligned(#symname+2, align) end o.sym_entry.type = 0xf o.sym_entry.sect = 1 o.sym_entry.strx = 1 ffi.copy(o.space+1, symname) -- Write Macho-O object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, mach_size)) bcsave_tail(fp, output, s) end local function bcsave_obj(ctx, output, s) local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write this file type") if ctx.os == "windows" then return bcsave_peobj(ctx, output, s, ffi) elseif ctx.os == "osx" then return bcsave_machobj(ctx, output, s, ffi) else return bcsave_elfobj(ctx, output, s, ffi) end end ------------------------------------------------------------------------------ local function bclist(input, output) local f = readfile(input) require("jit.bc").dump(f, savefile(output, "w"), true) end local function bcsave(ctx, input, output) local f = readfile(input) local s = string.dump(f, ctx.strip) local t = ctx.type if not t then t = detecttype(output) ctx.type = t end if t == "raw" then bcsave_raw(output, s) else if not ctx.modname then ctx.modname = detectmodname(input) end if t == "obj" then bcsave_obj(ctx, output, s) else bcsave_c(ctx, output, s) end end end local function docmd(...) local arg = {...} local n = 1 local list = false local ctx = { strip = true, arch = jit.arch, os = string.lower(jit.os), type = false, modname = false, } while n <= #arg do local a = arg[n] if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then table.remove(arg, n) if a == "--" then break end for m=2,#a do local opt = string.sub(a, m, m) if opt == "l" then list = true elseif opt == "s" then ctx.strip = true elseif opt == "g" then ctx.strip = false else if arg[n] == nil or m ~= #a then usage() end if opt == "e" then if n ~= 1 then usage() end arg[1] = check(loadstring(arg[1])) elseif opt == "n" then ctx.modname = checkmodname(table.remove(arg, n)) elseif opt == "t" then ctx.type = checkarg(table.remove(arg, n), map_type, "file type") elseif opt == "a" then ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture") elseif opt == "o" then ctx.os = checkarg(table.remove(arg, n), map_os, "OS name") else usage() end end end else n = n + 1 end end if list then if #arg == 0 or #arg > 2 then usage() end bclist(arg[1], arg[2] or "-") else if #arg ~= 2 then usage() end bcsave(ctx, arg[1], arg[2]) end end ------------------------------------------------------------------------------ -- Public module functions. return { start = docmd -- Process -b command line option. }
mit
aperezdc/lua-eol
examples/upng-info.lua
2
1348
#! /usr/bin/env lua -- -- upnginfo.lua -- Copyright (C) 2015 Adrian Perez <aperez@igalia.com> -- -- Distributed under terms of the MIT license. -- local upng = require "modularize" { "upng", prefix = "upng_" } local function enum_value_string(enum, value) for i = 1, #enum do local item = enum[i] if value == item.value then return item.name end end return tostring(value) .. " (no symbolic name?)" end local print_item_format = " %-10s %s\n" local function print_item(key, value) io.stdout:write(print_item_format:format(key, tostring(value))) end local function info(img) local fmt = upng.get_format(img) print_item("format", enum_value_string(upng.types.format, fmt)) print_item("channels", upng.get_components(img)) print_item("width", upng.get_width(img)) print_item("height", upng.get_height(img)) print_item("bpp", upng.get_bpp(img)) print_item("depth", upng.get_bitdepth(img)) end for _, path in ipairs(arg) do local img = upng.new_from_file(path) if img ~= nil then if upng.decode(img) == 0 then print("" .. path .. "") info(img) else io.stderr:write(path .. ": error ") local err = upng.get_error(img) io.stderr:write(enum_value_string(upng.types.error, err)) end upng.free(img) else io.stderr:write("Cannot open '" .. path .. "'\n") end end
mit
dicebox/minetest-france
games/minetest_game/mods/fire/init.lua
6
8613
-- Global namespace for functions fire = {} -- -- Items -- -- Flame nodes minetest.register_node("fire:basic_flame", { drawtype = "firelike", tiles = { { name = "fire_basic_flame_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1 }, }, }, inventory_image = "fire_basic_flame.png", paramtype = "light", light_source = 13, walkable = false, buildable_to = true, sunlight_propagates = true, damage_per_second = 4, groups = {igniter = 2, dig_immediate = 3, not_in_creative_inventory = 1}, on_timer = function(pos) local f = minetest.find_node_near(pos, 1, {"group:flammable"}) if not f then minetest.remove_node(pos) return end -- Restart timer return true end, drop = "", on_construct = function(pos) minetest.get_node_timer(pos):start(math.random(30, 60)) end, }) minetest.register_node("fire:permanent_flame", { description = "Permanent Flame", drawtype = "firelike", tiles = { { name = "fire_basic_flame_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1 }, }, }, inventory_image = "fire_basic_flame.png", paramtype = "light", light_source = 13, walkable = false, buildable_to = true, sunlight_propagates = true, damage_per_second = 4, groups = {igniter = 2, dig_immediate = 3}, drop = "", }) -- Flint and steel minetest.register_tool("fire:flint_and_steel", { description = "Flint and Steel", inventory_image = "fire_flint_steel.png", sound = {breaks = "default_tool_breaks"}, on_use = function(itemstack, user, pointed_thing) local pt = pointed_thing minetest.sound_play( "fire_flint_and_steel", {pos = pt.above, gain = 0.5, max_hear_distance = 8} ) if pt.type == "node" then local node_under = minetest.get_node(pt.under).name local nodedef = minetest.registered_nodes[node_under] if not nodedef then return end local player_name = user:get_player_name() if minetest.is_protected(pt.under, player_name) then minetest.chat_send_player(player_name, "This area is protected") return end if nodedef.on_ignite then nodedef.on_ignite(pt.under, user) elseif minetest.get_item_group(node_under, "flammable") >= 1 and minetest.get_node(pt.above).name == "air" then minetest.set_node(pt.above, {name = "fire:basic_flame"}) end end if not minetest.setting_getbool("creative_mode") then -- Wear tool local wdef = itemstack:get_definition() itemstack:add_wear(1000) -- Tool break sound if itemstack:get_count() == 0 and wdef.sound and wdef.sound.breaks then minetest.sound_play(wdef.sound.breaks, {pos = pt.above, gain = 0.5}) end return itemstack end end }) minetest.register_craft({ output = "fire:flint_and_steel", recipe = { {"default:flint", "default:steel_ingot"} } }) -- Override coalblock to enable permanent flame above -- Coalblock is non-flammable to avoid unwanted basic_flame nodes minetest.override_item("default:coalblock", { after_destruct = function(pos, oldnode) pos.y = pos.y + 1 if minetest.get_node(pos).name == "fire:permanent_flame" then minetest.remove_node(pos) end end, on_ignite = function(pos, igniter) local flame_pos = {x = pos.x, y = pos.y + 1, z = pos.z} if minetest.get_node(flame_pos).name == "air" then minetest.set_node(flame_pos, {name = "fire:permanent_flame"}) end end, }) -- -- Sound -- local flame_sound = minetest.setting_getbool("flame_sound") if flame_sound == nil then -- Enable if no setting present flame_sound = true end if flame_sound then local handles = {} local timer = 0 -- Parameters local radius = 8 -- Flame node search radius around player local cycle = 3 -- Cycle time for sound updates -- Update sound for player function fire.update_player_sound(player) local player_name = player:get_player_name() -- Search for flame nodes in radius around player local ppos = player:getpos() local areamin = vector.subtract(ppos, radius) local areamax = vector.add(ppos, radius) local fpos, num = minetest.find_nodes_in_area( areamin, areamax, {"fire:basic_flame", "fire:permanent_flame"} ) -- Total number of flames in radius local flames = (num["fire:basic_flame"] or 0) + (num["fire:permanent_flame"] or 0) -- Stop previous sound if handles[player_name] then minetest.sound_stop(handles[player_name]) handles[player_name] = nil end -- If flames if flames > 0 then -- Find centre of flame positions local fposmid = fpos[1] -- If more than 1 flame if #fpos > 1 then local fposmin = areamax local fposmax = areamin for i = 1, #fpos do local fposi = fpos[i] if fposi.x > fposmax.x then fposmax.x = fposi.x end if fposi.y > fposmax.y then fposmax.y = fposi.y end if fposi.z > fposmax.z then fposmax.z = fposi.z end if fposi.x < fposmin.x then fposmin.x = fposi.x end if fposi.y < fposmin.y then fposmin.y = fposi.y end if fposi.z < fposmin.z then fposmin.z = fposi.z end end fposmid = vector.divide(vector.add(fposmin, fposmax), 2) end -- Play sound local handle = minetest.sound_play( "fire_fire", { pos = fposmid, to_player = player_name, gain = math.min(0.06 * (1 + flames * 0.125), 0.18), max_hear_distance = 32, loop = true, -- In case of lag } ) -- Store sound handle for this player if handle then handles[player_name] = handle end end end -- Cycle for updating players sounds minetest.register_globalstep(function(dtime) timer = timer + dtime if timer < cycle then return end timer = 0 local players = minetest.get_connected_players() for n = 1, #players do fire.update_player_sound(players[n]) end end) -- Stop sound and clear handle on player leave minetest.register_on_leaveplayer(function(player) local player_name = player:get_player_name() if handles[player_name] then minetest.sound_stop(handles[player_name]) handles[player_name] = nil end end) end -- Deprecated function kept temporarily to avoid crashes if mod fire nodes call it function fire.update_sounds_around(pos) end -- -- ABMs -- -- Extinguish all flames quickly with water, snow, ice minetest.register_abm({ label = "Extinguish flame", nodenames = {"fire:basic_flame", "fire:permanent_flame"}, neighbors = {"group:puts_out_fire"}, interval = 3, chance = 1, catch_up = false, action = function(pos, node, active_object_count, active_object_count_wider) minetest.remove_node(pos) minetest.sound_play("fire_extinguish_flame", {pos = pos, max_hear_distance = 16, gain = 0.15}) end, }) -- Enable the following ABMs according to 'enable fire' setting local fire_enabled = minetest.setting_getbool("enable_fire") if fire_enabled == nil then -- New setting not specified, check for old setting. -- If old setting is also not specified, 'not nil' is true. fire_enabled = not minetest.setting_getbool("disable_fire") end if not fire_enabled then -- Remove basic flames only if fire disabled minetest.register_abm({ label = "Remove disabled fire", nodenames = {"fire:basic_flame"}, interval = 7, chance = 1, catch_up = false, action = minetest.remove_node, }) else -- Fire enabled -- Ignite neighboring nodes, add basic flames minetest.register_abm({ label = "Ignite flame", nodenames = {"group:flammable"}, neighbors = {"group:igniter"}, interval = 7, chance = 12, catch_up = false, action = function(pos, node, active_object_count, active_object_count_wider) -- If there is water or stuff like that around node, don't ignite if minetest.find_node_near(pos, 1, {"group:puts_out_fire"}) then return end local p = minetest.find_node_near(pos, 1, {"air"}) if p then minetest.set_node(p, {name = "fire:basic_flame"}) end end, }) -- Remove flammable nodes around basic flame minetest.register_abm({ label = "Remove flammable nodes", nodenames = {"fire:basic_flame"}, neighbors = "group:flammable", interval = 5, chance = 18, catch_up = false, action = function(pos, node, active_object_count, active_object_count_wider) local p = minetest.find_node_near(pos, 1, {"group:flammable"}) if p then local flammable_node = minetest.get_node(p) local def = minetest.registered_nodes[flammable_node.name] if def.on_burn then def.on_burn(p) else minetest.remove_node(p) minetest.check_for_falling(p) end end end, }) end
gpl-3.0
silverhammermba/awesome
lib/wibox/widget/systray.lua
3
5410
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2010 Uli Schlachter -- @release @AWESOME_VERSION@ -- @classmod wibox.widget.systray --------------------------------------------------------------------------- local wbase = require("wibox.widget.base") local beautiful = require("beautiful") local util = require("awful.util") local capi = { awesome = awesome, screen = screen } local setmetatable = setmetatable local error = error local abs = math.abs local systray = { mt = {} } local instance = nil local horizontal = true local base_size = nil local reverse = false local display_on_screen = "primary" --- The systray background color. -- @beautiful beautiful.bg_systray -- @param string The color (string like "#ff0000" only) --- The systray icon spacing. -- @beautiful beautiful.systray_icon_spacing -- @tparam[opt=0] integer The icon spacing local function should_display_on(s) if display_on_screen == "primary" then return s == capi.screen.primary end return s == display_on_screen end function systray:draw(context, cr, width, height) if not should_display_on(context.screen) then return end local x, y, _, _ = wbase.rect_to_device_geometry(cr, 0, 0, width, height) local num_entries = capi.awesome.systray() local bg = beautiful.bg_systray or beautiful.bg_normal or "#000000" local spacing = beautiful.systray_icon_spacing or 0 if context and not context.wibox then error("The systray widget can only be placed inside a wibox.") end -- Figure out if the cairo context is rotated local dir_x, dir_y = cr:user_to_device_distance(1, 0) local is_rotated = abs(dir_x) < abs(dir_y) local in_dir, ortho, base if horizontal then in_dir, ortho = width, height is_rotated = not is_rotated else ortho, in_dir = width, height end if ortho * num_entries <= in_dir then base = ortho else base = in_dir / num_entries end capi.awesome.systray(context.wibox.drawin, math.ceil(x), math.ceil(y), base, is_rotated, bg, reverse, spacing) end function systray:fit(context, width, height) if not should_display_on(context.screen) then return 0, 0 end local num_entries = capi.awesome.systray() local base = base_size local spacing = beautiful.systray_icon_spacing or 0 if num_entries == 0 then return 0, 0 end if base == nil then if width < height then base = width else base = height end end base = base + spacing if horizontal then return base * num_entries - spacing, base end return base, base * num_entries - spacing end -- Check if the function was called like :foo() or .foo() and do the right thing local function get_args(self, ...) if self == instance then return ... end return self, ... end --- Set the size of a single icon. -- If this is set to nil, then the size is picked dynamically based on the -- available space. Otherwise, any single icon has a size of `size`x`size`. -- @tparam integer|nil size The base size function systray:set_base_size(size) base_size = get_args(self, size) if instance then instance:emit_signal("widget::layout_changed") end end --- Decide between horizontal or vertical display. -- @tparam boolean horiz Use horizontal mode? function systray:set_horizontal(horiz) horizontal = get_args(self, horiz) if instance then instance:emit_signal("widget::layout_changed") end end --- Should the systray icons be displayed in reverse order? -- @tparam boolean rev Display in reverse order function systray:set_reverse(rev) reverse = get_args(self, rev) if instance then instance:emit_signal("widget::redraw_needed") end end --- Set the screen that the systray should be displayed on. -- This can either be a screen, in which case the systray will be displayed on -- exactly that screen, or the string `"primary"`, in which case it will be -- visible on the primary screen. The default value is "primary". -- @tparam screen|"primary" s The screen to display on. function systray:set_screen(s) display_on_screen = get_args(self, s) if instance then instance:emit_signal("widget::layout_changed") end end --- Create the systray widget. -- Note that this widget can only exist once. -- @tparam boolean revers Show in the opposite direction -- @treturn table The new `systray` widget -- @function wibox.widget.systray local function new(revers) local ret = wbase.make_widget() util.table.crush(ret, systray, true) if revers then ret:set_reverse(true) end capi.awesome.connect_signal("systray::update", function() ret:emit_signal("widget::layout_changed") ret:emit_signal("widget::redraw_needed") end) capi.screen.connect_signal("primary_changed", function() if display_on_screen == "primary" then ret:emit_signal("widget::layout_changed") end end) return ret end function systray.mt:__call(...) if not instance then instance = new(...) end return instance end return setmetatable(systray, systray.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
interfaceware/iguana-web-apps
scratch/shared/channelmanager/backend.lua
2
11761
-- -- Private helpers -- --local function unpackC local function statuses() local StatusHtml = '<div class="%s"></div>' local Statuses = { on='status-green', off='status-grey', error='status-red', transition='status-yellow'} return StatusHtml, Statuses end local function components() local ComponentsHtml = [[<img alt="%s" width="38" height="16" border="0" title="" src="/channelmanager/icon_%s.gif"> <img alt="arrow" width="11" height="16" border="0" title="" src="/channelmanager/arrow.gif"> <img alt="%s" width="38" height="16" border="0" title="" src="/channelmanager/icon_%s.gif">]] local Components = { ['From Translator'] = 'TRANS', ['To Translator'] = 'TRANS', ['From File'] = 'FILE', ['To File'] = 'FILE', ['From HTTPS'] = 'HTTPS', ['To HTTPS'] = 'HTTPS', ['LLP Listener'] = 'LLP', ['LLP Client'] = 'LLP', ['From Channel'] = 'QUE', ['To Channel'] = 'QUE', ['To Plugin'] = 'PLG-N', ['From Plugin'] = 'PLG-N'} return ComponentsHtml, Components end local function exportSummaryBtn(Channel) local Html = string.format( '<a href=\"%s#export-summary&channel=%s\">Export</a>', app.config.approot, Channel.Name:nodeValue():gsub(" ","_")) return Html end local function importSummaryBtn(Channel) local Html = string.format( '<a href=\"%s#import-summary&channel=%s\">Import</a>', app.config.approot, Channel.Name:nodeValue():gsub(" ","_")) return Html end local function exportConfirmBtn(Channel) local Html = string.format( '<a href=\"%s#export-channel&channel=%s\">Export</a>', app.config.approot, Channel.Name:nodeValue():gsub(" ","_")) return Html end local function importConfirmBtn(Channel) local Html = string.format( '<a href=\"%s#import-channel&channel=%s\">Import</a>', app.config.approot, Channel.Name:nodeValue():gsub(" ","_")) return Html end local function inspectAndWrite(T, ChDir) local Path = ChDir .. "/" for k,v in pairs(T) do if type(v) == 'table' then if not os.fs.stat(Path .. k) then os.fs.mkdir(Path .. k) end inspectAndWrite(v, Path .. k) end if type(v) == 'string' and not k:find("::") -- Metadata then local F = io.open(Path .. k, "w+") F:write(v) F:close() end end end local function writeZippedFiles(B64, Dir, Guid, Dest) local D = filter.base64.dec(B64) local T = filter.zip.inflate(D) local TranPath = Dir..'/'..Dest trace(TranPath) if not os.fs.stat(TranPath) then os.fs.mkdir(TranPath) end inspectAndWrite(T[Guid], TranPath) if (T.other) then inspectAndWrite(T.other, Dir..'/other') end if (T.shared) then inspectAndWrite(T.shared, Dir..'/shared') end end -- -- End helpers -- -- -- -- -- -- -- -- -- The App -- -- Require this app object in the top of your main script for -- your web app. Make in *non-local* so the webserver can use it. local app = {} app.ui = require 'channelmanager.presentation' app.config = require 'channelmanager.config' app.actions = app.config.actions function app.default() return app.ui["/channelmanager/index.html"] end function app.listChannels(Request) -- switch this to iguana.status once it's available local StatusXml = iguana.status() local Conf = xml.parse{data=StatusXml}.IguanaStatus local Results = {aaData={}, aoColumns={}} Results.aoColumns = { {['sTitle'] = 'Name', ['sType'] = 'string'}, {['sTitle'] = 'Status', ['sType'] = 'html'}, {['sTitle'] = 'Type', ['sType'] = 'string'}, {['sTitle'] = 'Msgs Queued', ['sType'] = 'string'}, {['sTitle'] = 'Total Errs', ['sType'] = 'string'}, {['sTitle'] = 'Export', ['sType'] = 'html'}, {['sTitle'] = 'Import', ['sType'] = 'html'}} local StatusHtml, Statuses = statuses() ComponentsHtml, Components = components() for i=1, Conf:childCount('Channel') do local Ch = Conf:child('Channel', i) Results.aaData[i] = { Ch.Name:nodeValue(), string.format( StatusHtml, Statuses[Ch.Status:nodeValue()]), string.format( ComponentsHtml, Components[Ch.Source:nodeValue()], Components[Ch.Source:nodeValue()], Components[Ch.Destination:nodeValue()], Components[Ch.Destination:nodeValue()]), Ch.MessagesQueued:nodeValue(), Ch.TotalErrors:nodeValue(), exportSummaryBtn(Ch), importSummaryBtn(Ch)} end return Results end -- A summary of the channel and a chance to confirm. function app.exportSummary(Request) local Status = iguana.status() local ConfXml = xml.parse{data=Status}.IguanaStatus for i=1, ConfXml:childCount('Channel') do local Ch = ConfXml:child('Channel', i) if Ch.Name:nodeValue():gsub(" ","_") == Request.get_params.channel then return { ChannelName = Ch.Name:nodeValue(), ExportPath = app.config.channelExportPath, ConfirmBtn = exportConfirmBtn(Ch)} end end end function app.importSummary(Request) local Status = iguana.status() local ConfXml = xml.parse{data=Status}.IguanaStatus for i=1, ConfXml:childCount('Channel') do local Ch = ConfXml:child('Channel', i) if Ch.Name:nodeValue():gsub(" ","_") == Request.get_params.channel then return { ChannelName = Ch.Name:nodeValue(), ExportPath = app.config.channelExportPath, ConfirmBtn = importConfirmBtn(Ch)} end end end function app.importChannel(Request) local ChGuid = Request.get_params.guid local Dir = app.config.channelExportPath local ChConf = xml.parse{ data=io.open(Dir.."/"..Request.get_params.channel..".xml") :read("*a")} local Tmp = Dir.."/".."scratch" local ChannelName = ChConf.channel.name:nodeValue():gsub(" ","_") print(Tmp) if not os.fs.stat(Tmp) then os.fs.mkdir(Tmp) end --local PrjDir = Dir.."/"..ChannelName.."_http" --trace(PrjDir) --[[ os.execute("cp -R "..PrjDir.." "..Tmp) ]] local PrjDir if ChConf.channel.use_message_filter:nodeValue() == 'true' then PrjDir = Dir.."/"..ChannelName.."_message_filter" end trace(PrjDir) -- Open the project.prj file and pull in needed files local PrjF = json.parse{ data=io.open( PrjDir.."/project.prj") :read("*a")} -- Copy over project files for k,v in os.fs.glob(PrjDir.."/*") do if not os.fs.stat(Tmp.."/"..ChConf.channel.guid) then os.fs.mkdir(Tmp.."/"..ChConf.channel.guid) end os.execute("cp "..k.." "..Tmp .."/"..ChConf.channel.guid) end -- Move over dependencies for k,v in pairs(PrjF['OtherDependencies']) do if not os.fs.stat(Tmp.."/other") then os.fs.mkdir(Tmp.."/other") end print(k,v) os.execute("cp "..Dir.."/other/"..v.. " "..Tmp.."/other") end for k,v in pairs(PrjF['LuaDependencies']) do if not os.fs.stat(Tmp.."/shared") then os.fs.mkdir(Tmp.."/shared") end if os.fs.stat(Dir.."/shared/"..v..".lua") then print('hi') os.execute("cp "..Dir.."/shared/"..v..".lua "..Tmp.."/shared") elseif v:find(".") then local PackageDir = v:sub(1, v:find('%.')-1) -- It's a package, copy from top down. os.execute("cp -R "..Dir.."/shared/"..PackageDir.. " "..Tmp.."/shared") end end -- Zip and import first project os.execute("cd "..Dir.."/scratch && zip -r scratch.zip *") ---[[ require 'iguanaServer' local Web = iguana.webInfo() local ChAPI = iguanaServer.connect{ url='http://localhost:'..Web.web_config.port, username='admin', password='password'} -- Add the channel local NewCfg = ChAPI:addChannel{ config=ChConf, live=true }.channel local B64 = filter.base64.enc(io.open(Dir.."/scratch/scratch.zip"):read("*a")) ChAPI:importProject{project=B64, guid=NewCfg.message_filter.translator_guid:nodeValue() ,live=true} --]] -- Zip and import filter -- Zip and import second project --[[ for k,v in os.fs.glob(app.config.channelExportPath .. "/EB004E5EB4123CD02D0722A4B0D6895F/*") do print(k,v) end ]] --[[ for f in os.fs.glob( app.config.channelExportPath .. "/EB004E5EB4123CD02D0722A4B0D6895F" .. "/E76737E42964D985AA06049A663C1D2B/*") do -- grab the file name if f:match("/project.prj") then local F = io.open(f) local C = F:read("*a") local J = json.parse{data=C} --for k,v in pairs(J) do -- print(k,v) --end --trace(J.LuaDependencies[1]) end end ]] end -- The export has been confirmed. function app.exportChannel(Request) -- grab the channel configuration local Web = iguana.webInfo() local CnlCfg = net.http.post{ url='http://localhost:'..Web.web_config.port..'/get_channel_config', auth={password='password', username='admin'}, parameters={name=Request.get_params.channel:gsub("_"," ")}, live=true} trace(CnlCfg) local Ch = xml.parse{data=CnlCfg}.channel local Path = app.config.channelExportPath if not os.fs.stat(Path) then os.fs.mkdir(Path) end local ChannelDir = app.config.channelExportPath local ChannelName = Ch.name:nodeValue():gsub(' ','_'):lower() -- Write the config fragment for the channel. This is -- required for importing. local F = io.open(ChannelDir .. "/"..ChannelName..".xml", "w") F:write(CnlCfg) F:close() -- switch on component types require 'iguanaServer' local ChAPI = iguanaServer.connect{ url='http://localhost:'..Web.web_config.port, username='admin', password='password'} -- TODO - all the other components... if Ch.to_mapper then B64ProjectContents = ChAPI:exportProject{ guid=Ch.to_mapper.guid:nodeValue(), live=true} writeZippedFiles(B64ProjectContents, ChannelDir, Ch.to_mapper.guid:nodeValue(), ChannelName.."_to_mapper") end if Ch.from_mapper then ChAPI:exportProject{ guid=Ch.from_mapper.guid:nodeValue(), live=true} writeZippedFiles(B64ProjectContents, ChannelDir) end if Ch.message_filter and Ch.message_filter.translator_guid and Ch.message_filter.translator_guid:nodeValue() ~= '00000000000000000000000000000000' then B64ProjectContents = ChAPI:exportProject{ guid=Ch.message_filter.translator_guid:nodeValue(), live=true} writeZippedFiles(B64ProjectContents, ChannelDir, Ch.message_filter.translator_guid:nodeValue(), ChannelName.."_message_filter") end -- TODO: confirm this one works if Ch.from_llp_listener and Ch.from_llp_listener.ack_script then B64ProjectContents = ChAPI:exportProject{ guid=Ch.from_llp_listener.ack_script:nodeValue(), live=true} writeZippedFiles(B64ProjectContents, ChannelDir) end -- TODO: confirm this one works if Ch.from_http and Ch.from_http.guid then B64ProjectContents = ChAPI:exportProject{ guid=Ch.from_http.guid:nodeValue(), live=true} writeZippedFiles(B64ProjectContents, ChannelDir, Ch.from_http.guid:nodeValue(), ChannelName.."_from_http") end local Message = 'Channel was exported successfully' return {message = Message} end return app
mit
135yshr/Holocraft-server
world/Plugins/APIDump/Hooks/OnBlockToPickups.lua
36
2438
return { HOOK_BLOCK_TO_PICKUPS = { CalledWhen = "A block is about to be dug ({{cPlayer|player}}, {{cEntity|entity}} or natural reason), plugins may override what pickups that will produce.", DefaultFnName = "OnBlockToPickups", -- also used as pagename Desc = [[ This callback gets called whenever a block is about to be dug. This includes {{cPlayer|players}} digging blocks, entities causing blocks to disappear ({{cTNTEntity|TNT}}, Endermen) and natural causes (water washing away a block). Plugins may override the amount and kinds of pickups this action produces. ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the block resides" }, { Name = "Digger", Type = "{{cEntity}} descendant", Notes = "The entity causing the digging. May be a {{cPlayer}}, {{cTNTEntity}} or even nil (natural causes)" }, { Name = "BlockX", Type = "number", Notes = "X-coord of the block" }, { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" }, { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" }, { Name = "BlockType", Type = "BLOCKTYPE", Notes = "Block type of the block" }, { Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "Block meta of the block" }, { Name = "Pickups", Type = "{{cItems}}", Notes = "Items that will be spawned as pickups" }, }, Returns = [[ If the function returns false or no value, the next callback in the hook chain will be called. If the function returns true, no other callbacks in the chain will be called.</p> <p> Either way, the server will then spawn pickups specified in the Pickups parameter, so to disable pickups, you need to Clear the object first, then return true. ]], CodeExamples = { { Title = "Modify pickups", Desc = "This example callback function makes tall grass drop diamonds when digged by natural causes (washed away by water).", Code = [[ function OnBlockToPickups(a_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_Pickups) if (a_Digger ~= nil) then -- Not a natural cause return false; end if (a_BlockType ~= E_BLOCK_TALL_GRASS) then -- Not a tall grass being washed away return false; end -- Remove all pickups suggested by Cuberite: a_Pickups:Clear(); -- Drop a diamond: a_Pickups:Add(cItem(E_ITEM_DIAMOND)); return true; end; ]], }, } , -- CodeExamples }, -- HOOK_BLOCK_TO_PICKUPS }
mit
mqmaker/witi-openwrt
package/ramips/ui/luci-mtk/src/modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
73
11663
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- -- Data init -- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() if not uci:get("network", "wan") then uci:section("network", "interface", "wan", {proto="none", ifname=" "}) uci:save("network") uci:commit("network") end local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local wifidevs = {} local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end wlcursor:foreach("wireless", "wifi-device", function(section) table.insert(wifidevs, section[".name"]) end) -- Main Map -- m = Map("wireless", translate("Wifi"), translate("Here you can configure installed wifi devices.")) m:chain("network") -- Status Table -- s = m:section(Table, ifaces, translate("Networks")) link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and iwinfo.bssid or "-" end channel = s:option(DummyValue, "channel", translate("Channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("Protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("Mode")) encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) power = s:option(DummyValue, "_power", translate("Power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d dBm" % iwinfo.txpower or "-" end scan = s:option(Button, "_scan", translate("Scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end -- WLAN-Scan-Table -- t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment")) function scan.write(self, section) m.autoapply = false t2.render = t2._render local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) if iwinfo then local _, cell for _, cell in ipairs(iwinfo.scanlist) do t2.data[#t2.data+1] = { Quality = "%d/%d" %{ cell.quality, cell.quality_max }, ESSID = cell.ssid, Address = cell.bssid, Mode = cell.mode, ["Encryption key"] = cell.encryption.enabled and "On" or "Off", ["Signal level"] = "%d dBm" % cell.signal, ["Noise level"] = "%d dBm" % iwinfo.noise } end end end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("Link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return self.map:get(section, "ESSID") end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("Mode")) chan = t2:option(DummyValue, "channel", translate("Channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) t2:option(DummyValue, "Signal level", translate("Signal")) t2:option(DummyValue, "Noise level", translate("Noise")) if #wifidevs < 1 then return m end -- Config Section -- s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices")) s.addremove = false en = s:option(Flag, "disabled", translate("enable")) en.rmempty = false en.enabled = "0" en.disabled = "1" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local hwtype = m:get(wifidevs[1], "type") if hwtype == "atheros" then mode = s:option(ListValue, "hwmode", translate("Mode")) mode.override_values = true mode:value("", "auto") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true end ch = s:option(Value, "channel", translate("Channel")) for i=1, 14 do ch:value(i, i .. " (2.4 GHz)") end s = m:section(TypedSection, "wifi-iface", translate("Local Network")) s.anonymous = true s.addremove = false s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) local devs = {} luci.model.uci.cursor():foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("Device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Provide (Access Point)")) mode:value("adhoc", translate("Independent (Ad-Hoc)")) mode:value("sta", translate("Join (Client)")) function mode.write(self, section, value) if value == "sta" then local oldif = m.uci:get("network", "wan", "ifname") if oldif and oldif ~= " " then m.uci:set("network", "wan", "_ifname", oldif) end m.uci:set("network", "wan", "ifname", " ") self.map:set(section, "network", "wan") else if m.uci:get("network", "wan", "_ifname") then m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("Encryption")) encr.override_values = true encr:value("none", "No Encryption") encr:value("wep", "WEP") if hwtype == "atheros" or hwtype == "mac80211" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") if hostapd and supplicant then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode") encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"}) elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"}) encr:value("wpa", "WPA-Radius", {mode="ap"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}) encr:value("wpa", "WPA-EAP", {mode="sta"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end key = s:option(Value, "key", translate("Key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key:depends("encryption", "psk+psk2") key:depends("encryption", "psk-mixed") key:depends({mode="ap", encryption="wpa"}) key:depends({mode="ap", encryption="wpa2"}) key.rmempty = true key.password = true server = s:option(Value, "server", translate("Radius-Server")) server:depends({mode="ap", encryption="wpa"}) server:depends({mode="ap", encryption="wpa2"}) server.rmempty = true port = s:option(Value, "port", translate("Radius-Port")) port:depends({mode="ap", encryption="wpa"}) port:depends({mode="ap", encryption="wpa2"}) port.rmempty = true if hwtype == "atheros" or hwtype == "mac80211" then nasid = s:option(Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid.rmempty = true eaptype = s:option(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"}) privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"}) auth = s:option(Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) identity = s:option(Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) password = s:option(Value, "password", translate("Password")) password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) password:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) end if hwtype == "atheros" or hwtype == "broadcom" then iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hide.rmempty = true hide:depends("mode", "ap") end if hwtype == "mac80211" or hwtype == "atheros" then bssid:depends({mode="adhoc"}) end if hwtype == "broadcom" then bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end return m
gpl-2.0
matija-hustic/OpenRA
mods/ra/maps/soviet-04b/soviet04b-AI.lua
19
3108
IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end IdlingUnits = function() local lazyUnits = Greece.GetGroundAttackers() Utils.Do(lazyUnits, function(unit) Trigger.OnDamaged(unit, function() Trigger.ClearAll(unit) Trigger.AfterDelay(0, function() IdleHunt(unit) end) end) end) end BasePower = { type = "powr", pos = CVec.New(-4, -2), cost = 300, exists = true } BaseBarracks = { type = "tent", pos = CVec.New(-8, 1), cost = 400, exists = true } BaseProc = { type = "proc", pos = CVec.New(-5, 1), cost = 1400, exists = true } BaseWeaponsFactory = { type = "weap", pos = CVec.New(-12, -1), cost = 2000, exists = true } BaseBuildings = { BasePower, BaseBarracks, BaseProc, BaseWeaponsFactory } BuildBase = function() for i,v in ipairs(BaseBuildings) do if not v.exists then BuildBuilding(v) return end end Trigger.AfterDelay(DateTime.Seconds(10), BuildBase) end BuildBuilding = function(building) Trigger.AfterDelay(Actor.BuildTime(building.type), function() if CYard.IsDead or CYard.Owner ~= Greece then return elseif Harvester.IsDead and Greece.Resources <= 299 then return end local actor = Actor.Create(building.type, true, { Owner = Greece, Location = GreeceCYard.Location + building.pos }) Greece.Cash = Greece.Cash - building.cost building.exists = true Trigger.OnKilled(actor, function() building.exists = false end) Trigger.OnDamaged(actor, function(building) if building.Owner == Greece and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.AfterDelay(DateTime.Seconds(10), BuildBase) end) end ProduceInfantry = function() if not BaseBarracks.exists then return elseif Harvester.IsDead and Greece.Resources <= 299 then return end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(AlliedInfantryTypes) } local Path = Utils.Random(AttackPaths) Greece.Build(toBuild, function(unit) InfAttack[#InfAttack + 1] = unit[1] if #InfAttack >= 10 then SendUnits(InfAttack, Path) InfAttack = { } Trigger.AfterDelay(DateTime.Minutes(2), ProduceInfantry) else Trigger.AfterDelay(delay, ProduceInfantry) end end) end ProduceArmor = function() if not BaseWeaponsFactory.exists then return elseif Harvester.IsDead and Greece.Resources <= 599 then return end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(AlliedArmorTypes) } local Path = Utils.Random(AttackPaths) Greece.Build(toBuild, function(unit) ArmorAttack[#ArmorAttack + 1] = unit[1] if #ArmorAttack >= 6 then SendUnits(ArmorAttack, Path) ArmorAttack = { } Trigger.AfterDelay(DateTime.Minutes(3), ProduceArmor) else Trigger.AfterDelay(delay, ProduceArmor) end end) end SendUnits = function(units, waypoints) Utils.Do(units, function(unit) if not unit.IsDead then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) unit.Hunt() end end) end
gpl-3.0
Olivine-Labs/luassert
src/languages/ar.lua
7
1694
local s = require('say') s:set_namespace("ar") s:set("assertion.same.positive", "تُوُقِّعَ تَماثُلُ الكائِنات.\nتَمَّ إدخال:\n %s.\nبَينَما كانَ مِن المُتَوقَّع:\n %s.") s:set("assertion.same.negative", "تُوُقِّعَ إختِلافُ الكائِنات.\nتَمَّ إدخال:\n %s.\nبَينَما كانَ مِن غَيرِ المُتَوقَّع:\n %s.") s:set("assertion.equals.positive", "تُوُقِّعَ أن تَتَساوىْ الكائِنات.\nتمَّ إِدخال:\n %s.\nبَينَما كانَ من المُتَوقَّع:\n %s.") s:set("assertion.equals.negative", "تُوُقِّعَ ألّا تَتَساوىْ الكائِنات.\nتمَّ إِدخال:\n %s.\nبَينَما كانَ مِن غير المُتًوقَّع:\n %s.") s:set("assertion.unique.positive", "تُوُقِّعَ أَنْ يَكونَ الكائِنٌ فَريد: \n%s") s:set("assertion.unique.negative", "تُوُقِّعَ أنْ يَكونَ الكائِنٌ غَيرَ فَريد: \n%s") s:set("assertion.error.positive", "تُوُقِّعَ إصدارُ خطأْ.") s:set("assertion.error.negative", "تُوُقِّعَ عدم إصدارِ خطأ.") s:set("assertion.truthy.positive", "تُوُقِّعَت قيمةٌ صَحيحة، بينما كانت: \n%s") s:set("assertion.truthy.negative", "تُوُقِّعَت قيمةٌ غيرُ صَحيحة، بينما كانت: \n%s") s:set("assertion.falsy.positive", "تُوُقِّعَت قيمةٌ خاطِئة، بَينَما كانت: \n%s") s:set("assertion.falsy.negative", "تُوُقِّعَت قيمةٌ غيرُ خاطِئة، بَينَما كانت: \n%s")
mit
135yshr/Holocraft-server
world/Plugins/ProtectionAreas/CommandHandlers.lua
6
7921
-- CommandHandlers.lua -- Defines the individual command handlers --- Handles the ProtAdd command function HandleAddArea(a_Split, a_Player) -- Command syntax: /protection add username1 [username2] [username3] ... if (#a_Split < 3) then a_Player:SendMessage(g_Msgs.ErrExpectedListOfUsernames); return true; end -- Get the cuboid that the player had selected local CmdState = GetCommandStateForPlayer(a_Player); if (CmdState == nil) then a_Player:SendMessage(g_Msgs.ErrCmdStateNilAddArea); return true; end local Cuboid = CmdState:GetCurrentCuboid(); if (Cuboid == nil) then a_Player:SendMessage(g_Msgs.ErrNoAreaWanded); return true; end -- Put all allowed players into a table: AllowedNames = {}; for i = 3, #a_Split do table.insert(AllowedNames, a_Split[i]); end -- Add the area to the storage local AreaID = g_Storage:AddArea(Cuboid, a_Player:GetWorld():GetName(), a_Player:GetName(), AllowedNames); a_Player:SendMessage(string.format(g_Msgs.AreaAdded, AreaID)); -- Reload all currently logged in players ReloadAllPlayersInWorld(a_Player:GetWorld():GetName()); return true; end function HandleAddAreaCoords(a_Split, a_Player) -- Command syntax: /protection addc x1 z1 x2 z2 username1 [username2] [username3] ... if (#a_Split < 7) then a_Player:SendMessage(g_Msgs.ErrExpectedCoordsUsernames); return true; end -- Convert the coords to a cCuboid local x1, z1 = tonumber(a_Split[3]), tonumber(a_Split[4]); local x2, z2 = tonumber(a_Split[5]), tonumber(a_Split[6]); if ((x1 == nil) or (z1 == nil) or (x2 == nil) or (z2 == nil)) then a_Player:SendMessage(g_Msgs.ErrParseCoords); return true; end local Cuboid = cCuboid(x1, 0, z1, x2, 255, z1); Cuboid:Sort(); -- Put all allowed players into a table: AllowedNames = {}; for i = 7, #a_Split do table.insert(AllowedNames, a_Split[i]); end -- Add the area to the storage local AreaID = g_Storage:AddArea(Cuboid, a_Player:GetWorld():GetName(), a_Player:GetName(), AllowedNames); a_Player:SendMessage(string.format(g_Msgs.AreaAdded, AreaID)); -- Reload all currently logged in players ReloadAllPlayersInWorld(a_Player:GetWorld():GetName()); return true; end function HandleAddAreaUser(a_Split, a_Player) -- Command syntax: /protection user add AreaID username1 [username2] [username3] ... if (#a_Split < 5) then a_Player:SendMessage(g_Msgs.ErrExpectedAreaIDUsernames); return true; end -- Put all allowed players into a table: AllowedNames = {}; for i = 5, #a_Split do table.insert(AllowedNames, a_Split[i]); end -- Add the area to the storage if (not(g_Storage:AddAreaUsers( tonumber(a_Split[4]), a_Player:GetWorld():GetName(), a_Player:GetName(), AllowedNames)) ) then LOGWARNING("g_Storage:AddAreaUsers failed"); a_Player:SendMessage(g_Msgs.ErrDBFailAddUsers); return true; end if (#AllowedNames == 0) then a_Player:SendMessage(g_Msgs.AllUsersAlreadyAllowed); else a_Player:SendMessage(string.format(g_Msgs.UsersAdded, table.concat(AllowedNames, ", "))); end -- Reload all currently logged in players ReloadAllPlayersInWorld(a_Player:GetWorld():GetName()); return true; end function HandleDelArea(a_Split, a_Player) -- Command syntax: /protection del AreaID if (#a_Split ~= 3) then a_Player:SendMessage(g_Msgs.ErrExpectedAreaID); return true; end -- Parse the AreaID local AreaID = tonumber(a_Split[3]); if (AreaID == nil) then a_Player:SendMessage(g_Msgs.ErrParseAreaID); return true; end -- Delete the area g_Storage:DelArea(a_Player:GetWorld():GetName(), AreaID); a_Player:SendMessage(string.format(g_Msgs.AreaDeleted, AreaID)); -- Reload all currently logged in players ReloadAllPlayersInWorld(a_Player:GetWorld():GetName()); return true; end function HandleGiveWand(a_Split, a_Player) local NumGiven = a_Player:GetInventory():AddItem(cConfig:GetWandItem()); if (NumGiven == 1) then a_Player:SendMessage(g_Msgs.WandGiven); else a_Player:SendMessage(g_Msgs.ErrNoSpaceForWand); end return true; end function HandleListAreas(a_Split, a_Player) -- Command syntax: /protection list [x z] local x, z; if (#a_Split == 2) then -- Get the last "wanded" coord local CmdState = GetCommandStateForPlayer(a_Player); if (CmdState == nil) then a_Player:SendMessage(g_Msgs.ErrCmdStateNilListAreas); return true; end x, z = CmdState:GetLastCoords(); if ((x == nil) or (z == nil)) then a_Player:SendMessage(g_Msgs.ErrListNotWanded); return true; end elseif (#a_Split == 4) then -- Parse the coords from the command params x = tonumber(a_Split[3]); z = tonumber(a_Split[4]); if ((x == nil) or (z == nil)) then a_Player:SendMessage(g_Msgs.ErrParseCoordsListAreas); return true; end else -- Wrong number of params, report back to the user a_Player:SendMessage(g_Msgs.ErrSyntaxErrorListAreas); return true; end a_Player:SendMessage(string.format(g_Msgs.ListAreasHeader, x, z)); -- List areas intersecting the coords local PlayerName = a_Player:GetName(); local WorldName = a_Player:GetWorld():GetName(); g_Storage:ForEachArea(x, z, WorldName, function(AreaID, MinX, MinZ, MaxX, MaxZ, CreatorName) local Coords = string.format("%s: {%d, %d} - {%d, %d} ", AreaID, MinX, MinZ, MaxX, MaxZ); local Allowance; if (g_Storage:IsAreaAllowed(AreaID, PlayerName, WorldName)) then Allowance = g_Msgs.AreaAllowed; else Allowance = g_Msgs.AreaNotAllowed; end a_Player:SendMessage(string.format(g_Msgs.ListAreasRow, Coords, Allowance, CreatorName)); end ); a_Player:SendMessage(g_Msgs.ListAreasFooter); return true; end --- Lists all allowed users for a particular area function HandleListUsers(a_Split, a_Player) -- Command syntax: /protection user list AreaID if (#a_Split ~= 4) then a_Player:SendMessage(g_Msgs.ErrExpectedAreaID); return true end -- Get the general info about the area local AreaID = a_Split[4]; local WorldName = a_Player:GetWorld():GetName(); local MinX, MinZ, MaxX, MaxZ, CreatorName = g_Storage:GetArea(AreaID, WorldName); if (MinX == nil) then a_Player:SendMessage(string.format(g_Msgs.ErrNoSuchArea, AreaID)); return true; end -- Send the header a_Player:SendMessage(string.format(g_Msgs.ListUsersHeader, AreaID, MinX, MinZ, MaxX, MaxZ, CreatorName)); -- List and count the allowed users local NumUsers = 0; g_Storage:ForEachUserInArea(AreaID, WorldName, function(UserName) a_Player:SendMessage(string.format(g_Msgs.ListUsersRow, UserName)); NumUsers = NumUsers + 1; end ); -- Send the footer a_Player:SendMessage(string.format(g_Msgs.ListUsersFooter, AreaID, NumUsers)); return true; end function HandleRemoveUser(a_Split, a_Player) -- Command syntax: /protection user remove AreaID UserName if (#a_Split ~= 5) then a_Player:SendMessage(g_Msgs.ErrExpectedAreaIDUserName); return true; end -- Parse the AreaID local AreaID = tonumber(a_Split[4]); if (AreaID == nil) then a_Player:SendMessage(g_Msgs.ErrParseAreaID); return true; end -- Remove the user from the DB local UserName = a_Split[5]; g_Storage:RemoveUser(AreaID, UserName, a_Player:GetWorld():GetName()); -- Send confirmation a_Player:SendMessage(string.format(g_Msgs.RemovedUser, UserName, AreaID)); -- Reload all currently logged in players ReloadAllPlayersInWorld(a_Player:GetWorld():GetName()); return true; end function HandleRemoveUserAll(a_Split, a_Player) -- Command syntax: /protection user strip UserName if (#a_Split ~= 4) then a_Player:SendMessage(g_Msgs.ErrExpectedUserName); return true; end -- Remove the user from the DB g_Storage:RemoveUserAll(a_Split[4], a_Player:GetWorld():GetName()); -- Send confirmation a_Player:SendMessage(string.format(g_Msgs.RemovedUserAll, UserName)); -- Reload all currently logged in players ReloadAllPlayersInWorld(a_Player:GetWorld():GetName()); return true; end
mit
mahdibagheri/mahdi
plugins/info.lua
4
2156
do local function action_by_reply(extra, success, result) local user_info = {} local uhash = 'user:'..result.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.from.id..':'..result.to.id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..result.from.id..']' local msgs = '› تعداد پیام ارسالی : '..user_info.msgs if result.from.username then user_name = '@'..result.from.username else user_name = '' end local msg = result local user_id = msg.from.id local chat_id = msg.to.id local user = 'user#id'..msg.from.id local chat = 'chat#id'..msg.to.id local data = load_data(_config.moderation.data) if data[tostring('admins')][tostring(user_id)] then who = '🏵 مدیر ربات' elseif data[tostring(msg.to.id)]['moderators'][tostring(user_id)] then who = '👮🏻 مدیر گروه' elseif data[tostring(msg.to.id)]['set_owner'] == tostring(user_id) then who = '🎗 مالک گروه' elseif tonumber(result.from.id) == tonumber(our_id) then who = '🎗 سازنده گروه' else who = '👤 ممبر' end for v,user in pairs(_config.sudo_users) do if user == user_id then who = '⭐️ مدیر کل ربات (سودو)' end end local text = '› نام کامل : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'› نام : '..(result.from.first_name or '')..'\n' ..'› نام خانوادگی : '..(result.from.last_name or '')..'\n' ..'› نام کاربری : '..user_name..'\n' ..'› کد کاربری : '..result.from.id..'\n' ..msgs..'\n' ..'› مقام : '..who..'\n\n' ..'› کد گروه : '..msg.to.id..'\nِ' send_large_msg(extra.receiver, text) end local function run(msg, matches) if matches[1] == 'info' and msg.reply_id then get_message(msg.reply_id, action_by_reply, {receiver=get_receiver(msg)}) end end return { patterns = { "^([Ii]nfo)$", "^[!/](info)$" }, run = run } end
gpl-2.0
nyov/luakit
lib/downloads_chrome.lua
4
12213
-- Grab what we need from the Lua environment local table = table local string = string local io = io local print = print local pairs = pairs local ipairs = ipairs local math = math local assert = assert local setmetatable = setmetatable local rawget = rawget local rawset = rawset local type = type local os = os local error = error -- Grab the luakit environment we need local downloads = require("downloads") local lousy = require("lousy") local chrome = require("chrome") local add_binds = add_binds local add_cmds = add_cmds local webview = webview local capi = { luakit = luakit } module("downloads.chrome") local html = [==[ <!doctype html> <html> <head> <meta charset="utf-8"> <title>Downloads</title> <style type="text/css"> body { background-color: white; color: black; margin: 10px; display: block; font-size: 84%; font-family: sans-serif; } div { display: block; } #downloads-summary { border-top: 1px solid #888; background-color: #ddd; padding: 3px; font-weight: bold; margin-top: 10px; margin-bottom: 10px; } .download { -webkit-margin-start: 90px; -webkit-padding-start: 10px; position: relative; display: block; margin-bottom: 10px; } .download .date { left: -90px; width: 90px; position: absolute; display: block; color: #888; } .download .title a { color: #3F6EC2; padding-right: 16px; } .download .status { display: inline; color: #999; white-space: nowrap; } .download .uri a { color: #56D; text-overflow: ellipsis; display: inline-block; white-space: nowrap; text-decoration: none; overflow: hidden; max-width: 500px; } .download .controls a { color: #777; margin-right: 16px; } </style> </head> <body> <div id="main"> <div id="downloads-summary">Downloads</div> <div id="downloads-list"> </div> </div> <script> </script> </body> </html> ]==] local main_js = [=[ var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; function basename(url) {     return url.substring(url.lastIndexOf('/') + 1); }; function readable_size(bytes, precision) { var bytes = bytes || 0, precision = precision || 2, kb = 1024, mb = kb*1024, gb = mb*1024, tb = gb*1024; if (bytes >= tb) { return (bytes / tb).toFixed(precision) + ' TB'; } else if (bytes >= gb) { return (bytes / gb).toFixed(precision) + ' GB'; } else if (bytes >= mb) { return (bytes / mb).toFixed(precision) + ' MB'; } else if (bytes >= kb) { return (bytes / kb).toFixed(precision) + ' KB'; } else { return bytes + ' B'; } } function make_download(d) { var e = "<div class='download' id='" + d.id + "' created='" + d.created + "'>"; var dt = new Date(d.created * 1000); e += ("<div class='date'>" + dt.getDate() + " " + months[dt.getMonth()] + " " + dt.getFullYear() + "</div>"); e += ("<div class='details'>" + "<div class='title'><a href='file://" + escape(d.destination) + "'>" + basename(d.destination) + "</a>" + "<div class='status'>waiting</div></div>" + "<div class='uri'><a href='" + encodeURI(d.uri) + "'>" + encodeURI(d.uri) + "</a></div></div>"); e += ("<div class='controls'>" + "<a href class='show'>Show in folder</a>" + "<a href class='restart'>Retry download</a>" + "<a href class='remove'>Remove from list</a>" + "<a href class='cancel'>Cancel</a>" + "</div>"); e += "</div>"; // <div class="download"> return e; } function getid(that) { return $(that).parents(".download").eq(0).attr("id"); }; function update_list() { var downloads = downloads_get_all(["status", "speed", "current_size", "total_size"]); // return if no downloads to display if (downloads.length === "undefined") { setTimeout(update, 1000); // update 1s from now return; } for (var i = 0; i < downloads.length; i++) { var d = downloads[i]; // find existing element var $elem = $("#"+d.id).eq(0); // create new download element if ($elem.length === 0) { // get some more information d = download_get(d.id, ["status", "destination", "created", "uri"]); var elem_html = make_download(d); // ordered insert var inserted = false; var $all = $("#downloads-list .download"); for (var j = 0; j < $all.length; j++) { if (d.created > $all.eq(j).attr("created")) { $all.eq(j).before(elem_html); inserted = true; break; } } // back of the bus if (!inserted) { $("#downloads-list").append(elem_html); } $elem = $("#"+d.id).eq(0); $elem.fadeIn(); } // update download controls when download status changes if (d.status !== $elem.attr("status")) { $elem.find(".controls a").hide(); switch (d.status) { case "created": case "started": $elem.find(".cancel,.show").fadeIn(); break; case "finished": $elem.find(".show,.remove").fadeIn(); break; case "error": case "cancelled": $elem.find(".remove,.restart").fadeIn(); break; } // save latest download status $elem.attr("status", d.status); } // update status text var $st = $elem.find(".status").eq(0); switch (d.status) { case "started": $st.text("downloading - " + readable_size(d.current_size) + "/" + readable_size(d.total_size) + " @ " + readable_size(d.speed) + "/s"); break; case "finished": $st.html("Finished - " + readable_size(d.total_size)); break; case "error": $st.html("Error"); break; case "cancelled": $st.html("Cancelled"); break; case "created": $st.html("Waiting"); break; default: $st.html(""); break; } } setTimeout(update_list, 1000); }; $(document).ready(function () { $("#downloads-list").on("click", ".controls .show", function (e) { download_show(getid(this)); }); $("#downloads-list").on("click", ".controls .restart", function (e) { download_restart(getid(this)); }); $("#downloads-list").on("click", ".controls .remove", function (e) { var id = getid(this); download_remove(id); elem = $("#"+id); elem.fadeOut("fast", function () { elem.remove(); }); }); $("#downloads-list").on("click", ".controls .cancel", function (e) { download_cancel(getid(this)); }); $("#downloads-list").on("click", ".details .title a", function (e) { download_open(getid(this)); return false; }); update_list(); }); ]=] -- default filter local default_filter = { destination = true, status = true, created = true, current_size = true, total_size = true, mime_type = true, uri = true, opening = true } local function collate_download_data(d, data, filter) local f = filter or default_filter local ret = { id = data.id } -- download object properties if rawget(f, "destination") then rawset(ret, "destination", d.destination) end if rawget(f, "status") then rawset(ret, "status", d.status) end if rawget(f, "uri") then rawset(ret, "uri", d.uri) end if rawget(f, "current_size") then rawset(ret, "current_size", d.current_size) end if rawget(f, "total_size") then rawset(ret, "total_size", d.total_size) end if rawget(f, "mime_type") then rawset(ret, "mime_type", d.mime_type) end -- data table properties if rawget(f, "created") then rawset(ret, "created", data.created) end if rawget(f, "opening") then rawset(ret, "opening", not not data.opening) end if rawget(f, "speed") then rawset(ret, "speed", data.speed) end return ret end local export_funcs = { download_get = function (id, filter) local d, data = downloads.get(id) if filter then assert(type(filter) == "table", "invalid filter table") for _, key in ipairs(filter) do rawset(filter, key, true) end end return collate_download_data(d, data, filter) end, downloads_get_all = function (filter) local ret = {} if filter then assert(type(filter) == "table", "invalid filter table") for _, key in ipairs(filter) do rawset(filter, key, true) end end for d, data in pairs(downloads.get_all()) do table.insert(ret, collate_download_data(d, data, filter)) end return ret end, download_show = function (id) local d, data = downloads.get(id) local dirname = string.gsub(d.destination, "(.*/)(.*)", "%1") if downloads.emit_signal("open-file", dirname, "inode/directory") ~= true then error("Couldn't show download directory (no inode/directory handler)") end end, download_cancel = downloads.cancel, download_restart = downloads.restart, download_open = downloads.open, download_remove = downloads.remove, downloads_clear = downloads.clear, } downloads.add_signal("status-tick", function (running) if running == 0 then for _, data in pairs(downloads.get_all()) do data.speed = nil end return end for d, data in pairs(downloads.get_all()) do if d.status == "started" then local last, curr = rawget(data, "last_size") or 0, d.current_size rawset(data, "speed", curr - last) rawset(data, "last_size", curr) end end end) chrome.add("downloads", function (view, meta) view:load_string(html, "luakit://downloads/") function on_first_visual(_, status) -- Wait for new page to be created if status ~= "first-visual" then return end -- Hack to run-once view:remove_signal("load-status", on_first_visual) -- Double check that we are where we should be if view.uri ~= "luakit://downloads/" then return end -- Export luakit JS<->Lua API functions for name, func in pairs(export_funcs) do view:register_function(name, func) end -- Load jQuery JavaScript library local jquery = lousy.load("lib/jquery.min.js") local _, err = view:eval_js(jquery, { no_return = true }) assert(not err, err) -- Load main luakit://download/ JavaScript local _, err = view:eval_js(main_js, { no_return = true }) assert(not err, err) end view:add_signal("load-status", on_first_visual) end) local page = "luakit://downloads/" local buf, cmd = lousy.bind.buf, lousy.bind.cmd add_binds("normal", { buf("^gd$", [[Open [luakit://downloads](luakit://downloads/) in current tab.]], function (w) w:navigate(page) end), buf("^gD$", [[Open [luakit://downloads](luakit://downloads/) in new tab.]], function (w) w:new_tab(page) end), }) add_cmds({ cmd("downloads", [[Open [luakit://downloads](luakit://downloads/) in new tab.]], function (w) w:new_tab(page) end), })
gpl-3.0
Naliwe/IntelliJ_WowAddOnSupport
resources/Wow_sdk/AceGUI-3.0/widgets/AceGUIWidget-EditBox.lua
1
8120
--[[----------------------------------------------------------------------------- EditBox Widget -------------------------------------------------------------------------------]] local Type, Version = "EditBox", 27 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local tostring, pairs = tostring, pairs -- WoW APIs local PlaySound = PlaySound local GetCursorInfo, ClearCursor, GetSpellInfo = GetCursorInfo, ClearCursor, GetSpellInfo local CreateFrame, UIParent = CreateFrame, UIParent local _G = _G -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: AceGUIEditBoxInsertLink, ChatFontNormal, OKAY --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] if not AceGUIEditBoxInsertLink then -- upgradeable hook hooksecurefunc("ChatEdit_InsertLink", function(...) return _G.AceGUIEditBoxInsertLink(...) end) end function _G.AceGUIEditBoxInsertLink(text) for i = 1, AceGUI:GetWidgetCount(Type) do local editbox = _G["AceGUI-3.0EditBox" .. i] if editbox and editbox:IsVisible() and editbox:HasFocus() then editbox:Insert(text) return true end end end local function ShowButton(self) if not self.disablebutton then self.button:Show() self.editbox:SetTextInsets(0, 20, 3, 3) end end local function HideButton(self) self.button:Hide() self.editbox:SetTextInsets(0, 0, 3, 3) end --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Frame_OnShowFocus(frame) frame.obj.editbox:SetFocus() frame:SetScript("OnShow", nil) end local function EditBox_OnEscapePressed(frame) AceGUI:ClearFocus() end local function EditBox_OnEnterPressed(frame) local self = frame.obj local value = frame:GetText() local cancel = self:Fire("OnEnterPressed", value) if not cancel then PlaySound(PlaySoundKitID and "igMainMenuOptionCheckBoxOn" or 856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON HideButton(self) end end local function EditBox_OnReceiveDrag(frame) local self = frame.obj local type, id, info = GetCursorInfo() if type == "item" then self:SetText(info) self:Fire("OnEnterPressed", info) ClearCursor() elseif type == "spell" then local name = GetSpellInfo(id, info) self:SetText(name) self:Fire("OnEnterPressed", name) ClearCursor() elseif type == "macro" then local name = GetMacroInfo(id) self:SetText(name) self:Fire("OnEnterPressed", name) ClearCursor() end HideButton(self) AceGUI:ClearFocus() end local function EditBox_OnTextChanged(frame) local self = frame.obj local value = frame:GetText() if tostring(value) ~= tostring(self.lasttext) then self:Fire("OnTextChanged", value) self.lasttext = value ShowButton(self) end end local function EditBox_OnFocusGained(frame) AceGUI:SetFocus(frame.obj) end local function Button_OnClick(frame) local editbox = frame.obj.editbox editbox:ClearFocus() EditBox_OnEnterPressed(editbox) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) -- height is controlled by SetLabel self:SetWidth(200) self:SetDisabled(false) self:SetLabel() self:SetText() self:DisableButton(false) self:SetMaxLetters(0) end, ["OnRelease"] = function(self) self:ClearFocus() end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.editbox:EnableMouse(false) self.editbox:ClearFocus() self.editbox:SetTextColor(0.5, 0.5, 0.5) self.label:SetTextColor(0.5, 0.5, 0.5) else self.editbox:EnableMouse(true) self.editbox:SetTextColor(1, 1, 1) self.label:SetTextColor(1, .82, 0) end end, ["SetText"] = function(self, text) self.lasttext = text or "" self.editbox:SetText(text or "") self.editbox:SetCursorPosition(0) HideButton(self) end, ["GetText"] = function(self, text) return self.editbox:GetText() end, ["SetLabel"] = function(self, text) if text and text ~= "" then self.label:SetText(text) self.label:Show() self.editbox:SetPoint("TOPLEFT", self.frame, "TOPLEFT", 7, -18) self:SetHeight(44) self.alignoffset = 30 else self.label:SetText("") self.label:Hide() self.editbox:SetPoint("TOPLEFT", self.frame, "TOPLEFT", 7, 0) self:SetHeight(26) self.alignoffset = 12 end end, ["DisableButton"] = function(self, disabled) self.disablebutton = disabled if disabled then HideButton(self) end end, ["SetMaxLetters"] = function(self, num) self.editbox:SetMaxLetters(num or 0) end, ["ClearFocus"] = function(self) self.editbox:ClearFocus() self.frame:SetScript("OnShow", nil) end, ["SetFocus"] = function(self) self.editbox:SetFocus() if not self.frame:IsShown() then self.frame:SetScript("OnShow", Frame_OnShowFocus) end end, ["HighlightText"] = function(self, from, to) self.editbox:HighlightText(from, to) end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local num = AceGUI:GetNextWidgetNum(Type) local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local editbox = CreateFrame("EditBox", "AceGUI-3.0EditBox" .. num, frame, "InputBoxTemplate") editbox:SetAutoFocus(false) editbox:SetFontObject(ChatFontNormal) editbox:SetScript("OnEnter", Control_OnEnter) editbox:SetScript("OnLeave", Control_OnLeave) editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed) editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed) editbox:SetScript("OnTextChanged", EditBox_OnTextChanged) editbox:SetScript("OnReceiveDrag", EditBox_OnReceiveDrag) editbox:SetScript("OnMouseDown", EditBox_OnReceiveDrag) editbox:SetScript("OnEditFocusGained", EditBox_OnFocusGained) editbox:SetTextInsets(0, 0, 3, 3) editbox:SetMaxLetters(256) editbox:SetPoint("BOTTOMLEFT", 6, 0) editbox:SetPoint("BOTTOMRIGHT") editbox:SetHeight(19) local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") label:SetPoint("TOPLEFT", 0, -2) label:SetPoint("TOPRIGHT", 0, -2) label:SetJustifyH("LEFT") label:SetHeight(18) local button = CreateFrame("Button", nil, editbox, "UIPanelButtonTemplate") button:SetWidth(40) button:SetHeight(20) button:SetPoint("RIGHT", -2, 0) button:SetText(OKAY) button:SetScript("OnClick", Button_OnClick) button:Hide() local widget = { alignoffset = 30, editbox = editbox, label = label, button = button, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end editbox.obj, button.obj = widget, widget return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
ShieldTeams/oldsdp
plugins/azan.lua
1
3556
do function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') return result end local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end function get_staticmap(area) local api = base_api .. "/staticmap?" local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) local receiver = get_receiver(msg) local city = matches[1] if matches[1] == 'praytime' or matches[1] == 'azan' then city = 'Tehran' end local lat,lng,url = get_staticmap(city) local dumptime = run_bash('date +%s') local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7') local jdat = json:decode(code) local data = jdat.data.timings local text = '🛣 شهر : '..city text = text..'\n➖➖➖➖➖➖➖➖➖➖➖\n🙉 اذان صبح : '..data.Fajr text = text..'\n➖➖➖➖➖➖➖➖➖➖➖\n☀️ طلوع آفتاب : '..data.Sunrise text = text..'\n➖➖➖➖➖➖➖➖➖➖➖\n🙉 اذان ظهر : '..data.Dhuhr text = text..'\n➖➖➖➖➖➖➖➖➖➖➖\n🌅 غروب آفتاب : '..data.Sunset text = text..'\n➖➖➖➖➖➖➖➖➖➖➖\n🙉 اذان مغرب : '..data.Maghrib text = text..'\n➖➖➖➖➖➖➖➖➖➖➖\n🙉 عشاء : '..data.Isha text = text..'\n\n🌔🌜🌕🌞⭐️🌞⭐️🌞🌕🌛🌖\n\n🆔 Channel ™ : @Shield_Tm\n=======================\n🇸 🇭 🇮 🇪 🇱 🇩™' if string.match(text, '0') then text = string.gsub(text, '0', '۰') end if string.match(text, '1') then text = string.gsub(text, '1', '۱') end if string.match(text, '2') then text = string.gsub(text, '2', '۲') end if string.match(text, '3') then text = string.gsub(text, '3', '۳') end if string.match(text, '4') then text = string.gsub(text, '4', '۴') end if string.match(text, '5') then text = string.gsub(text, '5', '۵') end if string.match(text, '6') then text = string.gsub(text, '6', '۶') end if string.match(text, '7') then text = string.gsub(text, '7', '۷') end if string.match(text, '8') then text = string.gsub(text, '8', '۸') end if string.match(text, '9') then text = string.gsub(text, '9', '۹') end return text end return { patterns = { "^[Pp]raytime (.*)$", "^[Pp]raytime$", "^[Aa]zan (.*)$", "^[Aa]zan$" }, run = run } end
agpl-3.0
bizkut/BudakJahat
Rotations/Old/old_HolyOdan.lua
1
35114
local rotationName = "Odan(Svs+)" --------------- --- Toggles --- --------------- local function createToggles() -- Rotation Button RotationModes = { [1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "Swaps between Single and Multiple based on number of targets in range", highlight = 1, icon = br.player.spell.holyWordSanctify }, [2] = { mode = "Mult", value = 2 , overlay = "Multiple Target Rotation", tip = "Multiple target rotation used", highlight = 0, icon = br.player.spell.prayerOfHealing }, [3] = { mode = "Sing", value = 3 , overlay = "Single Target Rotation", tip = "Single target rotation used", highlight = 0, icon = br.player.spell.heal }, [4] = { mode = "Off", value = 4 , overlay = "DPS Rotation Disabled", tip = "Disable DPS Rotation", highlight = 0, icon = br.player.spell.holyFire} }; CreateButton("Rotation",1,0) -- Cooldown Button CooldownModes = { [1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection", highlight = 1, icon = br.player.spell.guardianSpirit }, [2] = { mode = "On", value = 1 , overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target", highlight = 0, icon = br.player.spell.guardianSpirit }, [3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used", highlight = 0, icon = br.player.spell.guardianSpirit } }; CreateButton("Cooldown",2,0) -- Defensive Button DefensiveModes = { [1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns", highlight = 1, icon = br.player.spell.desperatePrayer }, [2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "No Defensives will be used", highlight = 0, icon = br.player.spell.desperatePrayer } }; CreateButton("Defensive",3,0) -- Decurse Button DecurseModes = { [1] = { mode = "On", value = 1 , overlay = "Decurse Enabled", tip = "Decurse Enabled", highlight = 1, icon = br.player.spell.purify }, [2] = { mode = "Off", value = 2 , overlay = "Decurse Disabled", tip = "Decurse Disabled", highlight = 0, icon = br.player.spell.purify } }; CreateButton("Decurse",4,0) -- DPS Button DPSModes = { [1] = { mode = "On", value = 1 , overlay = "DPS Enabled", tip = "DPS Enabled", highlight = 1, icon = br.player.spell.smite }, [2] = { mode = "Off", value = 2 , overlay = "DPS Disabled", tip = "DPS Disabled", highlight = 0, icon = br.player.spell.renew } }; CreateButton("DPS",5,0) end -------------- --- COLORS --- -------------- local colorBlue = "|cff00CCFF" local colorGreen = "|cff00FF00" local colorRed = "|cffFF0000" local colorWhite = "|cffFFFFFF" local colorGold = "|cffFFDD11" --------------- --- OPTIONS --- --------------- local function createOptions() local optionTable local function rotationOptions() -- General Options section = br.ui:createSection(br.ui.window.profile, "General") br.ui:createCheckbox(section,"OOC Healing","|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFout of combat healing|cffFFBB00.") -- Dummy DPS Test br.ui:createSpinner(section, "DPS Testing", 5, 5, 60, 5, "|cffFFFFFFSet to desired time for test in minuts. Min: 5 / Max: 60 / Interval: 5") -- Angelic Feather br.ui:createCheckbox(section,"Angelic Feather","|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFAngelic Feather usage|cffFFBB00.") -- Body and Mind br.ui:createCheckbox(section,"Body and Mind","|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFBody and Mind usage|cffFFBB00.") -- Dispel Magic br.ui:createCheckbox(section,"Dispel Magic","|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFDispel Magic usage|cffFFBB00.") -- Mass Dispel br.ui:createDropdown(section, "Mass Dispel", br.dropOptions.Toggle, 6, colorGreen.."Enables"..colorWhite.."/"..colorRed.."Disables "..colorWhite.." Mass Dispel usage.") -- Racial br.ui:createCheckbox(section, "Racial") -- Holy Word: Chastise br.ui:createCheckbox(section, "Holy Word: Chastise") br.ui:checkSectionState(section) -- Cooldown Options section = br.ui:createSection(br.ui.window.profile, "Cooldowns") -- Flask / Crystal br.ui:createCheckbox(section,"Flask / Crystal") -- Racial br.ui:createCheckbox(section,"Racial") -- Trinkets br.ui:createCheckbox(section,"Trinkets") --The Deceiver's Grand Design br.ui:createCheckbox(section, "The Deceiver's Grand Design") --The Deceiver's Grand Design -- Pre-Pot Timer br.ui:createSpinner(section, "Pre-Pot Timer", 5, 1, 15, 1, "|cffFFFFFFSet to desired time to start Pre-Pull (DBM Required). Min: 1 / Max: 15 / Interval: 1") -- Mana Potion br.ui:createSpinner(section, "Mana Potion", 50, 0, 100, 1, "Mana Percent to Cast At") -- Divine Hymn br.ui:createSpinner(section, "Divine Hymn", 50, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Divine Hymn Targets", 3, 0, 40, 1, "Minimum Divine Hymn Targets") -- Symbol of Hope br.ui:createSpinner(section, "Symbol of Hope", 50, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Symbol of Hope Targets", 3, 0, 40, 1, "Minimum Symbol of Hope Targets") br.ui:checkSectionState(section) -- Defensive Options section = br.ui:createSection(br.ui.window.profile, "Defensive") -- Healthstone br.ui:createSpinner(section, "Healthstone", 30, 0, 100, 5, "|cffFFFFFFHealth Percent to Cast At") -- Heirloom Neck br.ui:createSpinner(section, "Heirloom Neck", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at"); -- Gift of The Naaru if br.player.race == "Draenei" then br.ui:createSpinner(section, "Gift of the Naaru", 50, 0, 100, 5, "|cffFFFFFFHealth Percentage to use at") end -- Desperate Prayer br.ui:createSpinner(section, "Desperate Prayer", 80, 0, 100, 5, "|cffFFBB00Health Percentage to use at"); --Fade br.ui:createSpinner(section, "Fade", 95, 0, 100, 1, "|cffFFFFFFHealth Percent to Cast At. Default: 95") br.ui:checkSectionState(section) -- Healing Options section = br.ui:createSection(br.ui.window.profile, "Healing Options") -- Leap of Faith br.ui:createSpinner(section, "Leap of Faith", 20, 0, 100, 5, "Health Percent to Cast At") -- Guardian Spirit br.ui:createSpinner(section, "Guardian Spirit", 30, 0, 100, 5, "Health Percent to Cast At") -- Guardian Spirit Tank Only br.ui:createCheckbox(section,"Guardian Spirit Tank Only") -- Renew br.ui:createSpinner(section, "Renew", 85, 0, 100, 1, "Health Percent of group to Cast At") br.ui:createSpinner(section, "Renew on Tanks", 90, 0, 100, 1, "Tanks Health Percent of tanks to Cast At") br.ui:createSpinner(section, "Renew while moving", 80, 0, 100, 1, "Moving Health Percent to Cast At") -- Prayer of Mending br.ui:createSpinner(section, "Prayer of Mending", 100, 0, 100, 1, "Health Percent to Cast At") -- Light of T'uure br.ui:createSpinner(section, "Light of T'uure", 85, 0, 100, 5, "Health Percent to Cast At") -- Heal br.ui:createSpinner(section, "Heal", 70, 0, 100, 5, "Health Percent to Cast At") -- Flash Heal br.ui:createSpinner(section, "Flash Heal", 60, 0, 100, 5, "Health Percent to Cast At") -- Flash Heal Surge of Light br.ui:createSpinner(section, "Flash Heal Surge of Light", 80, 0, 100, 5, "Health Percent to Cast At") -- Holy Word: Serenity br.ui:createSpinner(section, "Holy Word: Serenity", 50, 0, 100, 5, "Health Percent to Cast At") -- Holy Word: Sanctify br.ui:createSpinner(section, "Holy Word: Sanctify", 80, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Holy Word: Sanctify Targets", 3, 0, 40, 1, "Minimum Holy Word: Sanctify Targets") -- Holy Word: Sanctify Hot Key br.ui:createDropdown(section, "Holy Word: Sanctify HK", br.dropOptions.Toggle, 10, colorGreen.."Enables"..colorWhite.."/"..colorRed.."Disables "..colorWhite.." Holy Word: Sanctify Usage.") -- Prayer of Healing br.ui:createSpinner(section, "Prayer of Healing", 70, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Prayer of Healing Targets", 3, 0, 40, 1, "Minimum Prayer of Healing Targets") -- Binding Heal(not implemented yet) br.ui:createSpinner(section, "Binding Heal", 70, 0, 100, 5, "Health Percent to Cast At") -- Divine Star br.ui:createSpinner(section, "Divine Star", 80, 0, 100, 5, colorGreen.."Enables"..colorWhite.."/"..colorRed.."Disables "..colorWhite.."Divine Star usage.", colorWhite.."Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Min Divine Star Targets", 3, 1, 40, 1, colorBlue.."Minimum Divine Star Targets "..colorGold.."(This includes you)") br.ui:createCheckbox(section,"Show Divine Star Area",colorGreen.."Enables"..colorWhite.."/"..colorRed.."Disables "..colorWhite.."area of effect drawing.") -- Halo br.ui:createSpinner(section, "Halo", 70, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Halo Targets", 3, 0, 40, 1, "Minimum Halo Targets") br.ui:checkSectionState(section) end optionTable = {{ [1] = "Rotation Options", [2] = rotationOptions, }} return optionTable end ---------------- --- ROTATION --- ---------------- local function runRotation() if br.timer:useTimer("debugHoly", 0.1) then --Print("Running: "..rotationName) --------------- --- Toggles --- -- List toggles here in order to update when pressed --------------- UpdateToggle("Rotation",0.25) UpdateToggle("Cooldown",0.25) UpdateToggle("Defensive",0.25) UpdateToggle("Decurse",0.25) UpdateToggle("DPS",0.25) br.player.mode.decurse = br.data.settings[br.selectedSpec].toggles["Decurse"] br.player.mode.dps = br.data.settings[br.selectedSpec].toggles["DPS"] -------------- --- Locals --- -------------- local artifact = br.player.artifact local buff = br.player.buff local cast = br.player.cast local combatTime = getCombatTime() local cd = br.player.cd local charges = br.player.charges local debuff = br.player.debuff local enemies = br.player.enemies local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), GetUnitSpeed("player")>0 local gcd = br.player.gcd local healPot = getHealthPot() local inCombat = br.player.inCombat local inInstance = br.player.instance=="party" local inRaid = br.player.instance=="raid" local lastSpell = lastSpellCast local level = br.player.level local lowestHP = br.friend[1].unit local mana = br.player.power.mana.percent() local mode = br.player.mode local perk = br.player.perk local php = br.player.health local power, powmax, powgen = br.player.power.mana.amount(), br.player.power.mana.max(), br.player.power.mana.regen() local pullTimer = br.DBM:getPulltimer() local race = br.player.race local racial = br.player.getRacial() local spell = br.player.spell local talent = br.player.talent local ttm = br.player.power.mana.ttm() local units = br.player.units local lowest = {} --Lowest Unit lowest.hp = br.friend[1].hp lowest.role = br.friend[1].role lowest.unit = br.friend[1].unit lowest.range = br.friend[1].range lowest.guid = br.friend[1].guid local friends = friends or {} local tank = {} --Tank local averageHealth = 0 units.get(5) units.get(8,true) units.get(40) enemies.get(5) enemies.get(8) enemies.get(8,"target") enemies.get(40) friends.yards40 = getAllies("player",40) -------------------- --- Action Lists --- -------------------- -- Action List - Extras local function actionList_Extras() -- Dummy Test if isChecked("DPS Testing") then if GetObjectExists("target") then if getCombatTime() >= (tonumber(getOptionValue("DPS Testing"))*60) and isDummy() then StopAttack() ClearTarget() Print(tonumber(getOptionValue("DPS Testing")) .." Minute Dummy Test Concluded - Profile Stopped") profileStop = true end end end -- End Dummy Test -- Moving if isMoving("player") then if isChecked("Angelic Feather") and talent.angelicFeather and not buff.angelicFeather.exists("player") then if cast.angelicFeather("player") then RunMacroText("/stopspelltarget") end end -- Body and Mind if isChecked("Body and Mind") and talent.bodyAndMind then if cast.bodyAndMind("player") then return end end end -- Pre-Pot Timer if isChecked("Pre-Pot Timer") and pullTimer <= getOptionValue("Pre-Pot Timer") then if pullTimer <= getOptionValue("Pre-Pot Timer") then if canUseItem(142117) and not buff.prolongedPower.exists() then useItem(142117); return true end end end -- Mass Dispel if isChecked("Mass Dispel") and (SpecificToggle("Mass Dispel") and not GetCurrentKeyBoardFocus()) then CastSpellByName(GetSpellInfo(spell.massDispel),"cursor") return true end end -- End Action List - Extras -- Action List - Pre-Combat function actionList_PreCombat() -- Renew if isChecked("Renew") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Renew") and not buff.renew.exists(br.friend[i].unit) then if cast.renew(br.friend[i].unit) then return end end end end -- Renew on tank if isChecked("Renew on Tanks") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Renew on Tanks") and not buff.renew.exists(br.friend[i].unit) and UnitGroupRolesAssigned(br.friend[i].unit) == "TANK" then if cast.renew(br.friend[i].unit) then return end end end end -- Heal if isChecked("Heal") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Heal") then if cast.heal(br.friend[i].unit) then return end end end end -- Flash Heal if isChecked("Flash Heal") and getDebuffRemain("player",240447) == 0 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Flash Heal") then if cast.flashHeal(br.friend[i].unit) then return end end end end -- Flash Heal Surge of Light if isChecked("Flash Heal Surge of Light") and talent.surgeOfLight and buff.surgeOfLight.exists() then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Flash Heal Surge of Light") then if cast.flashHeal(br.friend[i].unit) then return end end end end -- Renew While Moving if isChecked("Renew while moving") and isMoving("player") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Renew while moving") and not buff.renew.exists(br.friend[i].unit) then if cast.renew(br.friend[i].unit) then return end end end end end -- End Action List - Pre-Combat local function actionList_Defensive() if useDefensive() then -- Healthstone if isChecked("Healthstone") and php <= getOptionValue("Healthstone") and inCombat and hasItem(5512) then if canUseItem(5512) then useItem(5512) end end -- Heirloom Neck if isChecked("Heirloom Neck") and php <= getOptionValue("Heirloom Neck") then if hasEquiped(122668) then if GetItemCooldown(122668)==0 then useItem(122668) end end end --Fade if isChecked("Fade") then if php <= getValue("Fade") then if cast.fade() then return end end end -- Mana Potion if isChecked("Mana Potion") and mana <= getValue("Mana Potion")then if hasItem(127835) then useItem(127835) return true end end -- Gift of the Naaru if isChecked("Gift of the Naaru") and php <= getOptionValue("Gift of the Naaru") and php > 0 and br.player.race == "Draenei" then if castSpell("player",racial,false,false,false) then return end end -- Desperate Prayer if isChecked("Desperate Prayer") and php <= getOptionValue("Desperate Prayer") and inCombat then if cast.desperatePrayer() then return end end end -- End Defensive Toggle end -- End Action List - Defensive function actionList_Cooldowns() -- The Deceiver's Grand Design if isChecked("The Deceiver's Grand Design") then for i = 1, #br.friend do if hasEquiped(147007) and canUseItem(147007) and getBuffRemain(br.friend[i].unit,242622) == 0 and UnitGroupRolesAssigned(br.friend[i].unit) == "TANK" and UnitInRange(br.friend[i].unit) and not UnitIsDeadOrGhost(br.friend[i].unit) then UseItemByName(147007,br.friend[i].unit) end end end if useCDs() then -- Divine Hymn if isChecked("Divine Hymn") and not moving then if getLowAllies(getValue("Divine Hymn")) >= getValue("Divine Hymn Targets") then if cast.prayerOfMending(lowest.unit) then return end if isChecked("Holy Word: Sanctify") and not buff.divinity.exists() then if castWiseAoEHeal(br.friend,spell.holyWordSanctify,10,getValue("Holy Word: Sanctify"),getValue("Holy Word: Sanctify Targets"),6,false,false) then return end end if isChecked("Holy Word: Serenity") and not buff.divinity.exists() then if cast.holyWordSerenity(lowest.unit) then return end end if cast.divineHymn() then return end if isChecked("Holy Word: Sanctify") then if castWiseAoEHeal(br.friend,spell.holyWordSanctify,10,getValue("Holy Word: Sanctify"),getValue("Holy Word: Sanctify Targets"),6,false,false) then return end end if isChecked("Holy Word: Serenity") then if cast.holyWordSerenity(lowest.unit) then return end end end end -- Symbol of Hope if isChecked("Symbol of Hope") then if getLowAllies(getValue("Symbol of Hope")) >= getValue("Symbol of Hope Targets") then if cast.symbolOfHope() then return end end end -- Trinkets if isChecked("Trinkets") then if canUseItem(11) then useItem(11) end if canUseItem(12) then useItem(12) end if canUseItem(13) then useItem(13) end if canUseItem(14) then useItem(14) end end -- Racial: Orc Blood Fury | Troll Berserking | Blood Elf Arcane Torrent if isChecked("Racial") and (br.player.race == "Orc" or br.player.race == "Troll" or br.player.race == "BloodElf") then if castSpell("player",racial,false,false,false) then return end end end -- End useCooldowns check end -- End Action List - Cooldowns -- Dispel function actionList_Dispel() -- Purify if br.player.mode.decurse == 1 then for i = 1, #friends.yards40 do if canDispel(br.friend[i].unit,spell.purify) then if cast.purify(br.friend[i].unit) then return end end end end -- Mass Dispel if isChecked("Mass Dispel") and (SpecificToggle("Mass Dispel") and not GetCurrentKeyBoardFocus()) then CastSpellByName(GetSpellInfo(spell.massDispel),"cursor") return true end end -- End Action List - Dispel -- Emergency (Healing below 40%) function actionList_Emergency() -- Holy Word: Sanctify if isChecked("Holy Word: Sanctify") then if castWiseAoEHeal(br.friend,spell.holyWordSanctify,40,40,2,6,false,false) then return end end -- Holy Word: Serenity if isChecked("Holy Word: Serenity") then for i = 1, #br.friend do if br.friend[i].hp <= 40 then if cast.holyWordSerenity(br.friend[i].unit) then return end end end end -- Prayer of Healing if isChecked("Prayer of Healing") and getDebuffRemain("player",240447) == 0 then if castWiseAoEHeal(br.friend,spell.prayerOfHealing,40,40,3,5,false,true) then return end end -- Flash Heal if isChecked("Flash Heal") and getDebuffRemain("player",240447) == 0 then for i = 1, #br.friend do if br.friend[i].hp <= 40 then if cast.flashHeal(br.friend[i].unit) then return end end end end end -- EndAction List Emergency (Healing below 40%) -- Divinity function actionList_Divinity() -- Holy Word: Sanctify if isChecked("Holy Word: Sanctify") and not buff.divinity.exists() then if castWiseAoEHeal(br.friend,spell.holyWordSanctify,40,getValue("Holy Word: Sanctify"),getValue("Holy Word: Sanctify Targets"),6,false,false) then RunMacroText("/stopspelltarget") end end -- Holy Word: Serenity if isChecked("Holy Word: Serenity") and not buff.divinity.exists() then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Holy Word: Serenity") then if cast.holyWordSerenity(br.friend[i].unit) then return end end end end end -- End Action List - Divinity -- AOE Healing function actionList_AOEHealing() -- Prayer of Mending if isChecked("Prayer of Mending") and getDebuffRemain("player",240447) == 0 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Prayer of Mending") and not buff.prayerOfMending.exists(br.friend[i].unit) then if cast.prayerOfMending(br.friend[i].unit) then return end end end end -- Holy Word: Sanctify Hot Key if isChecked("Holy Word: Sanctify HK") and (SpecificToggle("Holy Word: Sanctify HK") and not GetCurrentKeyBoardFocus()) then CastSpellByName(GetSpellInfo(spell.holyWordSanctify),"cursor") return true end -- Binding Heal if isChecked("Binding Heal") and talent.bindingHeal and getDebuffRemain("player",240447) == 0 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Binding Heal") then if cast.bindingHeal(br.friend[i].unit) then RunMacroText("/stopspelltarget") end end end end -- Prayer of Healing (with Power Of The Naaru Buff) if isChecked("Prayer of Healing") and talent.piety and buff.powerOfTheNaaru.exists() and cd.holyWordSanctify.remain() >= 1 and getDebuffRemain("player",240447) == 0 then if castWiseAoEHeal(br.friend,spell.prayerOfHealing,40,getValue("Prayer of Healing"),getValue("Prayer of Healing Targets"),5,false,true) then return end end -- Prayer of Healing if isChecked("Prayer of Healing") and not talent.piety and getDebuffRemain("player",240447) == 0 then if castWiseAoEHeal(br.friend,spell.prayerOfHealing,40,getValue("Prayer of Healing"),getValue("Prayer of Healing Targets"),5,false,true) then return end end -- Divine Star if isChecked("Divine Star") and talent.divineStar then if castWiseAoEHeal(br.friend,spell.divineStar,10,getValue("Divine Star"),getValue("Min Divine Star Targets"),10,false,false) then return end end --Halo if isChecked("Halo") and talent.halo then if getLowAllies(getValue("Halo")) >= getValue("Halo Targets") then if cast.halo() then return end end end end -- End Action List - AOE Healing -- Single Target function actionList_SingleTarget() -- Guardian Spirit if isChecked("Guardian Spirit") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Guardian Spirit") then if br.friend[i].role == "TANK" or not isChecked("Guardian Spirit Tank Only") then if cast.guardianSpirit(br.friend[i].unit) then return end end end end end -- Leap of Faith if isChecked("Leap of Faith") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Leap of Faith") and not GetUnitIsUnit(br.friend[i].unit,"player") and br.friend[i].role ~= "TANK" then if cast.leapOfFaith(br.friend[i].unit) then return end end end end -- Light of T'uure if isChecked("Light of T'uure") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Light of T'uure") then if cast.lightOfTuure(br.friend[i].unit) then return end end end end -- Flash Heal if isChecked("Flash Heal") and getDebuffRemain("player",240447) == 0 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Flash Heal") then if cast.flashHeal(br.friend[i].unit) then return end end end end -- Flash Heal Surge of Light if isChecked("Flash Heal Surge of Light") and talent.surgeOfLight and buff.surgeOfLight.remain() > 1.5 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Flash Heal Surge of Light") then if cast.flashHeal(br.friend[i].unit) then return end end end end -- Heal if isChecked("Heal") and getDebuffRemain("player",240447) == 0 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Heal") then if cast.heal(br.friend[i].unit) then return end end end end -- Dispel Magic if isChecked("Dispel Magic") and canDispel("target",spell.dispelMagic) and not isBoss() and GetObjectExists("target") then if cast.dispelMagic() then return end end -- Renew if isChecked("Renew") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Renew") and not buff.renew.exists(br.friend[i].unit) then if cast.renew(br.friend[i].unit) then return end end end end -- Renew on tank if isChecked("Renew on Tanks") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Renew on Tanks") and not buff.renew.exists(br.friend[i].unit) and UnitGroupRolesAssigned(br.friend[i].unit) == "TANK" then if cast.renew(br.friend[i].unit) then return end end end end -- Moving if isMoving("player") then if isChecked("Angelic Feather") and talent.angelicFeather and not buff.angelicFeather.exists("player") then if cast.angelicFeather("player") then RunMacroText("/stopspelltarget") end end -- Body and Mind if isChecked("Body and Mind") and talent.bodyAndMind then if cast.bodyAndMind("player") then return end end end -- Renew While Moving if isChecked("Renew while moving") and isMoving("player") then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Renew while moving") and not buff.renew.exists(br.friend[i].unit) then if cast.renew(br.friend[i].unit) then return end end end end end -- End Action List - Single Target -- DPS function actionList_DPS() -- Holy Word: Chastise if isChecked("Holy Word: Chastise") then if cast.holyWordChastise() then return end end -- Holy Fire if cast.holyFire() then return end -- Divine Star if cast.divineStar(getBiggestUnitCluster(24,7)) then return end -- Smite if #enemies.yards8 < 3 and getDebuffRemain("player",240447) == 0 then if cast.smite() then return end end -- Holy Nova if #enemies.yards8 >= 3 and getDistance(units.dyn8AoE) < 12 and level > 25 then if cast.holyNova() then return end end end ----------------- --- Rotations --- ----------------- -- Pause if pause() or mode.rotation == 4 then return true else --------------------------------- --- Out Of Combat - Rotations --- --------------------------------- if not inCombat and not IsMounted() then actionList_Extras() if isChecked("OOC Healing") then actionList_PreCombat() end end -- End Out of Combat Rotation ----------------------------- --- In Combat - Rotations --- ----------------------------- if inCombat and not IsMounted() then if buff.spiritOfRedemption.exists() then actionList_Emergency() end if not buff.spiritOfRedemption.exists() then actionList_Defensive() actionList_Cooldowns() actionList_Dispel() actionList_Emergency() if talent.divinity then actionList_Divinity() end actionList_AOEHealing() actionList_SingleTarget() if br.player.mode.dps == 1 then actionList_DPS() end end end -- End In Combat Rotation end -- Pause end -- End Timer end -- End runRotation --local id = 257 local id = 0 if br.rotations[id] == nil then br.rotations[id] = {} end tinsert(br.rotations[id],{ name = rotationName, toggles = createToggles, options = createOptions, run = runRotation, })
gpl-3.0
cshore/luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/luci.lua
76
1122
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. require "luci.config" local fs = require "nixio.fs" m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>.")) -- force reload of global luci config namespace to reflect the changes function m.commit_handler(self) package.loaded["luci.config"] = nil require "luci.config" end c = m:section(NamedSection, "main", "core", translate("General")) l = c:option(ListValue, "lang", translate("Language")) l:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then l:value(k, v) end end t = c:option(ListValue, "mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then t:value(v, k) end end return m
apache-2.0
bizkut/BudakJahat
Rotations/Priest/Discipline/Disclo.lua
1
34269
local rotationName = "PangDisc" -- Version: 1350-02-09-2020 local function createToggles() -- Cooldown Button CooldownModes = { [1] = {mode = "Auto", value = 1, overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.divineStar}, [2] = {mode = "On", value = 2, overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.divineStar}, [3] = {mode = "Off", value = 3, overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.divineStar} } CreateButton("Cooldown", 1, 0) -- Defensive Button DefensiveModes = { [1] = {mode = "On", value = 1, overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.powerWordBarrier}, [2] = {mode = "Off", value = 2, overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.powerWordBarrier} } CreateButton("Defensive", 2, 0) -- Decurse Button DecurseModes = { [1] = {mode = "On", value = 1, overlay = "Decurse Enabled", tip = "Decurse Enabled", highlight = 1, icon = br.player.spell.purify}, [2] = {mode = "Off", value = 2, overlay = "Decurse Disabled", tip = "Decurse Disabled", highlight = 0, icon = br.player.spell.purify} } CreateButton("Decurse", 3, 0) -- Interrupt Button InterruptModes = { [1] = {mode = "On", value = 1, overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.psychicScream}, [2] = {mode = "Off", value = 2, overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.psychicScream} } CreateButton("Interrupt", 4, 0) BurstModes = { [1] = {mode = "Auto", value = 1, overlay = "Auto Ramp Enabled", tip = "Will Automatically Ramp based on DBM", highlight = 1, icon = br.player.spell.powerWordShield}, [2] = {mode = "Hold", value = 2, overlay = "Ramp Disabled", tip = "No Ramp Logic.", highlight = 0, icon = br.player.spell.powerWordShield} } CreateButton("Burst", 0, -1) end local function createOptions() local optionTable local function generalOptions() ------------------------- -------- UTILITY -------- ------------------------- section = br.ui:createSection(br.ui.window.profile, "General") br.ui:createCheckbox(section, "Enemy Target Lock") br.ui:createSpinner(section, "Heal OoC", 90, 1, 100, 1, "Set OoC HP value to heal.") br.ui:createCheckbox(section, "Power Word: Fortitude", "Maintain Fort Buff on Group") br.ui:createDropdown(section, "Dispel Magic", {"Only Target", "Auto"}, 1, "Dispel Target or Auto") br.ui:createDropdown(section, "Oh shit need heals", br.dropOptions.Toggle, 1, "Ignore dps limit") br.ui:createSpinner(section, "Body and Soul", 2, 0, 100, 1, "Movement (seconds) before Body and Soul") br.ui:createSpinner(section, "Angelic Feather", 2, 0, 100, 1, "Movement (seconds) before Feather") br.ui:createSpinner(section, "Fade", 95, 0, 100, 1, "Health to cast Fade if agro") br.ui:checkSectionState(section) section = br.ui:createSection(br.ui.window.profile, "Interrupts") br.ui:createCheckbox(section, "Shining Force - Int") br.ui:createCheckbox(section, "Psychic Scream - Int") if br.player.race == "Pandaren" then br.ui:createCheckbox(section, "Quaking Palm - Int") end br.ui:createSpinner(section, "Interrupt At", 0, 0, 95, 5, "Cast Percent to Cast At. Default: 0") br.ui:checkSectionState(section) end local function healingOptions() ------------------------- ---- SINGLE TARGET ------ ------------------------- section = br.ui:createSection(br.ui.window.profile, "Single Target Healing") --Atonement br.ui:createCheckbox(section, "Obey Atonement Limits") br.ui:createSpinnerWithout(section, "Tank Atonement HP", 95, 0, 100, 1, "Apply Atonement to Tank using Power Word: Shield and Power Word: Radiance. Health Percent to Cast At. Default: 95") br.ui:createSpinnerWithout(section, "Party Atonement HP", 95, 0, 100, 1, "Apply Atonement using Power Word: Shield and Power Word: Radiance. Health Percent to Cast At. Default: 95") br.ui:createSpinnerWithout(section, "Max Atonements", 3, 1, 40, 1, "Max Atonements to Keep Up At Once. Default: 3") br.ui:createDropdown(section, "Atonement Key", br.dropOptions.Toggle, 6, "Set key to press to spam atonements on everyone.") br.ui:createSpinner(section, "Heal Counter", 1, 1, 5, 1, "How many Heals to check before damaging") br.ui:createSpinner(section, "Shadow Mend", 65, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section, "Penance Heal", 60, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section, "Pain Suppression Tank", 30, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section, "Pain Suppression Party", 30, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section,"Revitalizing Voodoo Totem - Tank",30, 0, 100, 5 ) br.ui:createSpinner(section,"Revitalizing Voodoo Totem - Party",30, 0, 100, 5 ) if br.player.level < 28 then br.ui:createSpinner(section, "Low Level Flash Heal",60, 0, 100, 5) end br.ui:checkSectionState(section) ------------------------- ------ AOE HEALING ------ ------------------------- section = br.ui:createSection(br.ui.window.profile, "AOE Healing") --Power Word: Radiance br.ui:createSpinner(section, "Power Word: Radiance", 70, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "PWR Targets", 3, 0, 40, 1, "Minimum PWR Targets") --Shadow Covenant br.ui:createSpinner(section, "Shadow Covenant", 85, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Shadow Covenant Targets", 4, 0, 40, 1, "Minimum Shadow Covenant Targets") br.ui:checkSectionState(section) end local function damageOptions() ------------------------- ----- DAMAGE OPTIONS ---- ------------------------- section = br.ui:createSection(br.ui.window.profile, "Damage") br.ui:createSpinnerWithout(section, "Damage Mana Threshold") br.ui:createCheckbox(section, "Shadow Word: Pain/Purge The Wicked") br.ui:createSpinnerWithout(section, "SW:P/PtW Targets", 3, 0, 20, 1, "Maximum SW:P/PtW Targets") br.ui:createCheckbox(section, "Schism") br.ui:createCheckbox(section, "Penance") br.ui:createCheckbox(section, "Power Word: Solace") br.ui:createCheckbox(section, "Mind Blast") br.ui:createCheckbox(section, "Smite") br.ui:createCheckbox(section, "SHW: Death Snipe") br.ui:createSpinner(section, "Mindbender", 80, 0, 100, 5, "Mana Percent to Cast At") br.ui:createSpinner(section, "Shadowfiend", 80, 0, 100, 5, "Health Percent to Cast At") br.ui:checkSectionState(section) end local function cooldownOptions() ------------------------- ------- COOLDOWNS ------- ------------------------- section = br.ui:createSection(br.ui.window.profile, "Cooldowns") --Rapture when get Innervate br.ui:createCheckbox(section, "Rapture when get Innervate", "Auto Rapture when Innervated") --Rapture br.ui:createCheckbox(section, "Auto Rapture", "Auto Use Rapture based on DBM") br.ui:createSpinner(section, "Rapture", 60, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Rapture Targets", 3, 0, 40, 1, "Minimum Rapture Targets") --Evangelism br.ui:createSpinner(section, "Evangelism", 70, 0, 100, 1, "Health Percent to Cast At") br.ui:createCheckbox(section, "Evangelism Ramp") br.ui:createSpinnerWithout(section, "Evangelism Targets", 3, 0, 40, 1, "Target count to Cast At") br.ui:createSpinnerWithout(section, "Atonement for Evangelism", 3, 0, 40, 1, "Minimum Atonement count to Cast At") br.ui:checkSectionState(section) end local function defenseOptions() ------------------------- ------- DEFENSIVE ------- ------------------------- section = br.ui:createSection(br.ui.window.profile, "Defensive") br.ui:createSpinner(section, "Desperate Prayer", 40, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section, "Pot / Healthstone", 35, 0, 100, 5, "Health Percent to Cast At") if br.player.race == "Draenei" then br.ui:createSpinner(section, "Gift of the Naaru", 50, 0, 100, 5, "Health Percent to Cast At") end br.ui:checkSectionState(section) end optionTable = { { [1] = "General", [2] = generalOptions }, { [1] = "Healing", [2] = healingOptions }, { [1] = "Damage", [2] = damageOptions }, { [1] = "Cooldowns", [2] = cooldownOptions }, { [1] = "Defensive", [2] = defenseOptions } } return optionTable end local function runRotation() local buff = br.player.buff local cast = br.player.cast local combatTime = getCombatTime() local cd = br.player.cd local charges = br.player.charges local debuff = br.player.debuff local enemies = br.player.enemies local essence = br.player.essence local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), GetUnitSpeed("player") > 0 local freeMana = buff.innervate.exists() or buff.symbolOfHope.exists() local friends = friends or {} local gcd = br.player.gcd local gcdMax = br.player.gcdMax local healPot = getHealthPot() local inCombat = br.player.inCombat local inInstance = br.player.instance == "party" local inRaid = br.player.instance == "raid" local lastSpell = lastSpellCast local level = br.player.level local lootDelay = getOptionValue("LootDelay") local lowest = br.friend[1] local mana = getMana("player") local mode = br.player.ui.mode local perk = br.player.perk local php = br.player.health local power, powmax, powgen = br.player.power.mana.amount(), br.player.power.mana.max(), br.player.power.mana.regen() local pullTimer = br.DBM:getPulltimer() local race = br.player.race local racial = br.player.getRacial() local solo = #br.friend == 1 local spell = br.player.spell local tanks = getTanksTable() local talent = br.player.talent local ttd = getTTD local traits = br.player.traits local ttm = br.player.power.mana.ttm() local units = br.player.units local schismCount = debuff.schism.count() if timersTable then wipe(timersTable) end units.get(5) units.get(30) units.get(40) enemies.get(24) enemies.get(30) enemies.get(40) friends.yards40 = getAllies("player", 40) local atonementCount = br.player.buff.atonement.count() local schismBuff local ptwDebuff local deathnumber = tonumber((select(1, GetSpellDescription(32379):match("%d+"))), 10) if isChecked("Enemy Target Lock") and inCombat then if UnitIsFriend("target", "player") or UnitIsDeadOrGhost("target") or not UnitExists("target") or UnitIsPlayer("target") then TargetLastEnemy() end end -- set penance target for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if debuff.schism.exists("target") and ttd("target") > 4 then schismBuff = "target" elseif debuff.schism.exists(thisUnit) and not UnitIsOtherPlayersPet(thisUnit) and ttd(thisUnit) > 4 then schismBuff = thisUnit end if schismBuff == nil then if debuff.purgeTheWicked.exists("target") and ttd("target") > 4 then ptwDebuff = "target" elseif debuff.purgeTheWicked.exists(thisUnit) and not UnitIsOtherPlayersPet(thisUnit) and ttd(thisUnit) > 4 then ptwDebuff = thisUnit end end end local function atoneCount() notAtoned = 0 for i = 1, #br.friend do thisUnit = br.friend[1].unit if not buff.atonement.exists(thisUnit) then notAtoned = notAtoned + 1 end end return notAtoned end local current local function ptwTargets() current = 0 for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if debuff.purgeTheWicked.exists(thisUnit) or debuff.shadowWordPain.exists(thisUnit) then current = current + 1 end end return current end --------------------- ----- APL LISTS ----- --------------------- local function Interruptstuff() if useInterrupts() then for i = 1, #enemies.yards40 do thisUnit = enemies.yards40[i] if canInterrupt(thisUnit, getOptionValue("Interrupt At")) then if isChecked("Shining Force - Int") and getDistance(thisUnit) < 40 then if cast.shiningForce() then return end end if isChecked("Psychic Scream - Int") and getDistance(thisUnit) < 8 then if cast.psychicScream() then return end end if isChecked("Quaking Palm - Int") and getDistance(thisUnit) < 5 then if cast.quakingPalm(thisUnit) then return end end end end end end local function DefensiveTime() if useDefensive() then if isChecked("Fade") then for i = 1, #enemies.yards30 do local thisUnit = enemies.yards30[i] if UnitThreatSituation("player", thisUnit) ~= nil and UnitThreatSituation("player", thisUnit) > 1 and UnitAffectingCombat(thisUnit) then if cast.fade() then return end end end end if isChecked("Pot / Healthstone") and php <= getOptionValue("Pot / Healthstone") and inCombat and (hasHealthPot() or hasItem(5512) or hasItem(166799)) then if canUseItem(5512) then useItem(5512) elseif canUseItem(healPot) then useItem(healPot) elseif hasItem(166799) and canUseItem(166799) then useItem(166799) end end -- Gift of the Naaru if isChecked("Gift of the Naaru") and php <= getOptionValue("Gift of the Naaru") and php > 0 and br.player.race == "Draenei" then if cast.giftOfTheNaaru() then return end end if isChecked("Desperate Prayer") and php <= getOptionValue("Desperate Prayer") then if cast.desperatePrayer() then return end end end end local function CooldownTime() if useCDs() then -- Pain Suppression if isChecked("Pain Suppression Tank") and inCombat then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Pain Suppression Tank") and UnitGroupRolesAssigned(br.friend[i].unit) == "TANK" then if cast.painSuppression(br.friend[i].unit) then return end end end end if isChecked("Pain Suppression Party") and inCombat then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Pain Suppression Tank") then if cast.painSuppression(br.friend[i].unit) then return end end end end if isChecked("Rapture when get Innervate") and freeMana then if cast.rapture() then return end end for i = 1, #br.friend do if isChecked("Revitalizing Voodoo Totem - Tank") and hasEquiped(158320) and br.friend[i].hp <= getValue("Revitalizing Voodoo Totem - Tank") and UnitGroupRolesAssigned(br.friend[i].unit) == "TANK" then if GetItemCooldown(158320) <= gcdMax then UseItemByName(158320, lowest.unit) br.addonDebug("Using Revitalizing Voodoo Totem") end end end if isChecked("Revitalizing Voodoo Totem - Party") and hasEquiped(158320) and lowest.hp < getValue("Revitalizing Voodoo Totem - Party") or getValue("Revitalizing Voodoo Totem - Party") == 100 then if GetItemCooldown(158320) <= gcdMax then UseItemByName(158320, lowest.unit) br.addonDebug("Using Revitalizing Voodoo Totem") end end if isChecked("Rapture") then if getLowAllies(getValue("Rapture")) >= getValue("Rapture Targets") then if cast.rapture() then return end end end if (race == "Troll" or race == "Orc" or race == "MagharOrc" or race == "DarkIronDwarf" or race == "LightforgedDraenei") or (mana >= 30 and race == "BloodElf") then if race == "LightforgedDraenei" then if cast.racial("target", "ground") then return end else if cast.racial("player") then return end end end end end local function Dispelstuff() if mode.decurse == 1 then if isChecked("Dispel Magic") then if getOptionValue("Dispel Magic") == 1 then if canDispel("target", spell.dispelMagic) and GetObjectExists("target") then if cast.dispelMagic("target") then br.addonDebug("Casting Dispel Magic") return end end elseif getOptionValue("Dispel Magic") == 2 then for i = 1, #enemies.yards30 do local thisUnit = enemies.yards30[i] if canDispel(thisUnit, spell.dispelMagic) then if cast.dispelMagic(thisUnit) then br.addonDebug("Casting Dispel Magic") return end end end end end --Purify for i = 1, #br.friend do if canDispel(br.friend[i].unit, spell.purify) then if cast.purify(br.friend[i].unit) then return end end end end end local function Extrastuff() if IsMovingTime(getOptionValue("Angelic Feather")) and not IsSwimming() then if not runningTime then runningTime = GetTime() end if isChecked("Angelic Feather") and talent.angelicFeather and (not buff.angelicFeather.exists("player") or GetTime() > runningTime + 5) then if cast.angelicFeather("player") then runningTime = GetTime() SpellStopTargeting() end end end if IsMovingTime(getOptionValue("Body and Soul")) then if bnSTimer == nil then bnSTimer = GetTime() - 6 end if isChecked("Body and Soul") and talent.bodyAndSoul and not buff.bodyAndSoul.exists("player") and GetTime() >= bnSTimer + 6 then if cast.powerWordShield("player") then bnSTimer = GetTime() return end end end if isChecked("Power Word: Fortitude") and br.timer:useTimer("PW:F Delay", math.random(20, 50)) then for i = 1, #br.friend do if not buff.powerWordFortitude.exists(br.friend[i].unit, "any") and getDistance("player", br.friend[i].unit) < 40 and not UnitIsDeadOrGhost(br.friend[i].unit) then if cast.powerWordFortitude() then return end end end end end local function Keyshit() if (SpecificToggle("Atonement Key") and not GetCurrentKeyBoardFocus()) and isChecked("Atonement Key") then for i = 1, #br.friend do local thisUnit = br.friend[i].unit if not buff.atonement.exists(thisUnit) then if atoneCount() >= getOptionValue("Minimum PWR Targets") and not isMoving("player") and charges.powerWordRadiance.frac() >= 1 and level >= 23 then if cast.powerWordRadiance(thisUnit) then return true end elseif atonementCount <= getOptionValue("Atonement for Evangelism") or (charges.powerWordRadiance.frac() < 1 or level < 23) and not debuff.weakenedSoul.exists(thisUnit) then if cast.powerWordShield(thisUnit) then return true end end end if useCDs() and isChecked("Evangelism Ramp") and atonementCount >= getOptionValue("Atonement for Evangelism") and (charges.powerWordRadiance.count() == 0 or atoneCount() <= getOptionValue("Minimum PWR Targets")) then if cast.evangelism() then RunMacroText("/br toggle burst 1") return true end end end end end local function HealingTime() if buff.rapture.exists("player") then if isChecked("Obey Atonement Limits") then for i = 1, #br.friend do if atonementCount < getValue("Max Atonements") or (br.friend[i].role == "TANK" or UnitGroupRolesAssigned(br.friend[i].unit) == "TANK") then if getBuffRemain(br.friend[i].unit, spell.buffs.powerWordShield, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then return true end end end if atonementCount >= getValue("Max Atonements") then if cast.powerWordShield(lowest.unit) then return true end end end else for i = 1, #br.friend do if not buff.atonement.exists(br.friend[i].unit) and getBuffRemain(br.friend[i].unit, spell.buffs.powerWordShield, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then return true end end end for i = 1, #br.friend do if getBuffRemain(br.friend[i].unit, spell.buffs.powerWordShield, "player") < 1 then if cast.powerWordShield(br.friend[i].unit) then return true end end end end end if isChecked("Evangelism") and talent.evangelism and (atonementCount >= getValue("Atonement for Evangelism") or (not inRaid and atonementCount >= 3)) and not buff.rapture.exists("player") then if getLowAllies(getValue("Evangelism")) >= getValue("Evangelism Targets") then if cast.evangelism() then return true end end end if isChecked("Power Word: Radiance") and atoneCount() >= 2 and not cast.last.powerWordRadiance() and mode.burst ~= 2 then if charges.powerWordRadiance.count() >= 1 then if getLowAllies(getValue("Power Word: Radiance")) >= getValue("PWR Targets") then for i = 1, #br.friend do if not buff.atonement.exists(br.friend[i].unit) and br.friend[i].hp <= getValue("Power Word: Radiance") and not isMoving("player") then if cast.powerWordRadiance(br.friend[i].unit) then return true end end end end end end if isChecked("Shadow Covenant") and talent.shadowCovenant then if getLowAllies(getValue("Shadow Covenant")) >= getValue("Shadow Covenant Targets") then if cast.shadowCovenant(lowest.unit) then return true end end end if (isChecked("Penance Heal") and talent.contrition and atonementCount >= 3) or (isChecked("Heal OoC") and not inCombat and lowest.hp <= getOptionValue("Heal OoC")) or (level < 28 and lowest.hp < getOptionValue("Penance Heal")) then if cast.penance(lowest.unit) then return true end end if isChecked("Shadow Mend") and not isMoving("player") then for i = 1, #br.friend do if (br.friend[i].hp <= getValue("Shadow Mend") and (not buff.atonement.exists(br.friend[i].unit) or br.player.instance ~= "raid")) or (isChecked("Heal OoC") and not inCombat and lowest.hp <= getOptionValue("Heal OoC")) then if cast.shadowMend(br.friend[i].unit) then return true end end end end for i = 1, #tanks do if (tanks[i].hp <= getOptionValue("Tank Atonement HP") or getValue("Tank Atonement HP") == 100) and not buff.atonement.exists(tanks[i].unit) and not debuff.weakenedSoul.exists(tanks[i].unit) then if cast.powerWordShield(tanks[i].unit) then return true end end end for i = 1, #br.friend do if (br.friend[i].hp <= getOptionValue("Party Atonement HP") or getOptionValue("Party Atonement HP") == 100) and not debuff.weakenedSoul.exists(br.friend[i].unit) and not buff.atonement.exists(br.friend[i].unit) and (atonementCount < getOptionValue("Max Atonements") or not isChecked("Obey Atonement Limits")) then if cast.powerWordShield(br.friend[i].unit) then return true end end end if level < 28 then for i = 1, #br.friend do if isChecked("Low Level Flash Heal") and br.friend[i].hp <= getOptionValue("Low Level Flash Heal") then if cast.flashHeal(br.friend[i].unit) then return true end end end end end local function DamageTime() if isChecked("Power Word: Solace") and talent.powerWordSolace then if schismBuff ~= nil then if cast.powerWordSolace(schismBuff) then return end elseif schismBuff == nil then if cast.powerWordSolace("target") then return end end end if isChecked("SHW: Death Snipe") then for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if (UnitHealth(thisUnit) <= deathnumber) or (getHP(thisUnit) <= 20 and UnitHealth(thisUnit) <= deathnumber *1.5) then if cast.shadowWordDeath(thisUnit) then return end end end end if isChecked("Shadow Word: Pain/Purge The Wicked") and (getSpellCD(spell.penance) > gcdMax or (getSpellCD(spell.penance) <= gcdMax and debuff.purgeTheWicked.count() == 0)) then if talent.purgeTheWicked then for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if ptwTargets() < getValue("SW:P/PtW Targets") then if not debuff.purgeTheWicked.exists("target") and ttd("target") > 3 then if cast.purgeTheWicked("target") then return end elseif debuff.purgeTheWicked.remain(thisUnit) < 6 and not UnitIsOtherPlayersPet(thisUnit) and ttd(thisUnit) > 3 then if cast.purgeTheWicked(thisUnit) then return end end end end end if not talent.purgeTheWicked and cd.penance.remains() > gcd then for i = 1, #enemies.yards40 do local thisUnit = enemies.yards40[i] if ptwTargets() < getValue("SW:P/PtW Targets") then if not debuff.shadowWordPain.exists("target") and ttd("target") > 3 then if cast.shadowWordPain("target") then return end elseif debuff.shadowWordPain.remain(thisUnit) < 4.8 and not UnitIsOtherPlayersPet(thisUnit) and ttd(thisUnit) > 3 then if cast.shadowWordPain(thisUnit) then return end end end end end end -- Mindbender if isChecked("Mindbender") and mana <= getValue("Mindbender") and atonementCount >= 3 and talent.mindbender then if schismBuff ~= nil then if cast.mindbender(schismBuff) then return end elseif cast.mindbender() then return end end -- Shadowfiend if isChecked("Shadowfiend") and not talent.mindbender and atonementCount >= 3 then if schismBuff ~= nil then if cast.shadowfiend(schismBuff) then return end elseif cast.shadowfiend() then return end end if talent.schism and isChecked("Schism") and cd.penance.remain() <= gcdMax + 1 and not isMoving("player") and ttd("target") > 9 and not isExplosive("target") then if cast.schism("target") then return end end if isChecked("Penance") then if schismBuff ~= nil then if cast.penance(schismBuff) then return end elseif ptwDebuff ~= nil and schismBuff == nil then if cast.penance(ptwDebuff) then return end elseif (not schismBuff or ptwDebuff) and ttd("target") > 2.5 then if cast.penance("target") then return end end end if isChecked("Mind Blast") and not isMoving("player") then if schismBuff ~= nil and getFacing("player",schismBuff) then if cast.mindBlast(schismBuff) then return end elseif cast.mindBlast() then return end end if isChecked("Smite") and not isMoving("player") then if schismBuff ~= nil and getFacing("player",schismBuff) then if cast.smite(schismBuff) then return end elseif cast.smite() then return end end end ------------------------------ ------- Start the Stuff ------ if pause() or drinking then return true else if not inCombat then if isChecked("Heal OoC") then if HealingTime() then return true end end if Extrastuff() then return end if Dispelstuff() then return end if Keyshit() then return true end elseif inCombat then if Dispelstuff() then return end if Interruptstuff() then return end if DefensiveTime() then return end if CooldownTime() then return end if Keyshit() then return true end if discHealCount < getOptionValue("Heal Counter") or not isChecked("Heal Counter") or #enemies.yards40 == 0 or buff.rapture.exists("player") or SpecificToggle("Oh shit need heals") then if HealingTime() then return true end end if Extrastuff() then return end if DamageTime() then return end end end end local id = 256 if br.rotations[id] == nil then br.rotations[id] = {} end tinsert( br.rotations[id], { name = rotationName, toggles = createToggles, options = createOptions, run = runRotation } )
gpl-3.0
philanc/plc
test/test_sha3.lua
1
3977
-- Copyright (c) 2015 Phil Leblanc -- see LICENSE file ------------------------------------------------------------ -- sha3 tests local sha3 = require "plc.sha3" local bin = require "plc.bin" -- for hex conversion local insert, concat = table.insert, table.concat local function test_sha3() -- checked with sha3 512 and 256 on -- https://emn178.github.io/online-tools/sha3_512.html -- and with Python's hashlib.sha3, thanks to Michael Rosenberg -- (https://github.com/doomrobo) assert(sha3.sha512("") == bin.hextos[[ a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6 15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26 ]]) assert(sha3.sha512("abc") == bin.hextos[[ b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e 10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0 ]]) assert(sha3.sha512(('1'):rep(128)) == bin.hextos[[ 1e996f94a2c54cacd0fb3a778a3605e34c928bb9f51ffed970f05919dabf2fa3 fe12d5eafcb8457169846c67b5e30ede9b22c4c59ace3c11663965e4dba28294 ]]) assert(sha3.sha256("") == bin.hextos[[ a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a ]]) assert(sha3.sha256("abc") == bin.hextos[[ 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532 ]]) assert(sha3.sha256(('1'):rep(128)) == bin.hextos[[ fdfe32511b76f38a71a7ac95a4c98add2b41debab35e1b7dda8bb3b14c280533 ]]) -- check padding (all input sizes modulo 8) local st = { "", "a", "ab", "abc", "abcd", "abcde", "abcdef", "abcdefg", "abcdefgh", "abcdefghi", "abcdefghij" } local ht = {} -- hex digest values for _, s in ipairs(st) do insert(ht, sha3.sha256(s)) end for _, s in ipairs(st) do insert(ht, sha3.sha512(s)) end -- results local res = concat(ht) local expected = bin.hextos[[ a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a 80084bf2fba02475726feb2cab2d8215eab14bc6bdd8bfb2c8151257032ecd8b 5c828b33397f4762922e39a60c35699d2550466a52dd15ed44da37eb0bdc61e6 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532 6f6f129471590d2c91804c812b5750cd44cbdfb7238541c451e1ea2bc0193177 d716ec61e18904a8f58679b71cb065d4d5db72e0e0c3f155a4feff7add0e58eb 59890c1d183aa279505750422e6384ccb1499c793872d6f31bb3bcaa4bc9f5a5 7d55114476dfc6a2fbeaa10e221a8d0f32fc8f2efb69a6e878f4633366917a62 3e2020725a38a48eb3bbf75767f03a22c6b3f41f459c831309b06433ec649779 f74eb337992307c22bc59eb43e59583a683f3b93077e7f2472508e8c464d2657 d97f84d48722153838d4ede4f8ac5f9dea8abce77cd7367b2eb0dc500a36fbb4 a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26 697f2d856172cb8309d6b8b97dac4de344b549d4dee61edfb4962d8698b7fa803f4f93ff24393586e28b5b957ac3d1d369420ce53332712f997bd336d09ab02a 01c87b5e8f094d8725ed47be35430de40f6ab6bd7c6641a4ecf0d046c55cb468453796bb61724306a5fb3d90fbe3726a970e5630ae6a9cf9f30d2aa062a0175e b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0 6eb7b86765bf96a8467b72401231539cbb830f6c64120954c4567272f613f1364d6a80084234fa3400d306b9f5e10c341bbdc5894d9b484a8c7deea9cbe4e265 1d7c3aa6ee17da5f4aeb78be968aa38476dbee54842e1ae2856f4c9a5cd04d45dc75c2902182b07c130ed582d476995b502b8777ccf69f60574471600386639b 01309a45c57cd7faef9ee6bb95fed29e5e2e0312af12a95fffeee340e5e5948b4652d26ae4b75976a53cc1612141af6e24df36517a61f46a1a05f59cf667046a 9c93345c31ecffe20a95eca8db169f1b3ee312dd75fb3494cc1dc2f9a2b6092b6cbebf1299ec6d5ba46b08f728f3075109582bc71b97b4deac5122433732234c c9f25eee75ab4cf9a8cfd44f4992b282079b64d94647edbd88e818e44f701edeb450818f7272cba7a20205b3671ce1991ce9a6d2df8dbad6e0bb3e50493d7fa7 4dbdf4a9fc84c246217a68d5a8f3d2a761766cf78752057d60b730a4a8226ef99bbf580c85468f5e93d8fb7873bbdb0de44314e3adf4b94a4fc37c64ca949c6e b3e0886fff5ca1df436bf4f6efc124219f908c0abec14036e392a3204f4208b396da0da40e3273f596d4d3db1be4627a16f34230af12ccea92d5d107471551d7 ]] assert(res == expected) end test_sha3() print("test_sha3: ok")
mit
ld-test/oil
lua/oil/kernel/base/Proxies/asynchronous.lua
6
2034
local oo = require "oil.oo" --[[VERBOSE]] local verbose = require "oil.verbose" local utils = require "oil.kernel.base.Proxies.utils" local assertresults = utils.assertresults local unpackrequest = utils.unpackrequest -------------------------------------------------------------------------------- local Request = oo.class() function Request:ready() --[[VERBOSE]] verbose:proxies("check reply availability") local proxy = self.proxy assertresults(proxy, self.member, proxy.__manager.requester:getreply(self, true)) return self.success ~= nil end function Request:results() --[[VERBOSE]] verbose:proxies(true, "get reply results") local success, except = self.proxy.__manager.requester:getreply(self) if success then --[[VERBOSE]] verbose:proxies(false, "got results successfully") return unpackrequest(self) end --[[VERBOSE]] verbose:proxies(false, "got errors while reading reply") return success, except end function Request:evaluate() --[[VERBOSE]] verbose:proxies("get deferred results of ",self.member) return assertresults(self.proxy, self.member, self:results()) end -------------------------------------------------------------------------------- local Failed = oo.class({}, Request) function Failed:ready() return true end function Failed:results() return false, self[1] end -------------------------------------------------------------------------------- return function(invoker, operation) return function(self, ...) local request, except = invoker(self, ...) if request then request = Request(request) else request = Failed{ except } end request.proxy = self request.member = operation return request end end
mit
bigdogmat/wire
lua/wire/client/cl_modelplug.lua
2
32743
--Msg("=== Loading Wire Model Packs ===\n") CreateConVar("cl_showmodeltextbox", "0") --[[ -- Loads and converts model lists from the old WireModelPacks format do local converted = {} MsgN("WM: Loading models...") for _,filename in ipairs( file.Find("WireModelPacks/*", "DATA") ) do --for _,filename in ipairs{"bull_buttons.txt","bull_modelpack.txt","cheeze_buttons2.txt","default.txt","expression2.txt","wire_model_pack_1.txt","wire_model_pack_1plus.txt"} do filename = "WireModelPacks/"..filename print("Loading from WireModelPacks/"..filename) local f = file.Read(filename, "DATA") if f then converted[#converted+1] = "-- Converted from "..filename local packtbl = util.KeyValuesToTable(f) for name,entry in pairs(packtbl) do print(string.format("\tLoaded model %s => %s", name, entry.model)) local categorytable = string.Explode(",", entry.categories or "none") or { "none" } for _,cat in pairs(categorytable) do list.Set( "Wire_"..cat.."_Models", entry.model, true ) converted[#converted+1] = string.format('list.Set("Wire_%s_Models", "%s", true)', cat, entry.model) end end converted[#converted+1] = "" else print("Error opening "..filename) end end MsgN("End loading models") file.Write("converted.txt", table.concat(converted, "\n")) end ]] -- -- Add some more options to the stools -- --screens with a GPULib setup list.Set( "WireScreenModels", "models/props_lab/monitor01b.mdl", true ) list.Set( "WireScreenModels", "models/props/cs_office/tv_plasma.mdl", true ) list.Set( "WireScreenModels", "models/blacknecro/tv_plasma_4_3.mdl", true ) list.Set( "WireScreenModels", "models/props/cs_office/computer_monitor.mdl", true ) list.Set( "WireScreenModels", "models/kobilica/wiremonitorbig.mdl", true ) list.Set( "WireScreenModels", "models/kobilica/wiremonitorsmall.mdl", true ) list.Set( "WireScreenModels", "models/props/cs_assault/Billboard.mdl", true ) list.Set( "WireScreenModels", "models/cheeze/pcb/pcb4.mdl", true ) list.Set( "WireScreenModels", "models/cheeze/pcb/pcb6.mdl", true ) list.Set( "WireScreenModels", "models/cheeze/pcb/pcb5.mdl", true ) list.Set( "WireScreenModels", "models/cheeze/pcb/pcb7.mdl", true ) list.Set( "WireScreenModels", "models/cheeze/pcb/pcb8.mdl", true ) list.Set( "WireScreenModels", "models/cheeze/pcb2/pcb8.mdl", true ) list.Set( "WireScreenModels", "models/props/cs_militia/reload_bullet_tray.mdl", true ) list.Set( "WireScreenModels", "models/props_lab/workspace002.mdl", true ) --list.Set( "WireScreenModels", "models/blacknecro/ledboard60.mdl", true ) --broken --TF2 Billboards list.Set( "WireScreenModels", "models/props_mining/billboard001.mdl", true ) list.Set( "WireScreenModels", "models/props_mining/billboard002.mdl", true ) --PHX3 list.Set( "WireScreenModels", "models/hunter/plates/plate1x1.mdl", true ) list.Set( "WireScreenModels", "models/hunter/plates/plate2x2.mdl", true ) list.Set( "WireScreenModels", "models/hunter/plates/plate4x4.mdl", true ) list.Set( "WireScreenModels", "models/hunter/plates/plate8x8.mdl", true ) list.Set( "WireScreenModels", "models/hunter/plates/plate05x05.mdl", true ) list.Set( "WireScreenModels", "models/hunter/blocks/cube1x1x1.mdl", true ) --screens with out a GPULib setup (for the tools wire_panel and wire_screen) list.Set( "WireNoGPULibScreenModels", "models/props_lab/monitor01b.mdl", true ) list.Set( "WireNoGPULibScreenModels", "models/props/cs_office/tv_plasma.mdl", true ) list.Set( "WireNoGPULibScreenModels", "models/props/cs_office/computer_monitor.mdl", true ) list.Set( "WireNoGPULibScreenModels", "models/kobilica/wiremonitorbig.mdl", true ) list.Set( "WireNoGPULibScreenModels", "models/kobilica/wiremonitorsmall.mdl", true ) --sounds local WireSounds = { ["Warning"] = "common/warning.wav", ["Talk"] = "common/talk.wav", ["Button"] = "buttons/button15.wav", ["Denied"] = "buttons/weapon_cant_buy.wav", ["Zap"] = "ambient/energy/zap2.wav", ["Oh No"] = "vo/npc/male01/ohno.wav", ["Yeah"] = "vo/npc/male01/yeah02.wav", ["apc alarm"] = "ambient/alarms/apc_alarm_loop1.wav", ["Coast Siren"] = "coast.siren_citizen", ["Bunker Siren"] = "coast.bunker_siren1", ["Alarm Bell"] = "d1_canals.Floodgate_AlarmBellLoop", ["Engine Start"] = "ATV_engine_start", ["Engine Stop"] = "ATV_engine_stop", ["Zombie Breathe"] = "NPC_PoisonZombie.Moan1", ["Idle Zombies"] = "Zombie.Idle", ["Turret Alert"] = "NPC_FloorTurret.Alert", ["Helicopter Rotor"] = "NPC_CombineGunship.RotorSound", ["Heartbeat"] = "k_lab.teleport_heartbeat", ["Breathing"] = "k_lab.teleport_breathing", } for k,v in pairs(WireSounds) do list.Set("WireSounds",k,{wire_soundemitter_sound=v}); end --some extra wheels that wired wheels have local wastelandwheels = { "models/props_wasteland/wheel01a.mdl", "models/props_wasteland/wheel02a.mdl", "models/props_wasteland/wheel03a.mdl", "models/props_wasteland/wheel03b.mdl" } for k,v in pairs(wastelandwheels) do if file.Exists(v,"GAME") then list.Set( "WheelModels", v, { wheel_rx = 90, wheel_ry = 0, wheel_rz = 90} ) end end --Cheeze's Buttons Pack local CheezesButtons = { "models/cheeze/buttons/button_arm.mdl", "models/cheeze/buttons/button_clear.mdl", "models/cheeze/buttons/button_enter.mdl", "models/cheeze/buttons/button_fire.mdl", "models/cheeze/buttons/button_minus.mdl", "models/cheeze/buttons/button_muffin.mdl", "models/cheeze/buttons/button_plus.mdl", "models/cheeze/buttons/button_reset.mdl", "models/cheeze/buttons/button_set.mdl", "models/cheeze/buttons/button_start.mdl", "models/cheeze/buttons/button_stop.mdl", } for k,v in ipairs(CheezesButtons) do if file.Exists(v,"GAME") then list.Set( "ButtonModels", v, {} ) list.Set( "Wire_button_Models", v, true ) end end local CheezesSmallButtons = { "models/cheeze/buttons/button_0.mdl", "models/cheeze/buttons/button_1.mdl", "models/cheeze/buttons/button_2.mdl", "models/cheeze/buttons/button_3.mdl", "models/cheeze/buttons/button_4.mdl", "models/cheeze/buttons/button_5.mdl", "models/cheeze/buttons/button_6.mdl", "models/cheeze/buttons/button_7.mdl", "models/cheeze/buttons/button_8.mdl", "models/cheeze/buttons/button_9.mdl", } for k,v in ipairs(CheezesSmallButtons) do if file.Exists(v,"GAME") then list.Set( "ButtonModels", v, {} ) list.Set( "Wire_button_small_Models", v, true ) end end local Buttons = { "models/props_citizen_tech/Firetrap_button01a.mdl", "models/props_c17/clock01.mdl", "models/dav0r/buttons/switch.mdl", "models/dav0r/buttons/button.mdl", "models/cheeze/buttons2/air.mdl", "models/cheeze/buttons2/go.mdl", "models/cheeze/buttons2/3.mdl", "models/cheeze/buttons2/right.mdl", "models/cheeze/buttons2/alert.mdl", "models/cheeze/buttons2/plus.mdl", "models/cheeze/buttons2/activate.mdl", "models/cheeze/buttons2/coolant.mdl", "models/cheeze/buttons2/pwr_blue.mdl", "models/cheeze/buttons2/6.mdl", "models/cheeze/buttons2/easy.mdl", "models/cheeze/buttons2/muffin.mdl", "models/cheeze/buttons2/pwr_red.mdl", "models/cheeze/buttons2/1.mdl", "models/cheeze/buttons2/8.mdl", "models/cheeze/buttons2/aim.mdl", "models/cheeze/buttons2/compile.mdl", "models/cheeze/buttons2/set.mdl", "models/cheeze/buttons2/0.mdl", "models/cheeze/buttons2/arm.mdl", "models/cheeze/buttons2/test.mdl", "models/cheeze/buttons2/left.mdl", "models/cheeze/buttons2/pwr_green.mdl", "models/cheeze/buttons2/clock.mdl", "models/cheeze/buttons2/divide.mdl", "models/cheeze/buttons2/fire.mdl", "models/cheeze/buttons2/cake.mdl", "models/cheeze/buttons2/clear.mdl", "models/cheeze/buttons2/4.mdl", "models/cheeze/buttons2/power.mdl", "models/cheeze/buttons2/5.mdl", "models/cheeze/buttons2/deactivate.mdl", "models/cheeze/buttons2/down.mdl", "models/cheeze/buttons2/minus.mdl", "models/cheeze/buttons2/stop.mdl", "models/cheeze/buttons2/energy.mdl", "models/cheeze/buttons2/charge.mdl", "models/cheeze/buttons2/overide.mdl", "models/cheeze/buttons2/equals.mdl", "models/cheeze/buttons2/up.mdl", "models/cheeze/buttons2/toggle.mdl", "models/cheeze/buttons2/reset.mdl", "models/cheeze/buttons2/enter.mdl", "models/cheeze/buttons2/2.mdl", "models/cheeze/buttons2/start.mdl", "models/cheeze/buttons2/multiply.mdl", "models/cheeze/buttons2/7.mdl", "models/cheeze/buttons2/9.mdl", --animated buttons from here "models/props_lab/freightelevatorbutton.mdl", "models/props/switch001.mdl", "models/props_combine/combinebutton.mdl", "models/props_mining/control_lever01.mdl", "models/props_mining/freightelevatorbutton01.mdl", "models/props_mining/freightelevatorbutton02.mdl", "models/props_mining/switch01.mdl", "models/props_mining/switch_updown01.mdl", "models/maxofs2d/button_01.mdl", "models/maxofs2d/button_02.mdl", "models/maxofs2d/button_03.mdl", "models/maxofs2d/button_04.mdl", "models/maxofs2d/button_05.mdl", "models/maxofs2d/button_06.mdl", "models/bull/buttons/toggle_switch.mdl", "models/bull/buttons/rocker_switch.mdl", "models/bull/buttons/key_switch.mdl", } for k,v in ipairs(Buttons) do if file.Exists(v,"GAME") then list.Set( "Wire_button_Models", v, true ) end end --Dynamic button materials local WireDynamicButtonMaterials = { ["No Material"] = "", ["Clean"] = "bull/dynamic_button_clean", ["0"] = "bull/dynamic_button_0", ["1"] = "bull/dynamic_button_1", ["2"] = "bull/dynamic_button_2", ["3"] = "bull/dynamic_button_3", ["4"] = "bull/dynamic_button_4", ["5"] = "bull/dynamic_button_5", ["6"] = "bull/dynamic_button_6", ["7"] = "bull/dynamic_button_7", ["8"] = "bull/dynamic_button_8", ["9"] = "bull/dynamic_button_9" } for k,v in pairs(WireDynamicButtonMaterials) do list.Set("WireDynamicButtonMaterialsOn" ,k,{wire_dynamic_button_material_on =v}); list.Set("WireDynamicButtonMaterialsOff",k,{wire_dynamic_button_material_off=v}); end --Thrusters --Jaanus Thruster Pack --MsgN("\tJaanus' Thruster Pack") local JaanusThrusters = { "models/props_junk/garbage_metalcan001a.mdl", "models/jaanus/thruster_flat.mdl", "models/jaanus/thruster_invisi.mdl", "models/jaanus/thruster_shoop.mdl", "models/jaanus/thruster_smile.mdl", "models/jaanus/thruster_muff.mdl", "models/jaanus/thruster_rocket.mdl", "models/jaanus/thruster_megaphn.mdl", "models/jaanus/thruster_stun.mdl" } for k,v in pairs(JaanusThrusters) do if file.Exists(v,"GAME") then list.Set( "ThrusterModels", v, true ) end end local explosivemodels = { "models/dav0r/tnt/tnt.mdl", "models/Combine_Helicopter/helicopter_bomb01.mdl", "models/jaanus/thruster_flat.mdl", "models/props_c17/oildrum001.mdl", "models/props_c17/oildrum001_explosive.mdl", "models/props_phx/cannonball.mdl", "models/props_phx/facepunch_barrel.mdl", "models/props_phx/oildrum001.mdl", "models/props_phx/oildrum001_explosive.mdl", "models/props_phx/amraam.mdl", "models/props_phx/mk-82.mdl", "models/props_phx/rocket1.mdl", "models/props_phx/torpedo.mdl", "models/props_phx/ww2bomb.mdl", "models/props_junk/plasticbucket001a.mdl", "models/props_junk/PropaneCanister001a.mdl", "models/props_junk/propane_tank001a.mdl", "models/props_junk/PopCan01a.mdl", "models/props_lab/jar01a.mdl", "models/props_c17/canister_propane01a.mdl", "models/props_c17/canister01a.mdl", "models/props_c17/canister02a.mdl", "models/props_wasteland/gaspump001a.mdl", "models/props_junk/cardboard_box001a.mdl", "models/props_junk/cardboard_box001b.mdl", "models/props_junk/cardboard_box002a.mdl", "models/props_junk/cardboard_box002b.mdl", "models/props_junk/cardboard_box003a.mdl", "models/props_junk/cardboard_box003b.mdl", "models/props_junk/cardboard_box004a.mdl", "models/props_junk/CinderBlock01a.mdl", "models/props_junk/gascan001a.mdl", "models/props_junk/TrafficCone001a.mdl", "models/props_junk/metalgascan.mdl", "models/props_junk/metal_paintcan001a.mdl", "models/props_junk/wood_crate001a.mdl", "models/props_junk/wood_crate002a.mdl", "models/props_junk/wood_pallet001a.mdl", } for k,v in pairs(explosivemodels) do if file.Exists(v,"GAME") then list.Set( "Wire_Explosive_Models", v, true ) end end for k,v in pairs({ "models/props_c17/canister01a.mdl", "models/props_interiors/Furniture_Lamp01a.mdl", "models/props_c17/oildrum001.mdl", "models/props_phx/misc/smallcannon.mdl", "models/props_c17/fountain_01.mdl" }) do if file.Exists(v,"GAME") then list.Set( "Wire_Gimbal_Models", v, true ) end end local valuemodels = { "models/kobilica/value.mdl", "models/bull/gates/resistor.mdl", "models/bull/gates/transistor1.mdl", "models/bull/gates/transistor2.mdl", "models/cheeze/wires/cpu.mdl", "models/cheeze/wires/chip.mdl", "models/cheeze/wires/ram.mdl", "models/cheeze/wires/nano_value.mdl", -- This guy doesn't have a normal sized one in that folder } for k,v in pairs(valuemodels) do if file.Exists(v,"GAME") then list.Set( "Wire_Value_Models", v, true ) end end local teleportermodels = { "models/props_c17/utilityconducter001.mdl", "models/Combine_Helicopter/helicopter_bomb01.mdl", "models/props_combine/combine_interface001.mdl", "models/props_combine/combine_interface002.mdl", "models/props_combine/combine_interface003.mdl", "models/props_combine/combine_emitter01.mdl", "models/props_junk/sawblade001a.mdl", "models/props_combine/health_charger001.mdl", "models/props_combine/suit_charger001.mdl", "models/props_lab/reciever_cart.mdl", "models/props_lab/reciever01a.mdl", "models/props_lab/reciever01b.mdl", "models/props_lab/reciever01d.mdl", "models/props_c17/pottery03a.mdl", "models/props_wasteland/laundry_washer003.mdl" } for k,v in pairs(teleportermodels) do if file.Exists(v,"GAME") then list.Set( "WireTeleporterModels", v, true ) end end local turretmodels = { "models/weapons/w_smg1.mdl", "models/weapons/w_smg_mp5.mdl", "models/weapons/w_smg_mac10.mdl", "models/weapons/w_rif_m4a1.mdl", "models/weapons/w_357.mdl", "models/weapons/w_shot_m3super90.mdl" } for k,v in pairs(turretmodels) do if file.Exists(v,"GAME") then list.Set( "WireTurretModels", v, true ) end end local satellitedish_models = { "models/props_wasteland/prison_lamp001c.mdl", "models/props_rooftop/satellitedish02.mdl", -- EP2, but its perfect } for k,v in pairs(satellitedish_models) do if file.Exists(v,"GAME") then list.Set( "Wire_satellitedish_Models", v, true ) end end --Beer's models --MsgN("\tBeer's Model pack") --Keyboard list.Set( "Wire_Keyboard_Models", "models/beer/wiremod/keyboard.mdl", true ) list.Set( "Wire_Keyboard_Models", "models/jaanus/wiretool/wiretool_input.mdl", true ) list.Set( "Wire_Keyboard_Models", "models/props/kb_mouse/keyboard.mdl", true ) list.Set( "Wire_Keyboard_Models", "models/props_c17/computer01_keyboard.mdl", true ) --Hydraulic list.Set( "Wire_Hydraulic_Models", "models/beer/wiremod/hydraulic.mdl", true ) list.Set( "Wire_Hydraulic_Models", "models/jaanus/wiretool/wiretool_siren.mdl", true ) --GPS list.Set( "Wire_GPS_Models", "models/beer/wiremod/gps.mdl", true ) list.Set( "Wire_GPS_Models", "models/jaanus/wiretool/wiretool_speed.mdl", true ) --Numpad list.Set( "Wire_Numpad_Models", "models/beer/wiremod/numpad.mdl", true ) list.Set( "Wire_Numpad_Models", "models/jaanus/wiretool/wiretool_input.mdl", true ) list.Set( "Wire_Numpad_Models", "models/jaanus/wiretool/wiretool_output.mdl", true ) --Water Sensor list.Set( "Wire_WaterSensor_Models", "models/beer/wiremod/watersensor.mdl", true ) list.Set( "Wire_WaterSensor_Models", "models/jaanus/wiretool/wiretool_range.mdl", true ) --Target Finder list.Set( "Wire_TargetFinder_Models", "models/beer/wiremod/targetfinder.mdl", true ) list.Set( "Wire_TargetFinder_Models", "models/props_lab/powerbox02d.mdl", true ) list.Set( "Wire_Forcer_Models", "models/jaanus/wiretool/wiretool_grabber_forcer.mdl", true ) list.Set( "Wire_Forcer_Models", "models/jaanus/wiretool/wiretool_siren.mdl", true ) --Misc Tools (Entity Marker, Eye Pod, GpuLib Switcher, ect...) list.Set( "Wire_Misc_Tools_Models", "models/jaanus/wiretool/wiretool_range.mdl", true ) list.Set( "Wire_Misc_Tools_Models", "models/jaanus/wiretool/wiretool_siren.mdl", true ) list.Set( "Wire_Misc_Tools_Models", "models/props_lab/powerbox02d.mdl", true ) --Laser Tools (Ranger, User, etc) list.Set( "Wire_Laser_Tools_Models", "models/jaanus/wiretool/wiretool_range.mdl", true ) list.Set( "Wire_Laser_Tools_Models", "models/jaanus/wiretool/wiretool_siren.mdl", true ) list.Set( "Wire_Laser_Tools_Models", "models/jaanus/wiretool/wiretool_beamcaster.mdl", true ) list.Set( "Wire_Socket_Models", "models/props_lab/tpplugholder_single.mdl", true ) list.Set( "Wire_Socket_Models", "models/bull/various/usb_socket.mdl", true ) list.Set( "Wire_Socket_Models", "models/hammy/pci_slot.mdl", true ) list.Set( "Wire_Socket_Models", "models/wingf0x/isasocket.mdl", true ) list.Set( "Wire_Socket_Models", "models/wingf0x/altisasocket.mdl", true ) list.Set( "Wire_Socket_Models", "models/wingf0x/ethernetsocket.mdl", true ) list.Set( "Wire_Socket_Models", "models/wingf0x/hdmisocket.mdl", true ) -- Converted from WireModelPacks/wire_model_pack_1plus.txt list.Set("Wire_radio_Models", "models/props_lab/reciever01b.mdl", true) list.Set("Wire_pixel_Models", "models/jaanus/wiretool/wiretool_pixel_med.mdl", true) list.Set("Wire_indicator_Models", "models/jaanus/wiretool/wiretool_pixel_med.mdl", true) list.Set("Wire_waypoint_Models", "models/jaanus/wiretool/wiretool_waypoint.mdl", true) list.Set("Wire_pixel_Models", "models/jaanus/wiretool/wiretool_pixel_sml.mdl", true) list.Set("Wire_indicator_Models", "models/jaanus/wiretool/wiretool_pixel_sml.mdl", true) list.Set("Wire_radio_Models", "models/props_lab/reciever01a.mdl", true) list.Set("Wire_gate_Models", "models/jaanus/wiretool/wiretool_controlchip.mdl", true) list.Set("Wire_chip_Models", "models/jaanus/wiretool/wiretool_controlchip.mdl", true) list.Set("Wire_control_Models", "models/jaanus/wiretool/wiretool_controlchip.mdl", true) list.Set("Wire_detonator_Models", "models/jaanus/wiretool/wiretool_detonator.mdl", true) list.Set("Wire_beamcasting_Models", "models/jaanus/wiretool/wiretool_beamcaster.mdl", true) list.Set("Wire_radio_Models", "models/props_lab/reciever01c.mdl", true) list.Set("Wire_pixel_Models", "models/jaanus/wiretool/wiretool_pixel_lrg.mdl", true) list.Set("Wire_indicator_Models", "models/jaanus/wiretool/wiretool_pixel_lrg.mdl", true) -- Converted from WireModelPacks/wire_model_pack_1.txt list.Set("Wire_gate_Models", "models/cheeze/wires/amd_test.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/amd_test.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/mini_cpu.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/mini_cpu.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/ram.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/ram.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/nano_logic.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/nano_logic.mdl", true) list.Set("Wire_gate_Models", "models/kobilica/transistorsmall.mdl", true) list.Set("Wire_chip_Models", "models/kobilica/transistorsmall.mdl", true) list.Set("Wire_gate_Models", "models/kobilica/transistor.mdl", true) list.Set("Wire_chip_Models", "models/kobilica/transistor.mdl", true) list.Set("Wire_radio_Models", "models/cheeze/wires/wireless_card.mdl", true) list.Set("Wire_gate_Models", "models/cyborgmatt/capacitor_large.mdl", true) list.Set("Wire_chip_Models", "models/cyborgmatt/capacitor_large.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/nano_memory.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/nano_memory.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/nano_trig.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/nano_trig.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/nano_chip.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/nano_chip.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/cpu2.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/cpu2.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/nano_math.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/nano_math.mdl", true) list.Set("Wire_radio_Models", "models/cheeze/wires/router.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/nano_select.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/nano_select.mdl", true) list.Set("Wire_gate_Models", "models/cyborgmatt/capacitor_medium.mdl", true) list.Set("Wire_chip_Models", "models/cyborgmatt/capacitor_medium.mdl", true) list.Set("Wire_gate_Models", "models/cyborgmatt/capacitor_small.mdl", true) list.Set("Wire_chip_Models", "models/cyborgmatt/capacitor_small.mdl", true) list.Set("Wire_speaker_Models", "models/killa-x/speakers/speaker_small.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/nano_compare.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/nano_compare.mdl", true) list.Set("Wire_speaker_Models", "models/killa-x/speakers/speaker_medium.mdl", true) list.Set("Wire_speaker_Models", "models/props_junk/garbage_metalcan002a.mdl", true) list.Set("Wire_gate_Models", "models/kobilica/capacatitor.mdl", true) list.Set("Wire_chip_Models", "models/kobilica/capacatitor.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/cpu.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/cpu.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/mini_chip.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/mini_chip.mdl", true) list.Set("Wire_gate_Models", "models/kobilica/lowpolygate.mdl", true) list.Set("Wire_chip_Models", "models/kobilica/lowpolygate.mdl", true) list.Set("Wire_gate_Models", "models/cheeze/wires/nano_timer.mdl", true) list.Set("Wire_chip_Models", "models/cheeze/wires/nano_timer.mdl", true) -- Converted from WireModelPacks/expression2.txt list.Set("Wire_expr2_Models", "models/expression 2/cpu_controller.mdl", true) list.Set("Wire_expr2_Models", "models/expression 2/cpu_microchip.mdl", true) list.Set("Wire_expr2_Models", "models/expression 2/cpu_expression.mdl", true) -- Converted from WireModelPacks/default.txt list.Set("Wire_pixel_Models", "models/segment2.mdl", true) list.Set("Wire_indicator_Models", "models/segment2.mdl", true) list.Set("Wire_indicator_Models", "models/props_trainstation/trainstation_clock001.mdl", true) list.Set("Wire_pixel_Models", "models/segment.mdl", true) list.Set("Wire_indicator_Models", "models/segment.mdl", true) list.Set("Wire_gyroscope_Models", "models/bull/various/gyroscope.mdl", true) list.Set("Wire_weight_Models", "models/props_interiors/pot01a.mdl", true) list.Set("Wire_pixel_Models", "models/jaanus/wiretool/wiretool_siren.mdl", true) list.Set("Wire_indicator_Models", "models/jaanus/wiretool/wiretool_siren.mdl", true) list.Set("Wire_indicator_Models", "models/props_borealis/bluebarrel001.mdl", true) list.Set("Wire_indicator_Models", "models/props_junk/TrafficCone001a.mdl", true) list.Set("Wire_speaker_Models", "models/props_junk/garbage_metalcan002a.mdl", true) list.Set("Wire_pixel_Models", "models/led2.mdl", true) list.Set("Wire_indicator_Models", "models/led2.mdl", true) list.Set("Wire_weight_Models", "models/props_lab/huladoll.mdl", true) list.Set("Wire_radio_Models", "models/props_lab/binderblue.mdl", true) list.Set("Wire_pixel_Models", "models/led.mdl", true) list.Set("Wire_indicator_Models", "models/led.mdl", true) list.Set("Wire_gyroscope_Models", "models/cheeze/wires/gyroscope.mdl", true) list.Set("Wire_pixel_Models", "models/jaanus/wiretool/wiretool_range.mdl", true) list.Set("Wire_indicator_Models", "models/jaanus/wiretool/wiretool_range.mdl", true) list.Set("Wire_pixel_Models", "models/props_junk/PopCan01a.mdl", true) list.Set("Wire_indicator_Models", "models/props_junk/PopCan01a.mdl", true) list.Set("Wire_gate_Models", "models/jaanus/wiretool/wiretool_gate.mdl", true) list.Set("Wire_chip_Models", "models/jaanus/wiretool/wiretool_gate.mdl", true) list.Set("Wire_detonator_Models", "models/props_combine/breenclock.mdl", true) list.Set("Wire_speaker_Models", "models/cheeze/wires/speaker.mdl", true) list.Set("Wire_indicator_Models", "models/props_c17/clock01.mdl", true) list.Set("Wire_indicator_Models", "models/props_c17/gravestone004a.mdl", true) -- Converted from WireModelPacks/cheeze_buttons2.txt list.Set("Wire_button_small_Models", "models/cheeze/buttons2/compile_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/arm_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/fire_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/left_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/clear_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/aim_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/1_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/up_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/plus_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/stop_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/minus_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/6_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/coolant_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/power_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/toggle_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/activate_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/overide_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/pwr_red_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/go_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/pwr_blue_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/test_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/equals_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/energy_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/divide_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/clock_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/charge_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/alert_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/enter_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/5_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/2_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/deactivate_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/7_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/0_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/cake_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/reset_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/multiply_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/down_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/pwr_green_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/3_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/4_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/set_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/start_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/right_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/easy_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/8_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/muffin_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/air_small.mdl", true) list.Set("Wire_button_small_Models", "models/cheeze/buttons2/9_small.mdl", true) -- Converted from WireModelPacks/bull_modelpack.txt list.Set("Wire_gate_Models", "models/bull/gates/processor.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/processor.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/resistor_mini.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/resistor_mini.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/microcontroller2_nano.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/microcontroller2_nano.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/transistor2_nano.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/transistor2_nano.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/transistor1.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/transistor1.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/logic_nano.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/logic_nano.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/resistor_nano.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/resistor_nano.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/microcontroller2.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/microcontroller2.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/logic.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/logic.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/processor_nano.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/processor_nano.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/microcontroller1_nano.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/microcontroller1_nano.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/capacitor_mini.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/capacitor_mini.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/capacitor_nano.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/capacitor_nano.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/transistor1_nano.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/transistor1_nano.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/microcontroller2_mini.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/microcontroller2_mini.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/microcontroller1_mini.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/microcontroller1_mini.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/resistor.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/resistor.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/transistor2.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/transistor2.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/capacitor.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/capacitor.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/transistor1_mini.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/transistor1_mini.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/microcontroller1.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/microcontroller1.mdl", true) list.Set("Wire_speaker_Models", "models/bull/various/speaker.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/logic_mini.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/logic_mini.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/processor_mini.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/processor_mini.mdl", true) list.Set("Wire_gate_Models", "models/bull/gates/transistor2_mini.mdl", true) list.Set("Wire_chip_Models", "models/bull/gates/transistor2_mini.mdl", true) list.Set("Wire_speaker_Models", "models/bull/various/subwoofer.mdl", true) -- Converted from WireModelPacks/bull_buttons.txt list.Set("Wire_dynamic_button_Models", "models/bull/dynamicbuttonmedium.mdl", true) list.Set("Wire_dynamic_button_Models", "models/bull/dynamicbuttonflat.mdl", true) list.Set("Wire_dynamic_button_Models", "models/bull/dynamicbutton.mdl", true) list.Set("Wire_dynamic_button_small_Models", "models/bull/dynamicbuttonmedium_small.mdl", true) list.Set("Wire_dynamic_button_small_Models", "models/bull/dynamicbutton_small.mdl", true) list.Set("Wire_dynamic_button_small_Models", "models/bull/dynamicbuttonflat_small.mdl", true) list.Set("Wire_dynamic_button_Models", "models/maxofs2d/button_05.mdl", true)
apache-2.0
matija-hustic/OpenRA
mods/ra/maps/fort-lonestar/fort-lonestar.lua
9
8618
Patrol = { "e1", "e2", "e1" } Infantry = { "e4", "e1", "e1", "e2", "e1", "e2" } Vehicles = { "arty", "ftrk", "ftrk", "apc", "apc" } Tank = { "3tnk" } LongRange = { "v2rl" } Boss = { "4tnk" } SovietEntryPoints = { Entry1, Entry2, Entry3, Entry4, Entry5, Entry6, Entry7, Entry8 } PatrolWaypoints = { Entry2, Entry4, Entry6, Entry8 } ParadropWaypoints = { Paradrop1, Paradrop2, Paradrop3, Paradrop4 } OilDerricks = { OilDerrick1, OilDerrick2, OilDerrick3, OilDerrick4 } SpawnPoints = { Spawn1, Spawn2, Spawn3, Spawn4 } Snipers = { Sniper1, Sniper2, Sniper3, Sniper4, Sniper5, Sniper6, Sniper7, Sniper8, Sniper9, Sniper10, Sniper11, Sniper12 } Wave = 0 Waves = { { delay = 500, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 750, entries = PatrolWaypoints, units = Patrol, targets = ParadropWaypoints }, { delay = 750, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Vehicles, targets = SpawnPoints }, { delay = 1500, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1500, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Vehicles, targets = SpawnPoints }, { delay = 1500, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Tank, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Vehicles, targets = SpawnPoints }, { delay = 1500, entries = SovietEntryPoints, Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Tank, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Tank, targets = SpawnPoints }, { delay = 1500, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = LongRange, targets = SpawnPoints }, { delay = 1500, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = LongRange, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Tank, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = LongRange, targets = SpawnPoints }, { delay = 1500, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = LongRange, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = LongRange, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Tank, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Tank, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Vehicles, targets = SpawnPoints }, { delay = 1500, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Infantry, targets = SpawnPoints }, { delay = 1, entries = SovietEntryPoints, units = Boss, targets = SpawnPoints } } SendUnits = function(entryCell, unitTypes, interval, targetCell) Reinforcements.Reinforce(soviets, unitTypes, { entryCell }, interval, function(a) Trigger.OnIdle(a, function(a) if a.Location ~= targetCell then a.AttackMove(targetCell) else a.Hunt() end end) end) if (Wave < #Waves) then SendWave() else Trigger.AfterDelay(DateTime.Minutes(2), SovietsRetreating) Media.DisplayMessage("You survived the onslaught! No more waves incoming.") end end SendWave = function() Wave = Wave + 1 local wave = Waves[Wave] local entry = Utils.Random(wave.entries).Location local target = Utils.Random(wave.targets).Location Trigger.AfterDelay(wave.delay, function() SendUnits(entry, wave.units, 40, target) if not played then played = true Utils.Do(players, function(player) Media.PlaySpeechNotification(player, "EnemyUnitsApproaching") end) Trigger.AfterDelay(DateTime.Seconds(1), function() played = false end) end end) end SovietsRetreating = function() Utils.Do(Snipers, function(a) if not a.IsDead and a.Owner == soviets then a.Destroy() end end) end Tick = function() if (Utils.RandomInteger(1, 200) == 10) then local delay = Utils.RandomInteger(1, 10) Lighting.Flash("LightningStrike", delay) Trigger.AfterDelay(delay, function() Media.PlaySound("thunder" .. Utils.RandomInteger(1,6) .. ".aud") end) end if (Utils.RandomInteger(1, 200) == 10) then Media.PlaySound("thunder-ambient.aud") end end WorldLoaded = function() soviets = Player.GetPlayer("Soviets") players = { } for i = 0, 4, 1 do local player = Player.GetPlayer("Multi" ..i) players[i] = player end Utils.Do(Snipers, function(a) if a.Owner == soviets then a.GrantUpgrade("unkillable") end end) Media.DisplayMessage("Defend Fort Lonestar at all costs!") SendWave() end
gpl-3.0
ioiasff/qrt
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
bigdogmat/wire
lua/wire/stools/lever.lua
1
2120
WireToolSetup.setCategory( "Input, Output" ) WireToolSetup.open( "lever", "Lever", "gmod_wire_lever", nil, "Levers" ) if CLIENT then language.Add( "tool.wire_lever.name", "Lever Tool (Wire)" ) language.Add( "tool.wire_lever.desc", "Spawns a Lever for use with the wire system." ) language.Add( "tool.wire_lever.minvalue", "Max Value:" ) language.Add( "tool.wire_lever.maxvalue", "Min Value:" ) TOOL.Information = { { name = "left", text = "Create/Update " .. TOOL.Name } } end WireToolSetup.BaseLang() WireToolSetup.SetupMax( 10 ) if SERVER then function TOOL:GetConVars() return self:GetClientNumber( "min" ), self:GetClientNumber( "max" ) end function TOOL:MakeEnt( ply, model, Ang, trace ) //return WireLib.MakeWireEnt( ply, {Class = self.WireClass, Pos=trace.HitPos, Angle=Ang, Model=model}, self:GetConVars() ) local ent = WireLib.MakeWireEnt(ply, {Class = self.WireClass, Pos=(trace.HitPos + trace.HitNormal*22), Angle=Ang, Model=model}, self:GetConVars()) // +trace.HitNormal*46 local ent2 = ents.Create( "prop_physics" ) ent2:SetModel("models/props_wasteland/tram_leverbase01.mdl") ent2:SetPos(trace.HitPos) // +trace.HitNormal*26 ent2:SetAngles(Ang) ent2:Spawn() ent2:Activate() ent.BaseEnt = ent2 constraint.Weld(ent, ent2, 0, 0, 0, true) ent:SetParent(ent2) -- Parented + Weld seems more stable than a physical axis --local LPos = ent:WorldToLocal(ent:GetPos() + ent:GetUp() * 10) --local Cons = constraint.Ballsocket( ent2, ent, 0, 0, LPos, 0, 0, 1) --LPos = ent:WorldToLocal(ent:GetPos() + ent:GetUp() * -10) --Cons = constraint.Ballsocket( ent2, ent, 0, 0, LPos, 0, 0, 1) --constraint.Axis(ent, ent2, 0, 0, ent:WorldToLocal(ent2:GetPos()), ent2:GetRight()*0.15) return ent2 end -- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function end TOOL.ClientConVar = { model = "models/props_wasteland/tram_lever01.mdl", min = 0, max = 1 } function TOOL.BuildCPanel(panel) panel:NumSlider("#Tool.wire_lever.minvalue", "wire_lever_min", -10, 10, 2 ) panel:NumSlider("#Tool.wire_lever.maxvalue", "wire_lever_max", -10, 10, 2 ) end
apache-2.0
dwnld/thrift
lib/lua/TSocket.lua
113
2996
---- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- require 'TTransport' require 'libluasocket' -- TSocketBase TSocketBase = TTransportBase:new{ __type = 'TSocketBase', timeout = 1000, host = 'localhost', port = 9090, handle } function TSocketBase:close() if self.handle then self.handle:destroy() self.handle = nil end end -- Returns a table with the fields host and port function TSocketBase:getSocketInfo() if self.handle then return self.handle:getsockinfo() end terror(TTransportException:new{errorCode = TTransportException.NOT_OPEN}) end function TSocketBase:setTimeout(timeout) if timeout and ttype(timeout) == 'number' then if self.handle then self.handle:settimeout(timeout) end self.timeout = timeout end end -- TSocket TSocket = TSocketBase:new{ __type = 'TSocket', host = 'localhost', port = 9090 } function TSocket:isOpen() if self.handle then return true end return false end function TSocket:open() if self.handle then self:close() end -- Create local handle local sock, err = luasocket.create_and_connect( self.host, self.port, self.timeout) if err == nil then self.handle = sock end if err then terror(TTransportException:new{ message = 'Could not connect to ' .. self.host .. ':' .. self.port .. ' (' .. err .. ')' }) end end function TSocket:read(len) local buf = self.handle:receive(self.handle, len) if not buf or string.len(buf) ~= len then terror(TTransportException:new{errorCode = TTransportException.UNKNOWN}) end return buf end function TSocket:write(buf) self.handle:send(self.handle, buf) end function TSocket:flush() end -- TServerSocket TServerSocket = TSocketBase:new{ __type = 'TServerSocket', host = 'localhost', port = 9090 } function TServerSocket:listen() if self.handle then self:close() end local sock, err = luasocket.create(self.host, self.port) if not err then self.handle = sock else terror(err) end self.handle:settimeout(self.timeout) self.handle:listen() end function TServerSocket:accept() local client, err = self.handle:accept() if err then terror(err) end return TSocket:new({handle = client}) end
apache-2.0
ZeroK-RTS/Zero-K-Infrastructure
MissionEditor/MissionEditor2/MissionBase/LuaUI/Widgets/mission_selection_monitor.lua
9
1836
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Monitors Unit Selections", desc = "For the \"Unit Selected\" condition.", author = "quantum", date = "October 2010", license = "GNU GPL, v2 or later", layer = 1, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local oldSelection = {} function UpdateSelection() local changed local newSelection = Spring.GetSelectedUnits() local newSelectionCount = #newSelection if (newSelectionCount == #oldSelection) then for i=1, newSelectionCount do if (newSelection[i] ~= oldSelection[i]) then -- it appears that the order does not change changed = true break end end else changed = true end if changed then for i=1, newSelectionCount do local unitID = newSelection[i] if Spring.GetUnitRulesParam(unitID, "notifyselect") == 1 then Spring.SendLuaRulesMsg("notifyselect "..unitID) end end end oldSelection = newSelection end function widget:CommandsChanged() UpdateSelection() end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-3.0
ZeroK-RTS/Zero-K-Infrastructure
PlanetWars.old/Mods/BA66PW.sdd/LuaUI/Fonts/KOMTXT___16.lua
9
35223
-- $Id: KOMTXT___16.lua 3171 2008-11-06 09:06:29Z det $ local fontSpecs = { srcFile = [[KOMTXT__.ttf]], family = [[Komika Text]], style = [[Regular]], yStep = 20, height = 16, xTexSize = 512, yTexSize = 256, outlineRadius = 2, outlineWeight = 100, } local glyphs = {} glyphs[32] = { --' '-- num = 32, adv = 4, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 1, tyn = 1, txp = 6, typ = 6, } glyphs[33] = { --'!'-- num = 33, adv = 4, oxn = -2, oyn = -3, oxp = 6, oyp = 13, txn = 25, tyn = 1, txp = 33, typ = 17, } glyphs[34] = { --'"'-- num = 34, adv = 6, oxn = -2, oyn = 4, oxp = 8, oyp = 14, txn = 49, tyn = 1, txp = 59, typ = 11, } glyphs[35] = { --'#'-- num = 35, adv = 11, oxn = -1, oyn = -3, oxp = 13, oyp = 13, txn = 73, tyn = 1, txp = 87, typ = 17, } glyphs[36] = { --'$'-- num = 36, adv = 8, oxn = -2, oyn = -4, oxp = 10, oyp = 14, txn = 97, tyn = 1, txp = 109, typ = 19, } glyphs[37] = { --'%'-- num = 37, adv = 11, oxn = -1, oyn = -3, oxp = 13, oyp = 13, txn = 121, tyn = 1, txp = 135, typ = 17, } glyphs[38] = { --'&'-- num = 38, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 145, tyn = 1, txp = 159, typ = 17, } glyphs[39] = { --'''-- num = 39, adv = 3, oxn = -2, oyn = 4, oxp = 5, oyp = 14, txn = 169, tyn = 1, txp = 176, typ = 11, } glyphs[40] = { --'('-- num = 40, adv = 6, oxn = -1, oyn = -4, oxp = 9, oyp = 16, txn = 193, tyn = 1, txp = 203, typ = 21, } glyphs[41] = { --')'-- num = 41, adv = 6, oxn = -1, oyn = -4, oxp = 8, oyp = 16, txn = 217, tyn = 1, txp = 226, typ = 21, } glyphs[42] = { --'*'-- num = 42, adv = 9, oxn = -2, oyn = 2, oxp = 11, oyp = 16, txn = 241, tyn = 1, txp = 254, typ = 15, } glyphs[43] = { --'+'-- num = 43, adv = 9, oxn = -2, oyn = -3, oxp = 11, oyp = 10, txn = 265, tyn = 1, txp = 278, typ = 14, } glyphs[44] = { --','-- num = 44, adv = 3, oxn = -2, oyn = -4, oxp = 5, oyp = 4, txn = 289, tyn = 1, txp = 296, typ = 9, } glyphs[45] = { --'-'-- num = 45, adv = 6, oxn = -2, oyn = 1, oxp = 9, oyp = 8, txn = 313, tyn = 1, txp = 324, typ = 8, } glyphs[46] = { --'.'-- num = 46, adv = 3, oxn = -2, oyn = -3, oxp = 5, oyp = 5, txn = 337, tyn = 1, txp = 344, typ = 9, } glyphs[47] = { --'/'-- num = 47, adv = 6, oxn = -2, oyn = -3, oxp = 9, oyp = 13, txn = 361, tyn = 1, txp = 372, typ = 17, } glyphs[48] = { --'0'-- num = 48, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 385, tyn = 1, txp = 397, typ = 16, } glyphs[49] = { --'1'-- num = 49, adv = 4, oxn = -2, oyn = -2, oxp = 6, oyp = 13, txn = 409, tyn = 1, txp = 417, typ = 16, } glyphs[50] = { --'2'-- num = 50, adv = 8, oxn = -3, oyn = -2, oxp = 10, oyp = 13, txn = 433, tyn = 1, txp = 446, typ = 16, } glyphs[51] = { --'3'-- num = 51, adv = 8, oxn = -3, oyn = -2, oxp = 11, oyp = 13, txn = 457, tyn = 1, txp = 471, typ = 16, } glyphs[52] = { --'4'-- num = 52, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 13, txn = 481, tyn = 1, txp = 495, typ = 16, } glyphs[53] = { --'5'-- num = 53, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 1, tyn = 24, txp = 13, typ = 39, } glyphs[54] = { --'6'-- num = 54, adv = 9, oxn = -2, oyn = -2, oxp = 11, oyp = 13, txn = 25, tyn = 24, txp = 38, typ = 39, } glyphs[55] = { --'7'-- num = 55, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 49, tyn = 24, txp = 61, typ = 39, } glyphs[56] = { --'8'-- num = 56, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 73, tyn = 24, txp = 85, typ = 39, } glyphs[57] = { --'9'-- num = 57, adv = 8, oxn = -2, oyn = -2, oxp = 11, oyp = 13, txn = 97, tyn = 24, txp = 110, typ = 39, } glyphs[58] = { --':'-- num = 58, adv = 3, oxn = -2, oyn = -3, oxp = 6, oyp = 9, txn = 121, tyn = 24, txp = 129, typ = 36, } glyphs[59] = { --';'-- num = 59, adv = 3, oxn = -3, oyn = -4, oxp = 6, oyp = 9, txn = 145, tyn = 24, txp = 154, typ = 37, } glyphs[60] = { --'<'-- num = 60, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 10, txn = 169, tyn = 24, txp = 180, typ = 37, } glyphs[61] = { --'='-- num = 61, adv = 9, oxn = -1, oyn = 0, oxp = 11, oyp = 10, txn = 193, tyn = 24, txp = 205, typ = 34, } glyphs[62] = { --'>'-- num = 62, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 10, txn = 217, tyn = 24, txp = 228, typ = 37, } glyphs[63] = { --'?'-- num = 63, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 241, tyn = 24, txp = 253, typ = 40, } glyphs[64] = { --'@'-- num = 64, adv = 13, oxn = -2, oyn = -3, oxp = 15, oyp = 13, txn = 265, tyn = 24, txp = 282, typ = 40, } glyphs[65] = { --'A'-- num = 65, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 289, tyn = 24, txp = 303, typ = 40, } glyphs[66] = { --'B'-- num = 66, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 13, txn = 313, tyn = 24, txp = 326, typ = 40, } glyphs[67] = { --'C'-- num = 67, adv = 9, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 337, tyn = 24, txp = 351, typ = 40, } glyphs[68] = { --'D'-- num = 68, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 13, txn = 361, tyn = 24, txp = 374, typ = 40, } glyphs[69] = { --'E'-- num = 69, adv = 9, oxn = -1, oyn = -3, oxp = 11, oyp = 13, txn = 385, tyn = 24, txp = 397, typ = 40, } glyphs[70] = { --'F'-- num = 70, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 409, tyn = 24, txp = 422, typ = 40, } glyphs[71] = { --'G'-- num = 71, adv = 12, oxn = -2, oyn = -3, oxp = 14, oyp = 13, txn = 433, tyn = 24, txp = 449, typ = 40, } glyphs[72] = { --'H'-- num = 72, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 14, txn = 457, tyn = 24, txp = 471, typ = 41, } glyphs[73] = { --'I'-- num = 73, adv = 4, oxn = -1, oyn = -3, oxp = 6, oyp = 13, txn = 481, tyn = 24, txp = 488, typ = 40, } glyphs[74] = { --'J'-- num = 74, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 1, tyn = 47, txp = 14, typ = 63, } glyphs[75] = { --'K'-- num = 75, adv = 9, oxn = -1, oyn = -3, oxp = 11, oyp = 13, txn = 25, tyn = 47, txp = 37, typ = 63, } glyphs[76] = { --'L'-- num = 76, adv = 7, oxn = -1, oyn = -3, oxp = 10, oyp = 13, txn = 49, tyn = 47, txp = 60, typ = 63, } glyphs[77] = { --'M'-- num = 77, adv = 12, oxn = -1, oyn = -3, oxp = 15, oyp = 13, txn = 73, tyn = 47, txp = 89, typ = 63, } glyphs[78] = { --'N'-- num = 78, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 97, tyn = 47, txp = 112, typ = 63, } glyphs[79] = { --'O'-- num = 79, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 121, tyn = 47, txp = 136, typ = 63, } glyphs[80] = { --'P'-- num = 80, adv = 9, oxn = -1, oyn = -3, oxp = 12, oyp = 13, txn = 145, tyn = 47, txp = 158, typ = 63, } glyphs[81] = { --'Q'-- num = 81, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 169, tyn = 47, txp = 184, typ = 63, } glyphs[82] = { --'R'-- num = 82, adv = 9, oxn = -1, oyn = -3, oxp = 12, oyp = 13, txn = 193, tyn = 47, txp = 206, typ = 63, } glyphs[83] = { --'S'-- num = 83, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 217, tyn = 47, txp = 232, typ = 63, } glyphs[84] = { --'T'-- num = 84, adv = 8, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 241, tyn = 47, txp = 255, typ = 63, } glyphs[85] = { --'U'-- num = 85, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 13, txn = 265, tyn = 47, txp = 278, typ = 63, } glyphs[86] = { --'V'-- num = 86, adv = 8, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 289, tyn = 47, txp = 303, typ = 63, } glyphs[87] = { --'W'-- num = 87, adv = 12, oxn = -2, oyn = -3, oxp = 15, oyp = 13, txn = 313, tyn = 47, txp = 330, typ = 63, } glyphs[88] = { --'X'-- num = 88, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 337, tyn = 47, txp = 350, typ = 63, } glyphs[89] = { --'Y'-- num = 89, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 361, tyn = 47, txp = 376, typ = 63, } glyphs[90] = { --'Z'-- num = 90, adv = 9, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 385, tyn = 47, txp = 399, typ = 63, } glyphs[91] = { --'['-- num = 91, adv = 6, oxn = -2, oyn = -5, oxp = 9, oyp = 15, txn = 409, tyn = 47, txp = 420, typ = 67, } glyphs[92] = { --'\'-- num = 92, adv = 7, oxn = -1, oyn = -3, oxp = 9, oyp = 14, txn = 433, tyn = 47, txp = 443, typ = 64, } glyphs[93] = { --']'-- num = 93, adv = 6, oxn = -1, oyn = -5, oxp = 9, oyp = 15, txn = 457, tyn = 47, txp = 467, typ = 67, } glyphs[94] = { --'^'-- num = 94, adv = 6, oxn = 1, oyn = 6, oxp = 11, oyp = 14, txn = 481, tyn = 47, txp = 491, typ = 55, } glyphs[95] = { --'_'-- num = 95, adv = 8, oxn = -3, oyn = -4, oxp = 10, oyp = 2, txn = 1, tyn = 70, txp = 14, typ = 76, } glyphs[96] = { --'`'-- num = 96, adv = 8, oxn = 0, oyn = 5, oxp = 9, oyp = 14, txn = 25, tyn = 70, txp = 34, typ = 79, } glyphs[97] = { --'a'-- num = 97, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 49, tyn = 70, txp = 61, typ = 83, } glyphs[98] = { --'b'-- num = 98, adv = 8, oxn = -1, oyn = -3, oxp = 11, oyp = 13, txn = 73, tyn = 70, txp = 85, typ = 86, } glyphs[99] = { --'c'-- num = 99, adv = 7, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 97, tyn = 70, txp = 109, typ = 83, } glyphs[100] = { --'d'-- num = 100, adv = 9, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 121, tyn = 70, txp = 134, typ = 86, } glyphs[101] = { --'e'-- num = 101, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 145, tyn = 70, txp = 157, typ = 83, } glyphs[102] = { --'f'-- num = 102, adv = 6, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 169, tyn = 70, txp = 181, typ = 86, } glyphs[103] = { --'g'-- num = 103, adv = 8, oxn = -2, oyn = -6, oxp = 10, oyp = 10, txn = 193, tyn = 70, txp = 205, typ = 86, } glyphs[104] = { --'h'-- num = 104, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 13, txn = 217, tyn = 70, txp = 228, typ = 86, } glyphs[105] = { --'i'-- num = 105, adv = 4, oxn = -1, oyn = -3, oxp = 6, oyp = 13, txn = 241, tyn = 70, txp = 248, typ = 86, } glyphs[106] = { --'j'-- num = 106, adv = 4, oxn = -5, oyn = -7, oxp = 6, oyp = 13, txn = 265, tyn = 70, txp = 276, typ = 90, } glyphs[107] = { --'k'-- num = 107, adv = 7, oxn = -1, oyn = -3, oxp = 10, oyp = 13, txn = 289, tyn = 70, txp = 300, typ = 86, } glyphs[108] = { --'l'-- num = 108, adv = 4, oxn = -1, oyn = -3, oxp = 6, oyp = 13, txn = 313, tyn = 70, txp = 320, typ = 86, } glyphs[109] = { --'m'-- num = 109, adv = 12, oxn = -1, oyn = -3, oxp = 14, oyp = 10, txn = 337, tyn = 70, txp = 352, typ = 83, } glyphs[110] = { --'n'-- num = 110, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 10, txn = 361, tyn = 70, txp = 372, typ = 83, } glyphs[111] = { --'o'-- num = 111, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 10, txn = 385, tyn = 70, txp = 398, typ = 83, } glyphs[112] = { --'p'-- num = 112, adv = 8, oxn = -2, oyn = -7, oxp = 11, oyp = 10, txn = 409, tyn = 70, txp = 422, typ = 87, } glyphs[113] = { --'q'-- num = 113, adv = 9, oxn = -2, oyn = -7, oxp = 12, oyp = 10, txn = 433, tyn = 70, txp = 447, typ = 87, } glyphs[114] = { --'r'-- num = 114, adv = 6, oxn = -1, oyn = -3, oxp = 9, oyp = 10, txn = 457, tyn = 70, txp = 467, typ = 83, } glyphs[115] = { --'s'-- num = 115, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 10, txn = 481, tyn = 70, txp = 494, typ = 83, } glyphs[116] = { --'t'-- num = 116, adv = 7, oxn = -2, oyn = -3, oxp = 9, oyp = 12, txn = 1, tyn = 93, txp = 12, typ = 108, } glyphs[117] = { --'u'-- num = 117, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 10, txn = 25, tyn = 93, txp = 36, typ = 106, } glyphs[118] = { --'v'-- num = 118, adv = 7, oxn = -2, oyn = -3, oxp = 9, oyp = 10, txn = 49, tyn = 93, txp = 60, typ = 106, } glyphs[119] = { --'w'-- num = 119, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 10, txn = 73, tyn = 93, txp = 88, typ = 106, } glyphs[120] = { --'x'-- num = 120, adv = 7, oxn = -2, oyn = -3, oxp = 9, oyp = 10, txn = 97, tyn = 93, txp = 108, typ = 106, } glyphs[121] = { --'y'-- num = 121, adv = 7, oxn = -2, oyn = -6, oxp = 10, oyp = 10, txn = 121, tyn = 93, txp = 133, typ = 109, } glyphs[122] = { --'z'-- num = 122, adv = 7, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 145, tyn = 93, txp = 157, typ = 106, } glyphs[123] = { --'{'-- num = 123, adv = 8, oxn = -1, oyn = -5, oxp = 10, oyp = 15, txn = 169, tyn = 93, txp = 180, typ = 113, } glyphs[124] = { --'|'-- num = 124, adv = 4, oxn = -2, oyn = -5, oxp = 6, oyp = 15, txn = 193, tyn = 93, txp = 201, typ = 113, } glyphs[125] = { --'}'-- num = 125, adv = 8, oxn = -1, oyn = -5, oxp = 10, oyp = 16, txn = 217, tyn = 93, txp = 228, typ = 114, } glyphs[126] = { --'~'-- num = 126, adv = 8, oxn = -1, oyn = 6, oxp = 10, oyp = 13, txn = 241, tyn = 93, txp = 252, typ = 100, } glyphs[127] = { --''-- num = 127, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 265, tyn = 93, txp = 270, typ = 98, } glyphs[128] = { --'€'-- num = 128, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 289, tyn = 93, txp = 294, typ = 98, } glyphs[129] = { --''-- num = 129, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 313, tyn = 93, txp = 318, typ = 98, } glyphs[130] = { --'‚'-- num = 130, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 337, tyn = 93, txp = 342, typ = 98, } glyphs[131] = { --'ƒ'-- num = 131, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 361, tyn = 93, txp = 366, typ = 98, } glyphs[132] = { --'„'-- num = 132, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 385, tyn = 93, txp = 390, typ = 98, } glyphs[133] = { --'…'-- num = 133, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 409, tyn = 93, txp = 414, typ = 98, } glyphs[134] = { --'†'-- num = 134, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 433, tyn = 93, txp = 438, typ = 98, } glyphs[135] = { --'‡'-- num = 135, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 457, tyn = 93, txp = 462, typ = 98, } glyphs[136] = { --'ˆ'-- num = 136, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 481, tyn = 93, txp = 486, typ = 98, } glyphs[137] = { --'‰'-- num = 137, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 1, tyn = 116, txp = 6, typ = 121, } glyphs[138] = { --'Š'-- num = 138, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 25, tyn = 116, txp = 30, typ = 121, } glyphs[139] = { --'‹'-- num = 139, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 49, tyn = 116, txp = 54, typ = 121, } glyphs[140] = { --'Œ'-- num = 140, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 73, tyn = 116, txp = 78, typ = 121, } glyphs[141] = { --''-- num = 141, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 97, tyn = 116, txp = 102, typ = 121, } glyphs[142] = { --'Ž'-- num = 142, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 121, tyn = 116, txp = 126, typ = 121, } glyphs[143] = { --''-- num = 143, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 145, tyn = 116, txp = 150, typ = 121, } glyphs[144] = { --''-- num = 144, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 169, tyn = 116, txp = 174, typ = 121, } glyphs[145] = { --'‘'-- num = 145, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 193, tyn = 116, txp = 198, typ = 121, } glyphs[146] = { --'’'-- num = 146, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 217, tyn = 116, txp = 222, typ = 121, } glyphs[147] = { --'“'-- num = 147, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 241, tyn = 116, txp = 246, typ = 121, } glyphs[148] = { --'”'-- num = 148, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 265, tyn = 116, txp = 270, typ = 121, } glyphs[149] = { --'•'-- num = 149, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 289, tyn = 116, txp = 294, typ = 121, } glyphs[150] = { --'–'-- num = 150, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 313, tyn = 116, txp = 318, typ = 121, } glyphs[151] = { --'—'-- num = 151, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 337, tyn = 116, txp = 342, typ = 121, } glyphs[152] = { --'˜'-- num = 152, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 361, tyn = 116, txp = 366, typ = 121, } glyphs[153] = { --'™'-- num = 153, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 385, tyn = 116, txp = 390, typ = 121, } glyphs[154] = { --'š'-- num = 154, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 409, tyn = 116, txp = 414, typ = 121, } glyphs[155] = { --'›'-- num = 155, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 433, tyn = 116, txp = 438, typ = 121, } glyphs[156] = { --'œ'-- num = 156, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 457, tyn = 116, txp = 462, typ = 121, } glyphs[157] = { --''-- num = 157, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 481, tyn = 116, txp = 486, typ = 121, } glyphs[158] = { --'ž'-- num = 158, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 1, tyn = 139, txp = 6, typ = 144, } glyphs[159] = { --'Ÿ'-- num = 159, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 25, tyn = 139, txp = 30, typ = 144, } glyphs[160] = { --' '-- num = 160, adv = 4, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 49, tyn = 139, txp = 54, typ = 144, } glyphs[161] = { --'¡'-- num = 161, adv = 4, oxn = -2, oyn = -6, oxp = 6, oyp = 11, txn = 73, tyn = 139, txp = 81, typ = 156, } glyphs[162] = { --'¢'-- num = 162, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 97, tyn = 139, txp = 110, typ = 155, } glyphs[163] = { --'£'-- num = 163, adv = 9, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 121, tyn = 139, txp = 135, typ = 155, } glyphs[164] = { --'¤'-- num = 164, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 145, tyn = 139, txp = 150, typ = 144, } glyphs[165] = { --'¥'-- num = 165, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 169, tyn = 139, txp = 184, typ = 155, } glyphs[166] = { --'¦'-- num = 166, adv = 4, oxn = -2, oyn = -5, oxp = 6, oyp = 15, txn = 193, tyn = 139, txp = 201, typ = 159, } glyphs[167] = { --'§'-- num = 167, adv = 7, oxn = -2, oyn = 2, oxp = 9, oyp = 14, txn = 217, tyn = 139, txp = 228, typ = 151, } glyphs[168] = { --'¨'-- num = 168, adv = 7, oxn = -1, oyn = 6, oxp = 9, oyp = 13, txn = 241, tyn = 139, txp = 251, typ = 146, } glyphs[169] = { --'©'-- num = 169, adv = 12, oxn = -2, oyn = -4, oxp = 14, oyp = 14, txn = 265, tyn = 139, txp = 281, typ = 157, } glyphs[170] = { --'ª'-- num = 170, adv = 6, oxn = -2, oyn = 1, oxp = 8, oyp = 13, txn = 289, tyn = 139, txp = 299, typ = 151, } glyphs[171] = { --'«'-- num = 171, adv = 7, oxn = -2, oyn = 0, oxp = 10, oyp = 10, txn = 313, tyn = 139, txp = 325, typ = 149, } glyphs[172] = { --'¬'-- num = 172, adv = 15, oxn = -2, oyn = -3, oxp = 18, oyp = 15, txn = 337, tyn = 139, txp = 357, typ = 157, } glyphs[173] = { --'­'-- num = 173, adv = 8, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 361, tyn = 139, txp = 366, typ = 144, } glyphs[174] = { --'®'-- num = 174, adv = 8, oxn = -2, oyn = 1, oxp = 11, oyp = 14, txn = 385, tyn = 139, txp = 398, typ = 152, } glyphs[175] = { --'¯'-- num = 175, adv = 6, oxn = -2, oyn = 6, oxp = 9, oyp = 12, txn = 409, tyn = 139, txp = 420, typ = 145, } glyphs[176] = { --'°'-- num = 176, adv = 4, oxn = -2, oyn = 5, oxp = 7, oyp = 13, txn = 433, tyn = 139, txp = 442, typ = 147, } glyphs[177] = { --'±'-- num = 177, adv = 7, oxn = -2, oyn = -1, oxp = 9, oyp = 11, txn = 457, tyn = 139, txp = 468, typ = 151, } glyphs[178] = { --'²'-- num = 178, adv = 6, oxn = -2, oyn = 2, oxp = 8, oyp = 14, txn = 481, tyn = 139, txp = 491, typ = 151, } glyphs[179] = { --'³'-- num = 179, adv = 6, oxn = -2, oyn = 2, oxp = 8, oyp = 14, txn = 1, tyn = 162, txp = 11, typ = 174, } glyphs[180] = { --'´'-- num = 180, adv = 8, oxn = 0, oyn = 5, oxp = 9, oyp = 14, txn = 25, tyn = 162, txp = 34, typ = 171, } glyphs[181] = { --'µ'-- num = 181, adv = 8, oxn = -2, oyn = -5, oxp = 10, oyp = 10, txn = 49, tyn = 162, txp = 61, typ = 177, } glyphs[182] = { --'¶'-- num = 182, adv = 8, oxn = -2, oyn = -5, oxp = 11, oyp = 12, txn = 73, tyn = 162, txp = 86, typ = 179, } glyphs[183] = { --'·'-- num = 183, adv = 3, oxn = -2, oyn = 1, oxp = 6, oyp = 9, txn = 97, tyn = 162, txp = 105, typ = 170, } glyphs[184] = { --'¸'-- num = 184, adv = 8, oxn = 1, oyn = -5, oxp = 8, oyp = 4, txn = 121, tyn = 162, txp = 128, typ = 171, } glyphs[185] = { --'¹'-- num = 185, adv = 3, oxn = -2, oyn = 2, oxp = 5, oyp = 14, txn = 145, tyn = 162, txp = 152, typ = 174, } glyphs[186] = { --'º'-- num = 186, adv = 6, oxn = -2, oyn = 1, oxp = 9, oyp = 13, txn = 169, tyn = 162, txp = 180, typ = 174, } glyphs[187] = { --'»'-- num = 187, adv = 7, oxn = -2, oyn = 0, oxp = 10, oyp = 10, txn = 193, tyn = 162, txp = 205, typ = 172, } glyphs[188] = { --'¼'-- num = 188, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 217, tyn = 162, txp = 232, typ = 178, } glyphs[189] = { --'½'-- num = 189, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 241, tyn = 162, txp = 256, typ = 178, } glyphs[190] = { --'¾'-- num = 190, adv = 13, oxn = -2, oyn = -3, oxp = 16, oyp = 14, txn = 265, tyn = 162, txp = 283, typ = 179, } glyphs[191] = { --'¿'-- num = 191, adv = 9, oxn = -2, oyn = -6, oxp = 10, oyp = 11, txn = 289, tyn = 162, txp = 301, typ = 179, } glyphs[192] = { --'À'-- num = 192, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 17, txn = 313, tyn = 162, txp = 327, typ = 182, } glyphs[193] = { --'Á'-- num = 193, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 17, txn = 337, tyn = 162, txp = 351, typ = 182, } glyphs[194] = { --'Â'-- num = 194, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 17, txn = 361, tyn = 162, txp = 375, typ = 182, } glyphs[195] = { --'Ã'-- num = 195, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 16, txn = 385, tyn = 162, txp = 399, typ = 181, } glyphs[196] = { --'Ä'-- num = 196, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 16, txn = 409, tyn = 162, txp = 423, typ = 181, } glyphs[197] = { --'Å'-- num = 197, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 17, txn = 433, tyn = 162, txp = 447, typ = 182, } glyphs[198] = { --'Æ'-- num = 198, adv = 16, oxn = -3, oyn = -3, oxp = 19, oyp = 13, txn = 457, tyn = 162, txp = 479, typ = 178, } glyphs[199] = { --'Ç'-- num = 199, adv = 9, oxn = -2, oyn = -5, oxp = 12, oyp = 13, txn = 481, tyn = 162, txp = 495, typ = 180, } glyphs[200] = { --'È'-- num = 200, adv = 9, oxn = -1, oyn = -3, oxp = 11, oyp = 17, txn = 1, tyn = 185, txp = 13, typ = 205, } glyphs[201] = { --'É'-- num = 201, adv = 9, oxn = -1, oyn = -3, oxp = 11, oyp = 17, txn = 25, tyn = 185, txp = 37, typ = 205, } glyphs[202] = { --'Ê'-- num = 202, adv = 9, oxn = -1, oyn = -3, oxp = 11, oyp = 17, txn = 49, tyn = 185, txp = 61, typ = 205, } glyphs[203] = { --'Ë'-- num = 203, adv = 9, oxn = -1, oyn = -3, oxp = 11, oyp = 16, txn = 73, tyn = 185, txp = 85, typ = 204, } glyphs[204] = { --'Ì'-- num = 204, adv = 4, oxn = -1, oyn = -3, oxp = 7, oyp = 17, txn = 97, tyn = 185, txp = 105, typ = 205, } glyphs[205] = { --'Í'-- num = 205, adv = 4, oxn = -1, oyn = -3, oxp = 7, oyp = 17, txn = 121, tyn = 185, txp = 129, typ = 205, } glyphs[206] = { --'Î'-- num = 206, adv = 4, oxn = -2, oyn = -3, oxp = 8, oyp = 17, txn = 145, tyn = 185, txp = 155, typ = 205, } glyphs[207] = { --'Ï'-- num = 207, adv = 4, oxn = -2, oyn = -3, oxp = 8, oyp = 16, txn = 169, tyn = 185, txp = 179, typ = 204, } glyphs[208] = { --'Ð'-- num = 208, adv = 10, oxn = -3, oyn = -3, oxp = 12, oyp = 13, txn = 193, tyn = 185, txp = 208, typ = 201, } glyphs[209] = { --'Ñ'-- num = 209, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 16, txn = 217, tyn = 185, txp = 232, typ = 204, } glyphs[210] = { --'Ò'-- num = 210, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 17, txn = 241, tyn = 185, txp = 256, typ = 205, } glyphs[211] = { --'Ó'-- num = 211, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 17, txn = 265, tyn = 185, txp = 280, typ = 205, } glyphs[212] = { --'Ô'-- num = 212, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 17, txn = 289, tyn = 185, txp = 304, typ = 205, } glyphs[213] = { --'Õ'-- num = 213, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 16, txn = 313, tyn = 185, txp = 328, typ = 204, } glyphs[214] = { --'Ö'-- num = 214, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 16, txn = 337, tyn = 185, txp = 352, typ = 204, } glyphs[215] = { --'×'-- num = 215, adv = 7, oxn = -2, oyn = -2, oxp = 10, oyp = 9, txn = 361, tyn = 185, txp = 373, typ = 196, } glyphs[216] = { --'Ø'-- num = 216, adv = 10, oxn = -2, oyn = -4, oxp = 13, oyp = 14, txn = 385, tyn = 185, txp = 400, typ = 203, } glyphs[217] = { --'Ù'-- num = 217, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 17, txn = 409, tyn = 185, txp = 422, typ = 205, } glyphs[218] = { --'Ú'-- num = 218, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 17, txn = 433, tyn = 185, txp = 446, typ = 205, } glyphs[219] = { --'Û'-- num = 219, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 17, txn = 457, tyn = 185, txp = 470, typ = 205, } glyphs[220] = { --'Ü'-- num = 220, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 16, txn = 481, tyn = 185, txp = 494, typ = 204, } glyphs[221] = { --'Ý'-- num = 221, adv = 10, oxn = -2, oyn = -3, oxp = 13, oyp = 17, txn = 1, tyn = 208, txp = 16, typ = 228, } glyphs[222] = { --'Þ'-- num = 222, adv = 8, oxn = -1, oyn = -3, oxp = 11, oyp = 13, txn = 25, tyn = 208, txp = 37, typ = 224, } glyphs[223] = { --'ß'-- num = 223, adv = 10, oxn = -2, oyn = -4, oxp = 12, oyp = 13, txn = 49, tyn = 208, txp = 63, typ = 225, } glyphs[224] = { --'à'-- num = 224, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 14, txn = 73, tyn = 208, txp = 85, typ = 225, } glyphs[225] = { --'á'-- num = 225, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 14, txn = 97, tyn = 208, txp = 109, typ = 225, } glyphs[226] = { --'â'-- num = 226, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 14, txn = 121, tyn = 208, txp = 133, typ = 225, } glyphs[227] = { --'ã'-- num = 227, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 145, tyn = 208, txp = 157, typ = 224, } glyphs[228] = { --'ä'-- num = 228, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 169, tyn = 208, txp = 181, typ = 224, } glyphs[229] = { --'å'-- num = 229, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 14, txn = 193, tyn = 208, txp = 205, typ = 225, } glyphs[230] = { --'æ'-- num = 230, adv = 13, oxn = -2, oyn = -3, oxp = 15, oyp = 10, txn = 217, tyn = 208, txp = 234, typ = 221, } glyphs[231] = { --'ç'-- num = 231, adv = 7, oxn = -2, oyn = -5, oxp = 10, oyp = 10, txn = 241, tyn = 208, txp = 253, typ = 223, } glyphs[232] = { --'è'-- num = 232, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 14, txn = 265, tyn = 208, txp = 277, typ = 225, } glyphs[233] = { --'é'-- num = 233, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 14, txn = 289, tyn = 208, txp = 301, typ = 225, } glyphs[234] = { --'ê'-- num = 234, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 14, txn = 313, tyn = 208, txp = 325, typ = 225, } glyphs[235] = { --'ë'-- num = 235, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 337, tyn = 208, txp = 349, typ = 224, } glyphs[236] = { --'ì'-- num = 236, adv = 4, oxn = -2, oyn = -3, oxp = 6, oyp = 14, txn = 361, tyn = 208, txp = 369, typ = 225, } glyphs[237] = { --'í'-- num = 237, adv = 4, oxn = -1, oyn = -3, oxp = 7, oyp = 14, txn = 385, tyn = 208, txp = 393, typ = 225, } glyphs[238] = { --'î'-- num = 238, adv = 4, oxn = -3, oyn = -3, oxp = 7, oyp = 14, txn = 409, tyn = 208, txp = 419, typ = 225, } glyphs[239] = { --'ï'-- num = 239, adv = 4, oxn = -3, oyn = -3, oxp = 7, oyp = 13, txn = 433, tyn = 208, txp = 443, typ = 224, } glyphs[240] = { --'ð'-- num = 240, adv = 8, oxn = -2, oyn = -2, oxp = 11, oyp = 14, txn = 457, tyn = 208, txp = 470, typ = 224, } glyphs[241] = { --'ñ'-- num = 241, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 13, txn = 481, tyn = 208, txp = 492, typ = 224, } glyphs[242] = { --'ò'-- num = 242, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 14, txn = 1, tyn = 231, txp = 14, typ = 248, } glyphs[243] = { --'ó'-- num = 243, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 14, txn = 25, tyn = 231, txp = 38, typ = 248, } glyphs[244] = { --'ô'-- num = 244, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 14, txn = 49, tyn = 231, txp = 62, typ = 248, } glyphs[245] = { --'õ'-- num = 245, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 73, tyn = 231, txp = 86, typ = 247, } glyphs[246] = { --'ö'-- num = 246, adv = 8, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 97, tyn = 231, txp = 110, typ = 247, } glyphs[247] = { --'÷'-- num = 247, adv = 6, oxn = -2, oyn = -3, oxp = 9, oyp = 10, txn = 121, tyn = 231, txp = 132, typ = 244, } glyphs[248] = { --'ø'-- num = 248, adv = 8, oxn = -2, oyn = -5, oxp = 11, oyp = 11, txn = 145, tyn = 231, txp = 158, typ = 247, } glyphs[249] = { --'ù'-- num = 249, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 14, txn = 169, tyn = 231, txp = 180, typ = 248, } glyphs[250] = { --'ú'-- num = 250, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 14, txn = 193, tyn = 231, txp = 204, typ = 248, } glyphs[251] = { --'û'-- num = 251, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 14, txn = 217, tyn = 231, txp = 228, typ = 248, } glyphs[252] = { --'ü'-- num = 252, adv = 8, oxn = -1, oyn = -3, oxp = 10, oyp = 13, txn = 241, tyn = 231, txp = 252, typ = 247, } glyphs[253] = { --'ý'-- num = 253, adv = 7, oxn = -2, oyn = -6, oxp = 10, oyp = 14, txn = 265, tyn = 231, txp = 277, typ = 251, } glyphs[254] = { --'þ'-- num = 254, adv = 8, oxn = -2, oyn = -7, oxp = 11, oyp = 13, txn = 289, tyn = 231, txp = 302, typ = 251, } glyphs[255] = { --'ÿ'-- num = 255, adv = 7, oxn = -2, oyn = -6, oxp = 10, oyp = 13, txn = 313, tyn = 231, txp = 325, typ = 250, } fontSpecs.glyphs = glyphs return fontSpecs
gpl-3.0
interfaceware/iguana-web-apps
shared/test.lua
2
13295
local test = {} test.ui = require 'testui' zip = require 'zip' queue = require 'mockqueue' test.EXPECTED_DATA = "~/iguana_expected" test.IGUANA_PORT = "7500" local REDLIGHT = '<div class="status-red"></div>' local GREENLIGHT = '<div class="status-green"></div>' test.TheTrans = {} function test.cleanConfig() test.TheTrans = {} end -- Returns a handle on the database for a given translator instance function test.dbconn(TGuid) return db.connect{api=db.SQLITE, name = iguana.workingDir() .. 'data/' .. TGuid .. '.db'} end function loadChannel(ChannelGuid) local ChannelGuid = tostring(ChannelGuid) local C,R = net.http.post{url='http://localhost:' .. test.IGUANA_PORT .. '/get_channel_config', auth={password='password', username='admin'}, parameters={guid=ChannelGuid, compact=false}, live=true} if (R ~= 200) then test.error(C) end return xml.parse{data = C} end function test.getTranslatorGuid(ChannelGuid) C = loadChannel(ChannelGuid) if C.channel.use_message_filter:nodeValue() ~= 'false' then if tostring(C.channel.message_filter.translator_guid) == '00000000000000000000000000000000' then test.error('Channel ' .. tostring(C.channel.name) ..' does not have a filter with a saved milestone.') end return C.channel.message_filter.translator_guid end return false end function test.load(T) local TGuid = test.getTranslatorGuid(T) if TGuid then test.loadTrans(TGuid) return test.testTrans(TGuid) end test.error('Channel ' .. tostring(C.channel.name) .. ' does not use a translator filter so this regression test is of no use.') end function test.error(Msg) error({error=Msg}) end function test.loadExpected(Guid) local ExpectedFile = os.fs.abspath(test.EXPECTED_DATA).."/"..Guid..".json" trace(ExpectedFile) local F = io.open(ExpectedFile, "r") if (not F) then return {} end local C = F:read('*a') return json.parse{data=C} end function test.hasSample(Guid) local Cpath = iguana.workingDir() .. 'IguanaConfiguration.xml' local Cfile = io.open(Cpath, 'r') local Config = Cfile:read("*a") Cfile:close() local Details = xml.parse(Config) end function test.loadSample(Guid) local Guid = tostring(Guid) local SampleData = test.TheTrans[Guid]["samples.json"] if not SampleData then return {} end return json.parse{data=SampleData}.Samples or {} end function test.changeExpected(Guid, SDidx, NewText) local SDidx = SDidx + 1 local NewText = filter.uri.dec(NewText) trace(NewText) local ExpectedFile = os.fs.abspath(test.EXPECTED_DATA) .."/"..Guid..".json" trace(ExpectedFile) local Ex = io.open(ExpectedFile, 'r') local ExText = Ex:read('*a') local ExTree = json.parse{data=ExText} Ex:close() trace(ExTree) for Input, Tree in pairs(ExTree) do trace(Tree['i']) if Tree['i'] == SDidx then Tree['output'] = NewText Ex = io.open(ExpectedFile, 'w+') Ex:write(json.serialize{data=ExTree}) Ex:close() return {status="OK"} end end return {status="Error"} end function test.saveExpected(Guid, Actual) local ExpectedFile = os.fs.abspath(test.EXPECTED_DATA) .."/"..Guid..".json" trace(ExpectedFile) local F = io.open(ExpectedFile, 'w+') F:write(json.serialize{data=Actual}) F:close() end function test.buildExpected(TGuid) test.loadTrans(TGuid) local Input = test.loadSample(TGuid) queue.reset() for i=1, #Input do queue.setCurrent(Input[i].Message, i, Input[i].Name) originalMain(Input[i].Message) end test.saveExpected(TGuid, queue.results()) return {status="OK"} end function test.testTrans(Guid) local Input = test.loadSample(Guid) queue.reset() local Expected = test.loadExpected(Guid) queue.setExpected(Expected) for i=1, #Input do queue.setCurrent(Input[i].Message, i, Input[i].Name) originalMain(Input[i].Message) end local Actual = queue.results() return test.compare(Expected, Actual) end function test.compare(Expected, Actual) local Result = {} for Input, AOut in pairs(Actual) do Result[AOut.i] = {r = 'Y', name = AOut.name, Act = test.hideLineEnds(AOut.output)} local EOut = Expected[Input] trace(EOut) if EOut then Result[AOut.i]['Exp'] = test.hideLineEnds(EOut.output) else Result[AOut.i]['Exp'] = 'NO EXPECTED RESULT EXISTS FOR THIS TEST' end if EOut.output ~= AOut.output then Result[AOut.i]['r'] = 'N' end end return Result end local LineEndings = { ['\n'] = '\\n', ['\r'] = '\\r' } function test.hideLineEnds(TheString) TheString = string.gsub(TheString, '\\', '\\\\') for Real, Fake in pairs(LineEndings) do TheString = string.gsub(TheString, Real, Fake) TheString = string.gsub(TheString, Fake, ' <span class="line-end">' .. Fake .. '</span><br> ') end return TheString end function test.restoreLineEnds(TheString) for Real, Fake in pairs(LineEndings) do TheString = string.gsub(TheString, Real, '') TheString = string.gsub(TheString, Fake, Real) end TheString = string.gsub(TheString, '\\\\', '\\') return TheString end function test.require(ModName) local ReqScript = test.TheTrans.shared[ModName .. '.lua'] local MF = loadstring(ReqScript) return MF() end -- Checks a given translator for the presence of sample data function test.hasSample(TGuid) local db = test.dbconn(TGuid) local Res = db:query{sql='SELECT COUNT(Id) FROM Log', live = true} local Count = tonumber(Res[1]["COUNT(Id)"]:nodeValue()) return Count > 0 and Count or nil end -- Returns a list of channels with relevant details in a format DataTables likes. function test.loadChannels() local Channels = {} local Guids = {} local Summary, Retcode = net.http.post{url='http://localhost:' .. test.IGUANA_PORT .. '/monitor_query', auth={username="admin", password="password"},parameters={Compact='T'}, live=true} if Retcode == 200 then local Xml = xml.parse(Summary).IguanaStatus local ChannelIndex = 1 for i = 1, #Xml do if Xml[i]:nodeName() == 'Channel' then local ThisChannel = Xml[i] trace(ThisChannel.Guid) local TGuid = test.getTranslatorGuid(ThisChannel.Guid) trace(TGuid) if TGuid and test.hasSample(TGuid) then local Expected = test.loadExpected(TGuid) local HasExp = next(Expected) and true or false Channels[ChannelIndex] = { '<a href="#Test=' .. tostring(ThisChannel.Guid) .. '">' .. tostring(ThisChannel.Name) .. '</a>', tostring(ThisChannel.Source), tostring(ThisChannel.Destination), HasExp and GREENLIGHT or REDLIGHT, ''} Guids[ChannelIndex] = {tostring(ThisChannel.Guid), tostring(ThisChannel.Name), HasExp, tostring(TGuid)} ChannelIndex = ChannelIndex + 1 end end end else return {"Error"} end local Fields = { {['sTitle'] = 'Name', ['sType'] = 'html', ['sWidth'] = '40%'}, {['sTitle'] = 'Source', ['sType'] = 'string'}, {['sTitle'] = 'Destination', ['sType'] = 'string'}, {['sTitle'] = 'Has Test List', ['sType'] = 'string'}, {['sTitle'] = 'Test Results', ['sType'] = 'string'} } return Channels, Fields, Guids end function test.loadTrans(Guid) local Guid = tostring(Guid) local Config = net.http.post{url='localhost:' .. test.IGUANA_PORT .. '/export_project', auth={password='password', username='admin'}, parameters={guid=Guid, sample_data='true'}, live=true} local ZipFile = filter.base64.dec(Config) test.TheTrans = filter.zip.inflate(ZipFile) trace(test.TheTrans) local MainScript = test.TheTrans[Guid]["main.lua"] MainScript = MainScript:gsub("function main", "function originalMain") trace(MainScript) require = test.require local MF = loadstring(MainScript) MF() end function test.default(R) return test.ui.main(R) end local ContentTypeMap = { ['.js'] = 'application/x-javascript', ['.css'] = 'text/css' } function test.entity(Location) local Ext = Location:match('.*(%.%a+)$') local Entity = ContentTypeMap[Ext] return Entity or 'text/plain' end function test.serveRequest(Data) local R = net.http.parseRequest{data=Data} -- The UI itself if R.location == '/unit' and next(R.get_params) == nil then local Body = test.ui.main() net.http.respond{body=Body, entity_type="text/html"} return end -- UI asset requests local Resource = test.ui.ResourceTable[R.location] if (Resource) then local Body = test.ui.template(R.location, Resource) net.http.respond{body=Body, entity_type=test.entity(R.location)} return end -- Channel details if R.location == '/unit/channels' then local Channels = {} Channels.aaData, Channels.aoColumns, Channels.Guids = test.loadChannels() local Out = json.serialize{data=Channels} net.http.respond{body=Out, entity_type='text/json'} return end -- Build expected result set if R.location == '/unit/build' then local Channel = R.get_params.channel if (not Channel) then net.http.respond{body='{error="Please supply channel=guid in URL"}', entity_type='text/json'} return end local Result = test.buildExpected(Channel) net.http.respond{body = json.serialize{data = Result}, entity_type='text/json'} return end -- Change a single expected result if R.location == '/unit/edit_result' then local Translator = R.post_params.t_guid if (not Translator) then net.http.respond{body='{error="Please supply t_guid in URL"}', entity_type='text/json'} return end local Result = test.changeExpected(Translator, R.post_params.sd_idx, test.restoreLineEnds(R.post_params.txt)) net.http.respond{body = json.serialize{data = Result}, entity_type='text/json'} return end -- Run tests on a specific channel local Channel = R.get_params.channel local ChannelName = R.get_params.name or '' if (not Channel) then net.http.respond{body='{error="Please supply channel=guid in URL"}', entity_type='text/json'} return else -- Actully run the tests local Success, Results if iguana.isTest() then Results = test.load(Channel) else Success, Results = pcall(test.load, Channel) if (not Success) then if type(Results) == 'string' then Results = {error=Results} end end end -- Munge the result set into a DataTables structure local Cols = { {['sTitle'] = 'Test', ['sType'] = 'numeric'}, {['sTitle'] = 'Name', ['sType'] = 'string'}, {['sTitle'] = 'Result', ['sType'] = 'string'}, {['sTitle'] = 'Inspect', ['sType'] = 'html'}, } local Rows = {} for i = 1, #Results do local Light = Results[i]['r'] == 'Y' and GREENLIGHT or REDLIGHT local Link = '<a href="#Inspect=' .. i .. '&Test=' .. Channel .. '">Inspect</a>' Results[i]['EditLink'] = '<a target="_blank" href="http://localhost:' .. test.IGUANA_PORT .. '/mapper/#User=admin&ComponentName=Filter&ChannelName=' .. ChannelName .. '&ChannelGuid=' .. tostring(test.getTranslatorGuid(Channel)) .. '&ComponentType=Filter&Page=OpenEditor&Module=main&SDindex=' .. i .. '">See this sample data in the Iguana Translator</a>' Rows[i] = {i, Results[i]['name'], Light, Link} end local FinalResult = {['aoColumns'] = Cols, ['aaData'] = Rows, ['Res'] = Results, ['aaSorting'] = {{2, 'desc'}}, ['bFilter'] = false, ['bInfo'] = false, ['bPaginate'] = false} net.http.respond{body=json.serialize{data=FinalResult}, entity_type='text/json'} return end end -- This is a helper, used for cutting a path function string:split(Delimiter) local Results = {} local Index = 1 local SplitStart, SplitEnd = string.find(self, Delimiter, Index) while SplitStart do table.insert(Results, string.sub(self, Index, SplitStart - 1) ) Index = SplitEnd + 1 SplitStart, SplitEnd = string.find(self, Delimiter, Index) end table.insert(Results, string.sub(self, Index) ) return Results end function test.findVmd(Node, Path) local Pieces = Path:split('/') for i = 1, #Pieces do trace(Pieces[i]) Node = Node[Pieces[i]] end return Node end local originalHl7Parse = hl7.parse function hl7.parse(T) T.vmd_definition = test.findVmd(test.TheTrans.other, T.vmd) return originalHl7Parse(T) end local originalHl7Message = hl7.message function hl7.message(T) T.vmd_definition = test.findVmd(test.TheTrans.other, T.vmd) return originalHl7Message(T) end return test
mit
ariakabiryan/tnt_aria_bot
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
javarange/mongrel2
examples/bbs/ui.lua
96
2026
local coroutine = coroutine module 'ui' local SCREENS = { ['welcome'] = [[ __ __ ____ ____ ____ ____ | \/ |___ \| __ )| __ ) ___| | |\/| | __) | _ \| _ \___ \ | | | |/ __/| |_) | |_) |__) | |_| |_|_____|____/|____/____/ Welcome to the Mongrel2 BBS. ]], ['name'] = "What's your name?", ['welcome_newbie'] = 'Awesome! Welcome to our little BBS. Have fun.\n', ['password'] = "What's your password?", ['motd'] = [[ MOTD: There's not much going on here currently, and we're mostly just trying out this whole Lua with Mongrel2 thing. If you like it then help out by leaving a message and trying to break it. -- Zed Enter to continue.]], ['menu'] = [[ ---(((MAIN MENU))--- 1. Leave a message. 2. Read messages left. 3. Send to someone else. 4. Read messages to you. Q. Quit the BBS. ]], ['bye'] = "Alright, see ya later.", ['leave_msg'] = "Enter your message, up to 20 lines, then enter . by itself to end it:\n", ['read_msg'] = "These are left by different users:\n", ['menu_error'] = "That's not a valid menu option.", ['posted'] = "Message posted.", ['new_user'] = "Looks like you're new here. Type your password again and make it match.", ['bad_pass'] = "Right, I can't let you in unless you get the user and password right. Bye.", ['repeat_pass'] = "Password doesn't matched what you typed already, try again.", ['error'] = "We had an error, try again later.", } function display(conn, request, data) conn:reply_json(request, {type = 'screen', msg = data}) end function ask(conn, request, data, pchar) conn:reply_json(request, {type = 'prompt', msg = data, pchar = pchar}) return coroutine.yield() end function screen(conn, request, name) display(conn, request, SCREENS[name]) end function prompt(conn, request, name) return ask(conn, request, SCREENS[name], '> ') end function exit(conn, request, name) conn:reply_json(request, {type = 'exit', msg = SCREENS[name]}) end
bsd-3-clause
GarfieldJiang/UGFWithToLua
Assets/ToLua/ToLua/Lua/socket/tp.lua
51
3766
----------------------------------------------------------------------------- -- Unified SMTP/FTP subsystem -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local string = require("string") local socket = require("socket") local ltn12 = require("ltn12") socket.tp = {} local _M = socket.tp ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- _M.TIMEOUT = 60 ----------------------------------------------------------------------------- -- Implementation ----------------------------------------------------------------------------- -- gets server reply (works for SMTP and FTP) local function get_reply(c) local code, current, sep local line, err = c:receive() local reply = line if err then return nil, err end code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) if not code then return nil, "invalid server reply" end if sep == "-" then -- reply is multiline repeat line, err = c:receive() if err then return nil, err end current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) reply = reply .. "\n" .. line -- reply ends with same code until code == current and sep == " " end return code, reply end -- metatable for sock object local metat = { __index = {} } function metat.__index:getpeername() return self.c:getpeername() end function metat.__index:getsockname() return self.c:getpeername() end function metat.__index:check(ok) local code, reply = get_reply(self.c) if not code then return nil, reply end if base.type(ok) ~= "function" then if base.type(ok) == "table" then for i, v in base.ipairs(ok) do if string.find(code, v) then return base.tonumber(code), reply end end return nil, reply else if string.find(code, ok) then return base.tonumber(code), reply else return nil, reply end end else return ok(base.tonumber(code), reply) end end function metat.__index:command(cmd, arg) cmd = string.upper(cmd) if arg then return self.c:send(cmd .. " " .. arg.. "\r\n") else return self.c:send(cmd .. "\r\n") end end function metat.__index:sink(snk, pat) local chunk, err = self.c:receive(pat) return snk(chunk, err) end function metat.__index:send(data) return self.c:send(data) end function metat.__index:receive(pat) return self.c:receive(pat) end function metat.__index:getfd() return self.c:getfd() end function metat.__index:dirty() return self.c:dirty() end function metat.__index:getcontrol() return self.c end function metat.__index:source(source, step) local sink = socket.sink("keep-open", self.c) local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) return ret, err end -- closes the underlying c function metat.__index:close() self.c:close() return 1 end -- connect with server and return c object function _M.connect(host, port, timeout, create) local c, e = (create or socket.tcp)() if not c then return nil, e end c:settimeout(timeout or _M.TIMEOUT) local r, e = c:connect(host, port) if not r then c:close() return nil, e end return base.setmetatable({c = c}, metat) end return _M
mit
bigdogmat/wire
lua/entities/gmod_wire_expression2/core/complex.lua
17
11243
/******************************************************************************\ Complex numbers support \******************************************************************************/ -- faster access to some math library functions local abs = math.abs local Round = math.Round local sqrt = math.sqrt local exp = math.exp local log = math.log local sin = math.sin local cos = math.cos local sinh = math.sinh local cosh = math.cosh local acos = math.acos local atan2 = math.atan2 local function format(value) local dbginfo if abs(value[1]) < delta then if abs(value[2]) < delta then dbginfo = "0" else dbginfo = Round(value[2]*1000)/1000 .. "i" end else if value[2] > delta then dbginfo = Round(value[1]*1000)/1000 .. "+" .. Round(value[2]*1000)/1000 .. "i" elseif abs(value[2]) <= delta then dbginfo = Round(value[1]*1000)/1000 elseif value[2] < -delta then dbginfo = Round(value[1]*1000)/1000 .. Round(value[2]*1000)/1000 .. "i" end end return dbginfo end WireLib.registerDebuggerFormat("COMPLEX", format) /******************************************************************************/ __e2setcost(2) registerType("complex", "c", { 0, 0 }, function(self, input) return { input[1], input[2] } end, nil, function(retval) if !istable(retval) then error("Return value is not a table, but a "..type(retval).."!",0) end if #retval ~= 2 then error("Return value does not have exactly 2 entries!",0) end end, function(v) return !istable(v) or #v ~= 2 end ) /******************************************************************************/ __e2setcost(4) local function cexp(x,y) return {exp(x)*cos(y), exp(x)*sin(y)} end local function clog(x,y) local r,i,l l = x*x+y*y if l < delta then return {-1e+100, 0} end r = log(sqrt(l)) local c,s c = x/sqrt(l) i = acos(c) if y<0 then i = -i end return {r, i} end local function cdiv(a,b) local l=b[1]*b[1]+b[2]*b[2] return {(a[1]*b[1]+a[2]*b[2])/l, (a[2]*b[1]-a[1]*b[2])/l} end /******************************************************************************/ __e2setcost(2) registerOperator("ass", "c", "c", function(self, args) local lhs, op2, scope = args[2], args[3], args[4] local rhs = op2[1](self, op2) self.Scopes[scope][lhs] = rhs self.Scopes[scope].vclk[lhs] = true return rhs end) e2function number operator_is(complex z) if (z[1]==0) && (z[2]==0) then return 0 else return 1 end end e2function number operator==(complex lhs, complex rhs) if abs(lhs[1]-rhs[1])<=delta && abs(lhs[2]-rhs[2])<=delta then return 1 else return 0 end end e2function number operator==(complex lhs, number rhs) if abs(lhs[1]-rhs)<=delta && abs(lhs[2])<=delta then return 1 else return 0 end end e2function number operator==(number lhs, complex rhs) if abs(lhs-rhs[1])<=delta && abs(rhs[2])<=delta then return 1 else return 0 end end e2function number operator!=(complex lhs, complex rhs) if abs(lhs[1]-rhs[1])>delta || abs(lhs[2]-rhs[2])>delta then return 1 else return 0 end end e2function number operator!=(complex lhs, number rhs) if abs(lhs[1]-rhs)>delta || abs(lhs[2])>delta then return 1 else return 0 end end e2function number operator!=(number lhs, complex rhs) if abs(lhs-rhs[1])>delta || abs(rhs[2])>delta then return 1 else return 0 end end /******************************************************************************/ e2function complex operator_neg(complex z) return {-z[1], -z[2]} end e2function complex operator+(complex lhs, complex rhs) return {lhs[1]+rhs[1], lhs[2]+rhs[2]} end e2function complex operator+(number lhs, complex rhs) return {lhs+rhs[1], rhs[2]} end e2function complex operator+(complex lhs, number rhs) return {lhs[1]+rhs, lhs[2]} end e2function complex operator-(complex lhs, complex rhs) return {lhs[1]-rhs[1], lhs[2]-rhs[2]} end e2function complex operator-(number lhs, complex rhs) return {lhs-rhs[1], -rhs[2]} end e2function complex operator-(complex lhs, number rhs) return {lhs[1]-rhs, lhs[2]} end e2function complex operator*(complex lhs, complex rhs) return {lhs[1]*rhs[1]-lhs[2]*rhs[2], lhs[2]*rhs[1]+lhs[1]*rhs[2]} end e2function complex operator*(number lhs, complex rhs) return {lhs*rhs[1], lhs*rhs[2]} end e2function complex operator*(complex lhs, number rhs) return {lhs[1]*rhs, lhs[2]*rhs} end e2function complex operator/(complex lhs, complex rhs) local z = rhs[1]*rhs[1] + rhs[2]*rhs[2] return {(lhs[1]*rhs[1]+lhs[2]*rhs[2])/z, (lhs[2]*rhs[1]-lhs[1]*rhs[2])/z} end e2function complex operator/(number lhs, complex rhs) local z = rhs[1]*rhs[1] + rhs[2]*rhs[2] return {lhs*rhs[1]/z, -lhs*rhs[2]/z} end e2function complex operator/(complex lhs, number rhs) return {lhs[1]/rhs, lhs[2]/rhs} end e2function complex operator^(complex lhs, complex rhs) local l = clog(lhs[1], lhs[2]) local e = {rhs[1]*l[1] - rhs[2]*l[2], rhs[1]*l[2] + rhs[2]*l[1]} return cexp(e[1], e[2]) end e2function complex operator^(complex lhs, number rhs) local l = clog(lhs[1], lhs[2]) return cexp(rhs*l[1], rhs*l[2]) end /******************************** constructors ********************************/ --- Returns complex zero e2function complex comp() return {0, 0} end --- Converts a real number to complex (returns complex number with real part <a> and imaginary part 0) e2function complex comp(a) return {a, 0} end --- Returns <a>+<b>*i e2function complex comp(a, b) return {a, b} end --- Returns the imaginary unit i e2function complex i() return {0, 1} end --- Returns <b>*i e2function complex i(b) return {0, b} end /****************************** helper functions ******************************/ --- Returns the absolute value of <z> e2function number abs(complex z) return sqrt(z[1]*z[1] + z[2]*z[2]) end --- Returns the argument of <z> e2function number arg(complex z) local l = z[1]*z[1]+z[2]*z[2] if l==0 then return 0 end local c = z[1]/sqrt(l) local p = acos(c) if z[2]<0 then p = -p end return p end --- Returns the conjugate of <z> e2function complex conj(complex z) return {z[1], -z[2]} end --- Returns the real part of <z> e2function number real(complex z) return z[1] end --- Returns the imaginary part of <z> e2function number imag(complex z) return z[2] end /***************************** exp and logarithms *****************************/ --- Raises Euler's constant e to the power of <z> e2function complex exp(complex z) return cexp(z[1], z[2]) end --- Calculates the natural logarithm of <z> e2function complex log(complex z) return clog(z[1], z[2]) end --- Calculates the logarithm of <z> to a complex base <base> e2function complex log(complex base, complex z) return cdiv(clog(z),clog(base)) end --- Calculates the logarithm of <z> to a real base <base> e2function complex log(number base, complex z) local l=clog(z) return {l[1]/log(base), l[2]/log(base)} end --- Calculates the logarithm of <z> to base 2 e2function complex log2(complex z) local l=clog(z) return {l[1]/log(2), l[2]/log(2)} end --- Calculates the logarithm of <z> to base 10 e2function complex log10(complex z) local l=clog(z) return {l[1]/log(10), l[2]/log(10)} end /******************************************************************************/ --- Calculates the square root of <z> e2function complex sqrt(complex z) local l = clog(z[1], z[2]) return cexp(0.5*l[1], 0.5*l[2]) end --- Calculates the complex square root of the real number <n> e2function complex csqrt(n) if n<0 then return {0, sqrt(-n)} else return {sqrt(n), 0} end end /******************* trigonometric and hyperbolic functions *******************/ __e2setcost(3) --- Calculates the sine of <z> e2function complex sin(complex z) return {sin(z[1])*cosh(z[2]), sinh(z[2])*cos(z[1])} end --- Calculates the cosine of <z> e2function complex cos(complex z) return {cos(z[1])*cosh(z[2]), -sin(z[1])*sinh(z[2])} end --- Calculates the hyperbolic sine of <z> e2function complex sinh(complex z) return {sinh(z[1])*cos(z[2]), sin(z[2])*cosh(z[1])} end --- Calculates the hyperbolic cosine of <z> e2function complex cosh(complex z) return {cosh(z[1])*cos(z[2]), sinh(z[1])*sin(z[2])} end --- Calculates the tangent of <z> e2function complex tan(complex z) local s,c s = {sin(z[1])*cosh(z[2]), sinh(z[2])*cos(z[1])} c = {cos(z[1])*cosh(z[2]), -sin(z[1])*sinh(z[2])} return cdiv(s,c) end --- Calculates the cotangent of <z> e2function complex cot(complex z) local s,c s = {sin(z[1])*cosh(z[2]), sinh(z[2])*cos(z[1])} c = {cos(z[1])*cosh(z[2]), -sin(z[1])*sinh(z[2])} return cdiv(c,s) end __e2setcost(5) --- Calculates the inverse sine of <z> e2function complex asin(complex z) local log1mz2 = clog(1-z[1]*z[1]+z[2]*z[2], 2*z[1]*z[2]) local rt = cexp(log1mz2[1]*0.5,log1mz2[2]*0.5) local flog = clog(rt[1]-z[2], z[1]+rt[2]) return {flog[2], -flog[1]} end --- Calculates the inverse cosine of <z> e2function complex acos(complex z) local logz2m1 = clog(z[1]*z[1]-z[2]*z[2]-1, 2*z[1]*z[2]) local rt = cexp(logz2m1[1]*0.5,logz2m1[2]*0.5) local flog = clog(z[1]+rt[1], z[2]+rt[2]) return {flog[2], -flog[1]} end --- Calculates the inverse tangent of <z> e2function complex atan(complex z) local frac = cdiv({-z[1],1-z[2]},{z[1],1+z[2]}) local logfrac = clog(frac[1], frac[2]) local rt = cexp(logfrac[1]*0.5,logfrac[2]*0.5) local flog = clog(rt[1], rt[2]) return {flog[2], -flog[1]} end __e2setcost(2) --- Calculates the principle value of <z> e2function number atan2(complex z) return atan2(z[2], z[1]) end -- ******************** hyperbolic functions *********************** -- __e2setcost(4) --- Calculates the hyperbolic tangent of <z> e2function complex tanh(complex z) local s,c s = {sinh(z[1])*cos(z[2]), sin(z[2])*cosh(z[1])} c = {cosh(z[1])*cos(z[2]), sinh(z[1])*sin(z[2])} return cdiv(s,c) end --- Calculates the hyperbolic cotangent of <z> e2function complex coth(complex z) local s,c s = {sinh(z[1])*cos(z[2]), sin(z[2])*cosh(z[1])} c = {cosh(z[1])*cos(z[2]), sinh(z[1])*sin(z[2])} return cdiv(c,s) end __e2setcost(3) --- Calculates the secant of <z> e2function complex sec(complex z) local c c = {cos(z[1])*cosh(z[2]), -sin(z[1])*sinh(z[2])} return cdiv({1,0},c) end --- Calculates the cosecant of <z> e2function complex csc(complex z) local s s = {sin(z[1])*cosh(z[2]), sinh(z[2])*cos(z[1])} return cdiv({1,0},s) end --- Calculates the hyperbolic secant of <z> e2function complex sech(complex z) local c c = {cosh(z[1])*cos(z[2]), sinh(z[1])*sin(z[2])} return cdiv({1,0},c) end --- Calculates the hyperbolic cosecant of <z> e2function complex csch(complex z) local s s = {sinh(z[1])*cos(z[2]), sin(z[2])*cosh(z[1])} return cdiv({1,0},s) end /******************************************************************************/ __e2setcost(15) --- Formats <z> as a string. e2function string toString(complex z) return format(z) end e2function string complex:toString() return format(this) end
apache-2.0
ioiasff/qrt
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
TimVonsee/hammerspoon
extensions/milight/init.lua
5
4490
--- === hs.milight === --- --- Simple controls for the MiLight LED WiFi bridge (also known as LimitlessLED and EasyBulb) local milight = require "hs.milight.internal" milight.cmd = milight._cacheCommands() local milightObject = hs.getObjectMetatable("hs.milight") --- hs.milight.minBrightness --- Constant --- Specifies the minimum brightness value that can be used. Defaults to 0 milight.minBrightness = 0 -- --- hs.milight.maxBrightness --- Constant --- Specifies the maximum brightness value that can be used. Defaults to 25 milight.maxBrightness = 25 -- Internal helper to set brightness function brightnessHelper(bridge, zonecmd, value) if (bridge:send(milight.cmd[zonecmd])) then if (value < milight.minBrightness) then value = milight.minBrightness elseif (value > milight.maxBrightness) then value = milight.maxBrightness end value = value + 2 -- bridge accepts values between 2 and 27 result = bridge:send(milight.cmd["brightness"], value) if (result) then return value - 2 else return -1 end else return -1 end end -- Internal helper to set color function colorHelper(bridge, zonecmd, value) if (bridge:send(milight.cmd[zonecmd])) then if (value < 0) then value = 0 elseif (value > 255) then value = 255 end return bridge:send(milight.cmd["rgbw"], value) else return false end end -- Internal helper to map an integer and a string to a zone command key function zone2cmdkey(zone, cmdType) local zoneString if (zone == 0) then zoneString = "all_" else zoneString = "zone"..zone.."_" end return zoneString..cmdType end --- hs.milight:zoneOff(zone) -> bool --- Method --- Turns off the specified zone --- --- Parameters: --- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four --- --- Returns: --- * True if the command was sent correctly, otherwise false function milightObject:zoneOff(zone) return self:send(milight.cmd[zone2cmdkey(zone, "off")]) end --- hs.milight:zoneOn(zone) -> bool --- Method --- Turns on the specified zone --- --- Parameters: --- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four --- --- Returns: --- * True if the command was sent correctly, otherwise false function milightObject:zoneOn(zone) return self:send(milight.cmd[zone2cmdkey(zone, "on")]) end --- hs.milight:disco() -> bool --- Method --- Cycles through the disco modes --- --- Parameters: --- * None --- --- Returns: --- * True if the command was sent correctly, otherwise false function milightObject:discoCycle(zone) if (self:zoneOn(zone)) then return self:send(milight.cmd["disco"]) else return false end end --- hs.milight:zoneBrightness(zone, value) -> integer --- Method --- Sets brightness for the specified zone --- --- Parameters: --- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four --- * value - A number containing the brightness level to set, between `hs.milight.minBrightness` and `hs.milight.maxBrightness` --- --- Returns: --- * A number containing the value that was sent to the WiFi bridge, or -1 if an error occurred function milightObject:zoneBrightness(zone, value) return brightnessHelper(self, zone2cmdkey(zone, "on"), value) end --- hs.milight:zoneColor(zone, value) -> bool --- Method --- Sets RGB color for the specified zone --- --- Parameters: --- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four --- * value - A number containing an RGB color value between 0 and 255 --- --- Returns: --- * True if the command was sent correctly, otherwise false function milightObject:zoneColor(zone, value) return colorHelper(self, zone2cmdkey(zone, "on"), value) end --- hs.milight:zoneWhite(zone) -> bool --- Method --- Sets the specified zone to white --- --- Parameters: --- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four --- --- Returns: --- * True if the command was sent correctly, otherwise false function milightObject:zoneWhite(zone) if (self:zoneOn(zone)) then return self:send(milight.cmd[zone2cmdkey(zone, "white")]) else return false end end return milight
mit
MonkeyFirst/DisabledBoneSlerpWithShadowedAnimation
bin/Data/LuaScripts/18_CharacterDemo.lua
3
20531
-- Moving character example. -- This sample demonstrates: -- - Controlling a humanoid character through physics -- - Driving animations using the AnimationController component -- - Manual control of a bone scene node -- - Implementing 1st and 3rd person cameras, using raycasts to avoid the 3rd person camera clipping into scenery -- - Saving and loading the variables of a script object -- - Using touch inputs/gyroscope for iOS/Android (implemented through an external file) require "LuaScripts/Utilities/Sample" require "LuaScripts/Utilities/Touch" -- Variables used by external file are made global in order to be accessed CTRL_FORWARD = 1 CTRL_BACK = 2 CTRL_LEFT = 4 CTRL_RIGHT = 8 local CTRL_JUMP = 16 local MOVE_FORCE = 0.8 local INAIR_MOVE_FORCE = 0.02 local BRAKE_FORCE = 0.2 local JUMP_FORCE = 7.0 local YAW_SENSITIVITY = 0.1 local INAIR_THRESHOLD_TIME = 0.1 firstPerson = false -- First person camera flag local characterNode = nil function Start() -- Execute the common startup for samples SampleStart() -- Create static scene content CreateScene() -- Create the controllable character CreateCharacter() -- Create the UI content CreateInstructions() -- Subscribe to necessary events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create scene subsystem components scene_:CreateComponent("Octree") scene_:CreateComponent("PhysicsWorld") -- Create camera and define viewport. Camera does not necessarily have to belong to the scene cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 renderer:SetViewport(0, Viewport:new(scene_, camera)) -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) -- Create the floor object local floorNode = scene_:CreateChild("Floor") floorNode.position = Vector3(0.0, -0.5, 0.0) floorNode.scale = Vector3(200.0, 1.0, 200.0) local object = floorNode:CreateComponent("StaticModel") object.model = cache:GetResource("Model", "Models/Box.mdl") object.material = cache:GetResource("Material", "Materials/Stone.xml") local body = floorNode:CreateComponent("RigidBody") -- Use collision layer bit 2 to mark world scenery. This is what we will raycast against to prevent camera from going -- inside geometry body.collisionLayer = 2 local shape = floorNode:CreateComponent("CollisionShape") shape:SetBox(Vector3(1.0, 1.0, 1.0)) -- Create mushrooms of varying sizes local NUM_MUSHROOMS = 60 for i = 1, NUM_MUSHROOMS do local objectNode = scene_:CreateChild("Mushroom") objectNode.position = Vector3(Random(180.0) - 90.0, 0.0, Random(180.0) - 90.0) objectNode.rotation = Quaternion(0.0, Random(360.0), 0.0) objectNode:SetScale(2.0 + Random(5.0)) local object = objectNode:CreateComponent("StaticModel") object.model = cache:GetResource("Model", "Models/Mushroom.mdl") object.material = cache:GetResource("Material", "Materials/Mushroom.xml") object.castShadows = true local body = objectNode:CreateComponent("RigidBody") body.collisionLayer = 2 local shape = objectNode:CreateComponent("CollisionShape") shape:SetTriangleMesh(object.model, 0) end -- Create movable boxes. Let them fall from the sky at first local NUM_BOXES = 100 for i = 1, NUM_BOXES do local scale = Random(2.0) + 0.5 local objectNode = scene_:CreateChild("Box") objectNode.position = Vector3(Random(180.0) - 90.0, Random(10.0) + 10.0, Random(180.0) - 90.0) objectNode.rotation = Quaternion(Random(360.0), Random(360.0), Random(360.0)) objectNode:SetScale(scale) local object = objectNode:CreateComponent("StaticModel") object.model = cache:GetResource("Model", "Models/Box.mdl") object.material = cache:GetResource("Material", "Materials/Stone.xml") object.castShadows = true local body = objectNode:CreateComponent("RigidBody") body.collisionLayer = 2 -- Bigger boxes will be heavier and harder to move body.mass = scale * 2.0 local shape = objectNode:CreateComponent("CollisionShape") shape:SetBox(Vector3(1.0, 1.0, 1.0)) end end function CreateCharacter() characterNode = scene_:CreateChild("Jack") characterNode.position = Vector3(0.0, 1.0, 0.0) -- Create the rendering component + animation controller local object = characterNode:CreateComponent("AnimatedModel") object.model = cache:GetResource("Model", "Models/Jack.mdl") object.material = cache:GetResource("Material", "Materials/Jack.xml") object.castShadows = true characterNode:CreateComponent("AnimationController") -- Set the head bone for manual control object.skeleton:GetBone("Bip01_Head").animated = false -- Create rigidbody, and set non-zero mass so that the body becomes dynamic local body = characterNode:CreateComponent("RigidBody") body.collisionLayer = 1 body.mass = 1.0 -- Set zero angular factor so that physics doesn't turn the character on its own. -- Instead we will control the character yaw manually body.angularFactor = Vector3(0.0, 0.0, 0.0) -- Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly body.collisionEventMode = COLLISION_ALWAYS -- Set a capsule shape for collision local shape = characterNode:CreateComponent("CollisionShape") shape:SetCapsule(0.7, 1.8, Vector3(0.0, 0.9, 0.0)) -- Create the character logic object, which takes care of steering the rigidbody characterNode:CreateScriptObject("Character") end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText( "Use WASD keys and mouse to move\n".. "Space to jump, F to toggle 1st/3rd person\n".. "F5 to save scene, F7 to load") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SubscribeToEvents() -- Subscribe to Update event for setting the character controls before physics simulation SubscribeToEvent("Update", "HandleUpdate") -- Subscribe to PostUpdate event for updating the camera position after physics simulation SubscribeToEvent("PostUpdate", "HandlePostUpdate") -- Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample UnsubscribeFromEvent("SceneUpdate") end function HandleUpdate(eventType, eventData) if characterNode == nil then return end local character = characterNode:GetScriptObject() if character == nil then return end -- Clear previous controls character.controls:Set(CTRL_FORWARD + CTRL_BACK + CTRL_LEFT + CTRL_RIGHT + CTRL_JUMP, false) -- Update controls using touch utility if touchEnabled then UpdateTouches(character.controls) end -- Update controls using keys if ui.focusElement == nil then if not touchEnabled or not useGyroscope then if input:GetKeyDown(KEY_W) then character.controls:Set(CTRL_FORWARD, true) end if input:GetKeyDown(KEY_S) then character.controls:Set(CTRL_BACK, true) end if input:GetKeyDown(KEY_A) then character.controls:Set(CTRL_LEFT, true) end if input:GetKeyDown(KEY_D) then character.controls:Set(CTRL_RIGHT, true) end end if input:GetKeyDown(KEY_SPACE) then character.controls:Set(CTRL_JUMP, true) end -- Add character yaw & pitch from the mouse motion or touch input if touchEnabled then for i=0, input.numTouches - 1 do local state = input:GetTouch(i) if not state.touchedElement then -- Touch on empty space local camera = cameraNode:GetComponent("Camera") if not camera then return end character.controls.yaw = character.controls.yaw + TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.x character.controls.pitch = character.controls.pitch + TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.y end end else character.controls.yaw = character.controls.yaw + input.mouseMoveX * YAW_SENSITIVITY character.controls.pitch = character.controls.pitch + input.mouseMoveY * YAW_SENSITIVITY end -- Limit pitch character.controls.pitch = Clamp(character.controls.pitch, -80.0, 80.0) -- Set rotation already here so that it's updated every rendering frame instead of every physics frame characterNode.rotation = Quaternion(character.controls.yaw, Vector3(0.0, 1.0, 0.0)) -- Switch between 1st and 3rd person if input:GetKeyPress(KEY_F) then firstPerson = not firstPerson end -- Turn on/off gyroscope on mobile platform if input:GetKeyPress(KEY_G) then useGyroscope = not useGyroscope end -- Check for loading / saving the scene if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/CharacterDemo.xml") end if input:GetKeyPress(KEY_F7) then scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/CharacterDemo.xml") -- After loading we have to reacquire the character scene node, as it has been recreated -- Simply find by name as there's only one of them characterNode = scene_:GetChild("Jack", true) if characterNode == nil then return end end end end function HandlePostUpdate(eventType, eventData) if characterNode == nil then return end local character = characterNode:GetScriptObject() if character == nil then return end -- Get camera lookat dir from character yaw + pitch local rot = characterNode.rotation local dir = rot * Quaternion(character.controls.pitch, Vector3(1.0, 0.0, 0.0)) -- Turn head to camera pitch, but limit to avoid unnatural animation local headNode = characterNode:GetChild("Bip01_Head", true) local limitPitch = Clamp(character.controls.pitch, -45.0, 45.0) local headDir = rot * Quaternion(limitPitch, Vector3(1.0, 0.0, 0.0)) -- This could be expanded to look at an arbitrary target, now just look at a point in front local headWorldTarget = headNode.worldPosition + headDir * Vector3(0.0, 0.0, 1.0) headNode:LookAt(headWorldTarget, Vector3(0.0, 1.0, 0.0)) -- Correct head orientation because LookAt assumes Z = forward, but the bone has been authored differently (Y = forward) headNode:Rotate(Quaternion(0.0, 90.0, 90.0)) if firstPerson then -- First person camera: position to the head bone + offset slightly forward & up cameraNode.position = headNode.worldPosition + rot * Vector3(0.0, 0.15, 0.2) cameraNode.rotation = dir else -- Third person camera: position behind the character local aimPoint = characterNode.position + rot * Vector3(0.0, 1.7, 0.0) -- You can modify x Vector3 value to translate the fixed character position (indicative range[-2;2]) -- Collide camera ray with static physics objects (layer bitmask 2) to ensure we see the character properly local rayDir = dir * Vector3(0.0, 0.0, -1.0) -- For indoor scenes you can use dir * Vector3(0.0, 0.0, -0.5) to prevent camera from crossing the walls local rayDistance = cameraDistance local result = scene_:GetComponent("PhysicsWorld"):RaycastSingle(Ray(aimPoint, rayDir), rayDistance, 2) if result.body ~= nil then rayDistance = Min(rayDistance, result.distance) end rayDistance = Clamp(rayDistance, CAMERA_MIN_DIST, cameraDistance) cameraNode.position = aimPoint + rayDir * rayDistance cameraNode.rotation = dir end end -- Character script object class Character = ScriptObject() function Character:Start() -- Character controls. self.controls = Controls() -- Grounded flag for movement. self.onGround = false -- Jump flag. self.okToJump = true -- In air timer. Due to possible physics inaccuracy, character can be off ground for max. 1/10 second and still be allowed to move. self.inAirTimer = 0.0 self:SubscribeToEvent(self.node, "NodeCollision", "Character:HandleNodeCollision") end function Character:Load(deserializer) self.controls.yaw = deserializer:ReadFloat() self.controls.pitch = deserializer:ReadFloat() end function Character:Save(serializer) serializer:WriteFloat(self.controls.yaw) serializer:WriteFloat(self.controls.pitch) end function Character:HandleNodeCollision(eventType, eventData) local contacts = eventData["Contacts"]:GetBuffer() while not contacts.eof do local contactPosition = contacts:ReadVector3() local contactNormal = contacts:ReadVector3() local contactDistance = contacts:ReadFloat() local contactImpulse = contacts:ReadFloat() -- If contact is below node center and mostly vertical, assume it's a ground contact if contactPosition.y < self.node.position.y + 1.0 then local level = Abs(contactNormal.y) if level > 0.75 then self.onGround = true end end end end function Character:FixedUpdate(timeStep) -- Could cache the components for faster access instead of finding them each frame local body = self.node:GetComponent("RigidBody") local animCtrl = self.node:GetComponent("AnimationController") -- Update the in air timer. Reset if grounded if not self.onGround then self.inAirTimer = self.inAirTimer + timeStep else self.inAirTimer = 0.0 end -- When character has been in air less than 1/10 second, it's still interpreted as being on ground local softGrounded = self.inAirTimer < INAIR_THRESHOLD_TIME -- Update movement & animation local rot = self.node.rotation local moveDir = Vector3(0.0, 0.0, 0.0) local velocity = body.linearVelocity -- Velocity on the XZ plane local planeVelocity = Vector3(velocity.x, 0.0, velocity.z) if self.controls:IsDown(CTRL_FORWARD) then moveDir = moveDir + Vector3(0.0, 0.0, 1.0) end if self.controls:IsDown(CTRL_BACK) then moveDir = moveDir + Vector3(0.0, 0.0, -1.0) end if self.controls:IsDown(CTRL_LEFT) then moveDir = moveDir + Vector3(-1.0, 0.0, 0.0) end if self.controls:IsDown(CTRL_RIGHT) then moveDir = moveDir + Vector3(1.0, 0.0, 0.0) end -- Normalize move vector so that diagonal strafing is not faster if moveDir:LengthSquared() > 0.0 then moveDir:Normalize() end -- If in air, allow control, but slower than when on ground if softGrounded then body:ApplyImpulse(rot * moveDir * MOVE_FORCE) else body:ApplyImpulse(rot * moveDir * INAIR_MOVE_FORCE) end if softGrounded then -- When on ground, apply a braking force to limit maximum ground velocity local brakeForce = planeVelocity * -BRAKE_FORCE body:ApplyImpulse(brakeForce) -- Jump. Must release jump control inbetween jumps if self.controls:IsDown(CTRL_JUMP) then if self.okToJump then body:ApplyImpulse(Vector3(0.0, 1.0, 0.0) * JUMP_FORCE) self.okToJump = false end else self.okToJump = true end end -- Play walk animation if moving on ground, otherwise fade it out if softGrounded and not moveDir:Equals(Vector3(0.0, 0.0, 0.0)) then animCtrl:PlayExclusive("Models/Jack_Walk.ani", 0, true, 0.2) else animCtrl:Stop("Models/Jack_Walk.ani", 0.2) end -- Set walk animation speed proportional to velocity animCtrl:SetSpeed("Models/Jack_Walk.ani", planeVelocity:Length() * 0.3) -- Reset grounded flag for next frame self.onGround = false end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element\">" .. " <element type=\"Button\">" .. " <attribute name=\"Name\" value=\"Button3\" />" .. " <attribute name=\"Position\" value=\"-120 -120\" />" .. " <attribute name=\"Size\" value=\"96 96\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" .. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" .. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" .. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" .. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" .. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"Label\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" .. " <attribute name=\"Vert Alignment\" value=\"Center\" />" .. " <attribute name=\"Color\" value=\"0 0 0 1\" />" .. " <attribute name=\"Text\" value=\"Gyroscope\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"G\" />" .. " </element>" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">1st/3rd</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"F\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Jump</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
arventwei/WioEngine
Tools/jamplus/src/luaplus/Src/Modules/lanes/tests/launchtest.lua
7
2050
-- -- LAUNCHTEST.LUA Copyright (c) 2007-08, Asko Kauppi <akauppi@gmail.com> -- -- Tests launching speed of N threads -- -- Usage: -- [time] lua -lstrict launchtest.lua [threads] [-libs[=io,os,math,...]] -- -- threads: number of threads to launch (like: 2000) :) -- libs: combination of "os","io","math","package", ... -- just "-libs" for all libraries -- -- Note: -- One _can_ reach the system threading level, ie. doing 10000 on -- PowerBook G4: -- << -- pthread_create( ref, &a, lane_main, data ) failed @ line 316: 35 -- Command terminated abnormally. -- << -- -- (Lua Lanes _can_ be made tolerable to such congestion cases. Just -- currently, it is not. btw, 5000 seems to run okay - system limit -- being 2040 simultaneous threads) -- -- To do: -- - ... -- local N= 1000 -- threads/loops to use local M= 1000 -- sieves from 1..M local LIBS= nil -- default: load no libraries local function HELP() io.stderr:write( "Usage: lua launchtest.lua [threads] [-libs[=io,os,math,...]]\n" ) exit(1) end local m= require "argtable" local argtable= assert(m.argtable) for k,v in pairs( argtable(...) ) do if k==1 then N= tonumber(v) or HELP() elseif k=="libs" then LIBS= (v==true) and "*" or v else HELP() end end local lanes = require "lanes" lanes.configure() local g= lanes.gen( LIBS, function(i) --io.stderr:write( i.."\t" ) return i end ) local t= {} for i=1,N do t[i]= g(i) end if false then -- just finish here, without waiting for threads to finish -- local st= t[N].status print(st) -- if that is "done", they flew already! :) else -- mark that all have been launched, now wait for them to return -- io.stderr:write( N.." lanes launched.\n" ) for i=1,N do local rc= t[i]:join() assert( rc==i ) end io.stderr:write( N.." lanes finished.\n" ) end
mit
arventwei/WioEngine
Tools/jamplus/src/luaplus/Src/Modules/socket/test/mimetest.lua
44
8413
local socket = require("socket") local ltn12 = require("ltn12") local mime = require("mime") local unpack = unpack or table.unpack dofile("testsupport.lua") local qptest = "qptest.bin" local eqptest = "qptest.bin2" local dqptest = "qptest.bin3" local b64test = "b64test.bin" local eb64test = "b64test.bin2" local db64test = "b64test.bin3" -- from Machado de Assis, "A Mão e a Rosa" local mao = [[ Cursavam estes dois moços a academia de S. Paulo, estando Luís Alves no quarto ano e Estêvão no terceiro. Conheceram-se na academia, e ficaram amigos íntimos, tanto quanto podiam sê-lo dois espíritos diferentes, ou talvez por isso mesmo que o eram. Estêvão, dotado de extrema sensibilidade, e não menor fraqueza de ânimo, afetuoso e bom, não daquela bondade varonil, que é apanágio de uma alma forte, mas dessa outra bondade mole e de cera, que vai à mercê de todas as circunstâncias, tinha, além de tudo isso, o infortúnio de trazer ainda sobre o nariz os óculos cor-de-rosa de suas virginais ilusões. Luís Alves via bem com os olhos da cara. Não era mau rapaz, mas tinha o seu grão de egoísmo, e se não era incapaz de afeições, sabia regê-las, moderá-las, e sobretudo guiá-las ao seu próprio interesse. Entre estes dois homens travara-se amizade íntima, nascida para um na simpatia, para outro no costume. Eram eles os naturais confidentes um do outro, com a diferença que Luís Alves dava menos do que recebia, e, ainda assim, nem tudo o que dava exprimia grande confiança. ]] local function random(handle, io_err) if handle then return function() if not handle then error("source is empty!", 2) end local len = math.random(0, 1024) local chunk = handle:read(len) if not chunk then handle:close() handle = nil end return chunk end else return ltn12.source.empty(io_err or "unable to open file") end end local function named(f) return f end local what = nil local function transform(input, output, filter) local source = random(io.open(input, "rb")) local sink = ltn12.sink.file(io.open(output, "wb")) if what then sink = ltn12.sink.chain(filter, sink) else source = ltn12.source.chain(source, filter) end --what = not what ltn12.pump.all(source, sink) end local function encode_qptest(mode) local encode = mime.encode("quoted-printable", mode) local split = mime.wrap("quoted-printable") local chain = ltn12.filter.chain(encode, split) transform(qptest, eqptest, chain) end local function compare_qptest() io.write("testing qp encoding and wrap: ") compare(qptest, dqptest) end local function decode_qptest() local decode = mime.decode("quoted-printable") transform(eqptest, dqptest, decode) end local function create_qptest() local f, err = io.open(qptest, "wb") if not f then fail(err) end -- try all characters for i = 0, 255 do f:write(string.char(i)) end -- try all characters and different line sizes for i = 0, 255 do for j = 0, i do f:write(string.char(i)) end f:write("\r\n") end -- test latin text f:write(mao) -- force soft line breaks and treatment of space/tab in end of line local tab f:write(string.gsub(mao, "(%s)", function(c) if tab then tab = nil return "\t" else tab = 1 return " " end end)) -- test crazy end of line conventions local eol = { "\r\n", "\r", "\n", "\n\r" } local which = 0 f:write(string.gsub(mao, "(\n)", function(c) which = which + 1 if which > 4 then which = 1 end return eol[which] end)) for i = 1, 4 do for j = 1, 4 do f:write(eol[i]) f:write(eol[j]) end end -- try long spaced and tabbed lines f:write("\r\n") for i = 0, 255 do f:write(string.char(9)) end f:write("\r\n") for i = 0, 255 do f:write(' ') end f:write("\r\n") for i = 0, 255 do f:write(string.char(9),' ') end f:write("\r\n") for i = 0, 255 do f:write(' ',string.char(32)) end f:write("\r\n") f:close() end local function cleanup_qptest() os.remove(qptest) os.remove(eqptest) os.remove(dqptest) end -- create test file local function create_b64test() local f = assert(io.open(b64test, "wb")) local t = {} for j = 1, 100 do for i = 1, 100 do t[i] = math.random(0, 255) end f:write(string.char(unpack(t))) end f:close() end local function encode_b64test() local e1 = mime.encode("base64") local e2 = mime.encode("base64") local e3 = mime.encode("base64") local e4 = mime.encode("base64") local sp4 = mime.wrap() local sp3 = mime.wrap(59) local sp2 = mime.wrap("base64", 30) local sp1 = mime.wrap(27) local chain = ltn12.filter.chain(e1, sp1, e2, sp2, e3, sp3, e4, sp4) transform(b64test, eb64test, chain) end local function decode_b64test() local d1 = named(mime.decode("base64"), "d1") local d2 = named(mime.decode("base64"), "d2") local d3 = named(mime.decode("base64"), "d3") local d4 = named(mime.decode("base64"), "d4") local chain = named(ltn12.filter.chain(d1, d2, d3, d4), "chain") transform(eb64test, db64test, chain) end local function cleanup_b64test() os.remove(b64test) os.remove(eb64test) os.remove(db64test) end local function compare_b64test() io.write("testing b64 chained encode: ") compare(b64test, db64test) end local function identity_test() io.write("testing identity: ") local chain = named(ltn12.filter.chain( named(mime.encode("quoted-printable"), "1 eq"), named(mime.encode("base64"), "2 eb"), named(mime.decode("base64"), "3 db"), named(mime.decode("quoted-printable"), "4 dq") ), "chain") transform(b64test, eb64test, chain) compare(b64test, eb64test) os.remove(eb64test) end local function padcheck(original, encoded) local e = (mime.b64(original)) local d = (mime.unb64(encoded)) if e ~= encoded then fail("encoding failed") end if d ~= original then fail("decoding failed") end end local function chunkcheck(original, encoded) local len = string.len(original) for i = 0, len do local a = string.sub(original, 1, i) local b = string.sub(original, i+1) local e, r = mime.b64(a, b) local f = (mime.b64(r)) if (e .. (f or "") ~= encoded) then fail(e .. (f or "")) end end end local function padding_b64test() io.write("testing b64 padding: ") padcheck("a", "YQ==") padcheck("ab", "YWI=") padcheck("abc", "YWJj") padcheck("abcd", "YWJjZA==") padcheck("abcde", "YWJjZGU=") padcheck("abcdef", "YWJjZGVm") padcheck("abcdefg", "YWJjZGVmZw==") padcheck("abcdefgh", "YWJjZGVmZ2g=") padcheck("abcdefghi", "YWJjZGVmZ2hp") padcheck("abcdefghij", "YWJjZGVmZ2hpag==") chunkcheck("abcdefgh", "YWJjZGVmZ2g=") chunkcheck("abcdefghi", "YWJjZGVmZ2hp") chunkcheck("abcdefghij", "YWJjZGVmZ2hpag==") print("ok") end local function test_b64lowlevel() io.write("testing b64 low-level: ") local a, b a, b = mime.b64("", "") assert(a == "" and b == "") a, b = mime.b64(nil, "blablabla") assert(a == nil and b == nil) a, b = mime.b64("", nil) assert(a == nil and b == nil) a, b = mime.unb64("", "") assert(a == "" and b == "") a, b = mime.unb64(nil, "blablabla") assert(a == nil and b == nil) a, b = mime.unb64("", nil) assert(a == nil and b == nil) local binary=string.char(0x00,0x44,0x1D,0x14,0x0F,0xF4,0xDA,0x11,0xA9,0x78,0x00,0x14,0x38,0x50,0x60,0xCE) local encoded = mime.b64(binary) local decoded=mime.unb64(encoded) assert(binary == decoded) print("ok") end local t = socket.gettime() create_b64test() identity_test() encode_b64test() decode_b64test() compare_b64test() cleanup_b64test() padding_b64test() test_b64lowlevel() create_qptest() encode_qptest() decode_qptest() compare_qptest() encode_qptest("binary") decode_qptest() compare_qptest() cleanup_qptest() print(string.format("done in %.2fs", socket.gettime() - t))
mit
wrxck/mattata
plugins/help.lua
2
16362
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local help = {} local mattata = require('mattata') function help:init(configuration) help.commands = mattata.commands(self.info.username):command('help'):command('start').table help.help = '/help [plugin] - A help-orientated menu is sent if no arguments are given. If arguments are given, usage information for the given plugin is sent instead. Alias: /start.' help.per_page = configuration.limits.help.per_page end function help.get_initial_keyboard() return mattata.inline_keyboard():row( mattata.row():callback_data_button( 'Links', 'help:links' ):callback_data_button( 'Admin Help', 'help:acmds' ):callback_data_button( 'Commands', 'help:cmds' ) ):row( mattata.row():switch_inline_query_button( 'Inline Mode', '/' ):callback_data_button( 'Settings', 'help:settings' ):callback_data_button( 'Channels', 'help:channels' ) ) end function help.get_plugin_page(arguments_list, page) local plugin_count = #arguments_list local page_begins_at = tonumber(page) * help.per_page - (help.per_page - 1) local page_ends_at = tonumber(page_begins_at) + (help.per_page - 1) if tonumber(page_ends_at) > tonumber(plugin_count) then page_ends_at = tonumber(plugin_count) end local page_plugins = {} for i = tonumber(page_begins_at), tonumber(page_ends_at) do local plugin = arguments_list[i] if i < tonumber(page_ends_at) then plugin = plugin .. '\n' end table.insert(page_plugins, plugin) end return table.concat(page_plugins, '\n') end function help.get_back_keyboard() return mattata.inline_keyboard():row( mattata.row():callback_data_button( mattata.symbols.back .. ' Back', 'help:back' ) ) end function help.on_inline_query(_, inline_query, _, language) local offset = inline_query.offset and tonumber(inline_query.offset) or 0 local output = mattata.get_inline_help(inline_query.query, offset) if not next(output) and offset == 0 then output = string.format(language['help']['2'], inline_query.query) return mattata.send_inline_article(inline_query.id, language['help']['1'], output) end offset = tostring(offset + 50) return mattata.answer_inline_query(inline_query.id, output, 0, false, offset) end function help:on_callback_query(callback_query, message, _, language) if callback_query.data == 'cmds' then local arguments_list = mattata.get_help(self, false, message.chat.id) local plugin_count = #arguments_list local page_count = math.floor(tonumber(plugin_count) / help.per_page) if math.floor(tonumber(plugin_count) / help.per_page) ~= tonumber(plugin_count) / help.per_page then page_count = page_count + 1 end local output = help.get_plugin_page(arguments_list, 1) output = output .. mattata.escape_html(string.format(language['help']['3'], self.info.username)) return mattata.edit_message_text( message.chat.id, message.message_id, output, 'html', true, mattata.inline_keyboard():row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['4'], 'help:results:0' ):callback_data_button( '1/' .. page_count, 'help:pages:1:' .. page_count ):callback_data_button( language['help']['5'] .. ' ' .. mattata.symbols.next, 'help:results:2' ) ):row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['6'], 'help:back' ):switch_inline_query_current_chat_button( '🔎 ' .. language['help']['7'], '/' ) ) ) elseif callback_query.data:match('^results:%d*$') then local new_page = callback_query.data:match('^results:(%d*)$') local arguments_list = mattata.get_help(self, false, message.chat.id) local plugin_count = #arguments_list local page_count = math.floor(tonumber(plugin_count) / help.per_page) if math.floor(tonumber(plugin_count) / help.per_page) ~= tonumber(plugin_count) / help.per_page then page_count = page_count + 1 end if tonumber(new_page) > tonumber(page_count) then new_page = 1 elseif tonumber(new_page) < 1 then new_page = tonumber(page_count) end local output = help.get_plugin_page(arguments_list, new_page) output = output .. mattata.escape_html(string.format(language['help']['3'], self.info.username)) return mattata.edit_message_text( message.chat.id, message.message_id, output, 'html', true, mattata.inline_keyboard():row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['4'], 'help:results:' .. math.floor(tonumber(new_page) - 1) ):callback_data_button( new_page .. '/' .. page_count, 'help:pages:' .. new_page .. ':' .. page_count ):callback_data_button( language['help']['5'] .. ' ' .. mattata.symbols.next, 'help:results:' .. math.floor(tonumber(new_page) + 1) ) ):row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['6'], 'help:back' ):switch_inline_query_current_chat_button( '🔎 ' .. language['help']['7'], '/' ) ) ) elseif callback_query.data == 'acmds' then local arguments_list = mattata.get_help(self, true, message.chat.id) local plugin_count = #arguments_list local page_count = math.floor(tonumber(plugin_count) / help.per_page) if math.floor(tonumber(plugin_count) / help.per_page) ~= tonumber(plugin_count) / help.per_page then page_count = page_count + 1 end local output = help.get_plugin_page(arguments_list, 1) output = output .. mattata.escape_html(string.format(language['help']['3'], self.info.username)) return mattata.edit_message_text( message.chat.id, message.message_id, output, 'html', true, mattata.inline_keyboard():row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['4'], 'help:aresults:0' ):callback_data_button( '1/' .. page_count, 'help:pages:1:' .. page_count ):callback_data_button( language['help']['5'] .. ' ' .. mattata.symbols.next, 'help:aresults:2' ) ):row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['6'], 'help:back' ) ) ) elseif callback_query.data:match('^aresults:%d*$') then local new_page = callback_query.data:match('^aresults:(%d*)$') local arguments_list = mattata.get_help(self, true, message.chat.id) local plugin_count = #arguments_list local page_count = math.floor(tonumber(plugin_count) / help.per_page) if math.floor(tonumber(plugin_count) / help.per_page) ~= tonumber(plugin_count) / help.per_page then page_count = page_count + 1 end if tonumber(new_page) > tonumber(page_count) then new_page = 1 elseif tonumber(new_page) < 1 then new_page = tonumber(page_count) end local output = help.get_plugin_page(arguments_list, new_page) output = output .. mattata.escape_html(string.format(language['help']['3'], self.info.username)) return mattata.edit_message_text( message.chat.id, message.message_id, output, 'html', true, mattata.inline_keyboard():row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['4'], 'help:aresults:' .. math.floor(tonumber(new_page) - 1) ):callback_data_button( new_page .. '/' .. page_count, 'help:pages:' .. new_page .. ':' .. page_count ):callback_data_button( language['help']['5'] .. ' ' .. mattata.symbols.next, 'help:aresults:' .. math.floor(tonumber(new_page) + 1) ) ):row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['6'], 'help:back' ) ) ) elseif callback_query.data:match('^pages:%d*:%d*$') then local current_page, total_pages = callback_query.data:match('^pages:(%d*):(%d*)$') return mattata.answer_callback_query( callback_query.id, string.format(language['help']['8'], current_page, total_pages) ) elseif callback_query.data:match('^ahelp:') then return mattata.answer_callback_query(callback_query.id, 'This is an old keyboard, please request a new one using /help!') elseif callback_query.data == 'links' then return mattata.edit_message_text( message.chat.id, message.message_id, language['help']['12'], nil, true, mattata.inline_keyboard():row( mattata.row():url_button( language['help']['13'], 'https://t.me/mattataDev' ):url_button( language['help']['14'], 'https://t.me/mattata' ):url_button( language['help']['15'], 'https://t.me/mattataSupport' ) ):row( mattata.row():url_button( language['help']['16'], 'https://t.me/mattataFAQ' ):url_button( language['help']['17'], 'https://github.com/wrxck/mattata' ):url_button( language['help']['18'], 'https://paypal.me/wrxck' ) ):row( mattata.row():url_button( language['help']['19'], 'https://t.me/storebot?start=mattatabot' ):url_button( language['help']['20'], 'https://t.me/mattataLog' ):url_button( 'Twitter', 'https://twitter.com/intent/user?screen_name=matt__hesketh' ) ):row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['6'], 'help:back' ) ) ) elseif callback_query.data == 'channels' then return mattata.edit_message_text( message.chat.id, message.message_id, language['help']['12'], nil, true, mattata.inline_keyboard():row( mattata.row():url_button( 'no context', 'https://t.me/no_context' ) ):row( mattata.row():callback_data_button( mattata.symbols.back .. ' ' .. language['help']['6'], 'help:back' ) ) ) elseif callback_query.data == 'settings' then if message.chat.type == 'supergroup' and not mattata.is_group_admin(message.chat.id, callback_query.from.id) then return mattata.answer_callback_query(callback_query.id, language['errors']['admin']) end return mattata.edit_message_reply_markup( message.chat.id, message.message_id, nil, ( message.chat.type == 'supergroup' and mattata.is_group_admin( message.chat.id, callback_query.from.id ) ) and mattata.inline_keyboard() :row( mattata.row():callback_data_button( language['help']['21'], 'administration:' .. message.chat.id .. ':page:1' ):callback_data_button( language['help']['22'], 'plugins:' .. message.chat.id .. ':page:1' ) ) :row( mattata.row():callback_data_button( language['help']['6'], 'help:back' ) ) or mattata.inline_keyboard():row( mattata.row():callback_data_button( language['help']['22'], 'plugins:' .. message.chat.id .. ':page:1' ) ):row( mattata.row():callback_data_button( language['help']['6'], 'help:back' ) ) ) elseif callback_query.data == 'back' then return mattata.edit_message_text( message.chat.id, message.message_id, string.format( language['help']['23'], mattata.escape_html(callback_query.from.first_name), mattata.escape_html(self.info.first_name), utf8.char(128513), utf8.char(128161), message.chat.type ~= 'private' and ' ' .. language['help']['24'] .. ' ' .. mattata.escape_html(message.chat.title) or '', utf8.char(128176) ), 'html', true, help.get_initial_keyboard(message.chat.type == 'supergroup' and message.chat.id or false) ) end end function help:on_message(message, _, language) local input = mattata.input(message.text) if input and input:match('^[/!]?%w+$') then local plugin_documentation = false input = input:match('^/') and input or '/' .. input for _, v in pairs(self.plugin_list) do if v:match(input) then plugin_documentation = v end end if not plugin_documentation then -- if it wasn't a normal plugin, it might be an administrative one for _, v in pairs(self.administrative_plugin_list) do if v:match(input) then plugin_documentation = v end end end plugin_documentation = plugin_documentation or 'I couldn\'t find a plugin matching that command!' plugin_documentation = plugin_documentation .. '\n\nTo see all commands, just send /help.' return mattata.send_reply(message, plugin_documentation) end return mattata.send_message( message.chat.id, string.format( language['help']['23'], mattata.escape_html(message.from.first_name), mattata.escape_html(self.info.first_name), utf8.char(128513), utf8.char(128161), message.chat.type ~= 'private' and ' ' .. language['help']['24'] .. ' ' .. mattata.escape_html(message.chat.title) or '', utf8.char(128176) ), 'html', false, true, nil, help.get_initial_keyboard(message.chat.type == 'supergroup' and message.chat.id or false) ) end return help
mit
feiltom/domoticz
scripts/dzVents/examples/check dead devices by desc.lua
3
1557
--Check dead device using their description --This allow to configure device to be checked directly in domoticz GUI by accessing to device details and add "CDA:<delayInMinute>" --You have to active http fetching ! return { active = true, on = { ['timer'] = 'every 60 minutes' }, execute = function(domoticz) local message="" domoticz.devices.forEach(function(device) if (device.description ~= nil) then _, _, threshold = string.find(device.description,"CDA:(%d+)") if (threshold ~= nil) then local name = device.name local minutes = domoticz.devices[name].lastUpdate.minutesAgo if ( minutes > tonumber(threshold)) then message = message .. 'Device ' .. name .. ' seems to be dead. No heartbeat for at least ' .. minutes .. ' minutes.\r' end end end end) if (message ~= "") then domoticz.notify('Dead devices', message, domoticz.PRIORITY_HIGH) domoticz.log('Dead devices found: ' .. message, domoticz.LOG_ERROR) end end }
gpl-3.0
ld-test/oil
lua/loop/compiler/Conditional.lua
12
1934
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Conditional Compiler for Code Generation -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- local type = type local assert = assert local ipairs = ipairs local setfenv = setfenv local loadstring = loadstring local table = require "table" local oo = require "loop.base" module("loop.compiler.Conditional", oo.class) function source(self, includes) local func = {} for line, strip in ipairs(self) do local cond = strip[2] if cond then cond = assert(loadstring("return "..cond, "compiler condition "..line..":")) setfenv(cond, includes) cond = cond() else cond = true end if cond then assert(type(strip[1]) == "string", "code string is not a string") func[#func+1] = strip[1] end end return table.concat(func, "\n") end function execute(self, includes, ...) return assert(loadstring(self:source(includes), self.name))(...) end
mit
bigdogmat/wire
lua/wire/gates/comparison.lua
17
2192
--[[ Comparison Gates ]] GateActions("Comparison") GateActions["="] = { name = "Equal", inputs = { "A", "B" }, output = function(gate, A, B) if (math.abs(A-B) < 0.001) then return 1 end return 0 end, label = function(Out, A, B) return A.." == "..B.." = "..Out end } GateActions["!="] = { name = "Not Equal", inputs = { "A", "B" }, output = function(gate, A, B) if (math.abs(A-B) < 0.001) then return 0 end return 1 end, label = function(Out, A, B) return A.." ~= "..B.." = "..Out end } GateActions["<"] = { name = "Less Than", inputs = { "A", "B" }, output = function(gate, A, B) if (A < B) then return 1 end return 0 end, label = function(Out, A, B) return A.." < "..B.." = "..Out end } GateActions[">"] = { name = "Greater Than", inputs = { "A", "B" }, output = function(gate, A, B) if (A > B) then return 1 end return 0 end, label = function(Out, A, B) return A.." > "..B.." = "..Out end } GateActions["<="] = { name = "Less or Equal", inputs = { "A", "B" }, output = function(gate, A, B) if (A <= B) then return 1 end return 0 end, label = function(Out, A, B) return A.." <= "..B.." = "..Out end } GateActions[">="] = { name = "Greater or Equal", inputs = { "A", "B" }, output = function(gate, A, B) if (A >= B) then return 1 end return 0 end, label = function(Out, A, B) return A.." >= "..B.." = "..Out end } GateActions["inrangei"] = { name = "Is In Range (Inclusive)", inputs = { "Min", "Max", "Value" }, output = function(gate, Min, Max, Value) if (Max < Min) then local temp = Max Max = Min Min = temp end if ((Value >= Min) && (Value <= Max)) then return 1 end return 0 end, label = function(Out, Min, Max, Value) return Min.." <= "..Value.." <= "..Max.." = "..Out end } GateActions["inrangee"] = { name = "Is In Range (Exclusive)", inputs = { "Min", "Max", "Value" }, output = function(gate, Min, Max, Value) if (Max < Min) then local temp = Max Max = Min Min = temp end if ((Value > Min) && (Value < Max)) then return 1 end return 0 end, label = function(Out, Min, Max, Value) return Min.." < "..Value.." < "..Max.." = "..Out end } GateActions()
apache-2.0
bizkut/BudakJahat
System/Functions/Action.lua
1
1448
function canFly() local hasDraenorFly = select(4,GetAchievementInfo(10018)) local hasLegionFly = select(4,GetAchievementInfo(11446)) return IsOutdoors() and IsFlyableArea() and ((not isInDraenor() and not isInLegion()) or (hasDraenorFly and isInDraenor()) or (hasLegionFly and isInLegion())) end -- if canHeal("target") then function canHeal(Unit) if GetUnitExists(Unit) and UnitInRange(Unit) == true and UnitCanCooperate("player",Unit) and not UnitIsEnemy("player",Unit) and not UnitIsCharmed(Unit) and not UnitIsDeadOrGhost(Unit) and getLineOfSight(Unit) == true and not UnitDebuffID(Unit,33786) then return true end return false end -- if canRun() then function canRun() if getOptionCheck("Pause") ~= 1 then if isAlive("player") then if SpellIsTargeting() --or UnitInVehicle("Player") or (IsMounted() and not UnitBuffID("player",164222) and not UnitBuffID("player",165803) and not UnitBuffID("player",157059) and not UnitBuffID("player",157060)) or UnitBuffID("player",11392) ~= nil or UnitBuffID("player",80169) ~= nil or UnitBuffID("player",87959) ~= nil or UnitBuffID("player",104934) ~= nil or UnitBuffID("player",9265) ~= nil then -- Deep Sleep(SM) return nil else if GetObjectExists("target") then if GetObjectID("target") ~= 5687 then return nil end end return true end end else ChatOverlay("|cffFF0000-BudakJahat Paused-") return false end end
gpl-3.0
asmagill/hammerspoon_asm
turtle/init.lua
1
51873
--- === hs.canvas.turtle === --- --- Creates a view which can be assigned to an `hs.canvas` object of type "canvas" which displays graphical images rendered in a style similar to that of the Logo language, sometimes referred to as "Turtle Graphics". --- --- Briefly, turtle graphics are vector graphics using a relative cursor (the "turtle") upon a Cartesian plane. The view created by this module has its origin in the center of the display area. The Y axis grows positively as you move up and negatively as you move down from this origin (this is the opposite of the internal coordinates of other `hs.canvas` objects); similarly, movement left is positive movement along the X axis, while movement right is negative. --- --- The turtle is initially visible with a heading of 0 degrees (pointing straight up), and the pen (the drawing element of the turtle) is down with a black color in paint mode. All of these can be adjusted by methods within this module. --- --- --- Some of the code included in this module was influenced by or written to mimic behaviors described at: --- * https://people.eecs.berkeley.edu/~bh/docs/html/usermanual_6.html#GRAPHICS --- * https://www.calormen.com/jslogo/# --- * https://github.com/inexorabletash/jslogo local USERDATA_TAG = "hs.canvas.turtle" local module = require(USERDATA_TAG..".internal") local turtleMT = hs.getObjectMetatable(USERDATA_TAG) local color = require("hs.drawing.color") local inspect = require("hs.inspect") local fnutils = require("hs.fnutils") local canvas = require("hs.canvas") local screen = require("hs.screen") local eventtap = require("hs.eventtap") local mouse = require("hs.mouse") -- don't need these directly, just their helpers require("hs.image") local basePath = package.searchpath(USERDATA_TAG, package.path) if basePath then basePath = basePath:match("^(.+)/init.lua$") if require"hs.fs".attributes(basePath .. "/docs.json") then require"hs.doc".registerJSONFile(basePath .. "/docs.json") end end local log = require("hs.logger").new(USERDATA_TAG, require"hs.settings".get(USERDATA_TAG .. ".logLevel") or "warning") -- private variables and methods ----------------------------------------- -- borrowed and (very) slightly modified from https://www.calormen.com/jslogo/#; specifically -- https://github.com/inexorabletash/jslogo/blob/02482525925e399020f23339a0991d98c4f088ff/turtle.js#L129-L152 local betterTurtle = canvas.new{ x = 100, y = 100, h = 45, w = 45 }:appendElements{ { type = "segments", action = "strokeAndFill", strokeColor = { green = 1 }, fillColor = { green = .75, alpha = .25 }, frame = { x = 0, y = 0, h = 40, w = 40 }, strokeWidth = 2, transformation = canvas.matrix.translate(22.5, 24.5), coordinates = { { x = 0, y = -20 }, { x = 2.5, y = -17 }, { x = 3, y = -12 }, { x = 6, y = -10 }, { x = 9, y = -13 }, { x = 13, y = -12 }, { x = 18, y = -4 }, { x = 18, y = 0 }, { x = 14, y = -1 }, { x = 10, y = -7 }, { x = 8, y = -6 }, { x = 10, y = -2 }, { x = 9, y = 3 }, { x = 6, y = 10 }, { x = 9, y = 13 }, { x = 6, y = 15 }, { x = 3, y = 12 }, { x = 0, y = 13 }, { x = -3, y = 12 }, { x = -6, y = 15 }, { x = -9, y = 13 }, { x = -6, y = 10 }, { x = -9, y = 3 }, { x = -10, y = -2 }, { x = -8, y = -6 }, { x = -10, y = -7 }, { x = -14, y = -1 }, { x = -18, y = 0 }, { x = -18, y = -4 }, { x = -13, y = -12 }, { x = -9, y = -13 }, { x = -6, y = -10 }, { x = -3, y = -12 }, { x = -2.5, y = -17 }, { x = 0, y = -20 }, }, }, }:imageFromCanvas() -- Hide the internals from accidental usage local _wrappedCommands = module._wrappedCommands -- module._wrappedCommands = nil local _unwrappedSynonyms = { clearscreen = { "cs" }, showturtle = { "st" }, hideturtle = { "ht" }, background = { "bg" }, textscreen = { "ts" }, fullscreen = { "fs" }, splitscreen = { "ss" }, pencolor = { "pc" }, -- shownp = { "shown?" }, -- not a legal lua method name, so will need to catch when converter written -- pendownp = { "pendown?" }, } -- in case I ever write something to import turtle code directly, don't want these to cause it to break immediately local _nops = { wrap = false, -- boolean indicates whether or not warning has been issued; don't want to spam console window = false, fence = false, textscreen = false, fullscreen = false, splitscreen = false, refresh = false, norefresh = false, setpenpattern = true, -- used in setpen, in case I ever actually implement it, so skip warning } local defaultPalette = { { "black", { __luaSkinType = "NSColor", list = "Apple", name = "Black" }}, { "blue", { __luaSkinType = "NSColor", list = "Apple", name = "Blue" }}, { "green", { __luaSkinType = "NSColor", list = "Apple", name = "Green" }}, { "cyan", { __luaSkinType = "NSColor", list = "Apple", name = "Cyan" }}, { "red", { __luaSkinType = "NSColor", list = "Apple", name = "Red" }}, { "magenta", { __luaSkinType = "NSColor", list = "Apple", name = "Magenta" }}, { "yellow", { __luaSkinType = "NSColor", list = "Apple", name = "Yellow" }}, { "white", { __luaSkinType = "NSColor", list = "Apple", name = "White" }}, { "brown", { __luaSkinType = "NSColor", list = "Apple", name = "Brown" }}, { "tan", { __luaSkinType = "NSColor", list = "x11", name = "tan" }}, { "forest", { __luaSkinType = "NSColor", list = "x11", name = "forestgreen" }}, { "aqua", { __luaSkinType = "NSColor", list = "Crayons", name = "Aqua" }}, { "salmon", { __luaSkinType = "NSColor", list = "Crayons", name = "Salmon" }}, { "purple", { __luaSkinType = "NSColor", list = "Apple", name = "Purple" }}, { "orange", { __luaSkinType = "NSColor", list = "Apple", name = "Orange" }}, { "gray", { __luaSkinType = "NSColor", list = "x11", name = "gray" }}, } -- pulled from webkit/Source/WebKit/Shared/WebPreferencesDefaultValues.h 2020-05-17 module._fontMap = { serif = "Times", ["sans-serif"] = "Helvetica", cursive = "Apple Chancery", fantasy = "Papyrus", monospace = "Courier", -- pictograph = "Apple Color Emoji", } module._registerDefaultPalette(defaultPalette) module._registerDefaultPalette = nil module._registerFontMap(module._fontMap) module._registerFontMap = nil local finspect = function(obj) return inspect(obj, { newline = " ", indent = "" }) end local _backgroundQueues = setmetatable({}, { __mode = "k", -- work around for the fact that we're using selfRefCount to allow for auto-clean on __gc -- relies on the fact that these are only called if the key *doesn't* exist already in the -- table -- the following assume [<userdata>] = { table } in weak-key table; if you're not -- saving a table of values keyed to the userdata, all bets are off and you'll -- need to write something else __index = function(self, key) for k,v in pairs(self) do if k == key then -- put *this* key in with the same table so changes to the table affect all -- "keys" pointing to this table rawset(self, key, v) return v end end return nil end, __newindex = function(self, key, value) local haslogged = false -- only called for a complete re-assignment of the table if __index wasn't -- invoked first... for k,v in pairs(self) do if k == key then if type(value) == "table" and type(v) == "table" then -- do this to keep the target table for existing useradata the same -- because it may have multiple other userdatas pointing to it for k2, v2 in pairs(v) do v[k2] = nil end -- shallow copy -- can't have everything or this will get insane for k2, v2 in pairs(value) do v[k2] = v2 end rawset(self, key, v) return else -- we'll try... replace *all* existing matches (i.e. don't return after 1st) -- but since this will never get called if __index was invoked first, log -- warning anyways because this *isn't* what these additions are for... if not haslogged then hs.luaSkinLog.wf("%s - weak table indexing only works when value is a table; behavior is undefined for value type %s", USERDATA_TAG, type(value)) haslogged = true end rawset(self, k, value) end end end rawset(self, key, value) end, }) -- Public interface ------------------------------------------------------ local _new = module.new module.new = function(...) return _new(...):_turtleImage(betterTurtle) end module.turtleCanvas = function(...) local decorateSize = 16 local recalcDecorations = function(nC, decorate) if decorate then local frame = nC:frame() nC.moveBar.frame = { x = 0, y = 0, h = decorateSize, w = frame.w } nC.resizeX.frame = { x = frame.w - decorateSize, y = decorateSize, h = frame.h - decorateSize * 2, w = decorateSize } nC.resizeY.frame = { x = 0, y = frame.h - decorateSize, h = decorateSize, w = frame.w - decorateSize, } nC.resizeXY.frame = { x = frame.w - decorateSize, y = frame.h - decorateSize, h = decorateSize, w = decorateSize } nC.turtleView.frame = { x = 0, y = decorateSize, h = frame.h - decorateSize * 2, w = frame.w - decorateSize, } end end local args = table.pack(...) local frame, decorate = {}, true local decorateIdx = 2 if type(args[1]) == "table" then frame, decorateIdx = args[1], 2 end if args.n >= decorateIdx then decorate = args[decorateIdx] end frame = frame or {} local screenFrame = screen.mainScreen():fullFrame() local defaultFrame = { x = screenFrame.x + screenFrame.w / 4, y = screenFrame.y + screenFrame.h / 4, h = screenFrame.h / 2, w = screenFrame.w / 2, } frame.x = frame.x or defaultFrame.x frame.y = frame.y or defaultFrame.y frame.w = frame.w or defaultFrame.w frame.h = frame.h or defaultFrame.h local _cMouseAction -- make local here so it's an upvalue in mouseCallback local nC = canvas.new(frame):show() if decorate then nC[#nC + 1] = { id = "moveBar", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 0 }, fillColor = { white = 1 }, strokeWidth = 1, } nC[#nC + 1] = { id = "resizeX", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 0 }, fillColor = { white = 1 }, strokeWidth = 1, } nC[#nC + 1] = { id = "resizeY", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 0 }, fillColor = { white = 1 }, strokeWidth = 1, } nC[#nC + 1] = { id = "resizeXY", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 0 }, fillColor = { white = 1 }, strokeWidth = 1, } nC[#nC + 1] = { id = "label", type = "text", action = "strokeAndFill", textSize = decorateSize - 2, textAlignment = "center", text = "TurtleCanvas", textColor = { white = 0 }, frame = { x = 0, y = 0, h = decorateSize, w = "100%" }, } end local turtleViewObject = module.new() nC[#nC + 1] = { id = "turtleView", type = "canvas", canvas = turtleViewObject, } recalcDecorations(nC, decorate) if decorate ~= nil then nC:clickActivating(false) :canvasMouseEvents(true, true) :mouseCallback(function(_c, _m, _i, _x, _y) if _i == "_canvas_" then if _m == "mouseDown" then local buttons = eventtap.checkMouseButtons() if buttons.left then local cframe = _c:frame() local inMoveArea = (_y < decorateSize) local inResizeX = (_x > (cframe.w - decorateSize)) local inResizeY = (_y > (cframe.h - decorateSize)) if inMoveArea then _cMouseAction = coroutine.wrap(function() while _cMouseAction do local pos = mouse.absolutePosition() local frame = _c:frame() frame.x = pos.x - _x frame.y = pos.y - _y _c:frame(frame) recalcDecorations(_c, decorate) coroutine.applicationYield() end end) _cMouseAction() elseif inResizeX or inResizeY then _cMouseAction = coroutine.wrap(function() while _cMouseAction do local pos = mouse.absolutePosition() local frame = _c:frame() if inResizeX then local newW = pos.x + cframe.w - _x - frame.x if newW < decorateSize then newW = decorateSize end frame.w = newW end if inResizeY then local newY = pos.y + cframe.h - _y - frame.y if newY < (decorateSize * 2) then newY = (decorateSize * 2) end frame.h = newY end _c:frame(frame) recalcDecorations(_c, decorate) coroutine.applicationYield() end end) _cMouseAction() end elseif buttons.right then local modifiers = eventtap.checkKeyboardModifiers() if modifiers.shift then _c:hide() end end elseif _m == "mouseUp" then _cMouseAction = nil end end end) end return turtleViewObject end -- methods with visual impact call this to allow for yields when we're running in a coroutine local coroutineFriendlyCheck = function(self) -- don't get tripped up by other coroutines if _backgroundQueues[self] and _backgroundQueues[self].ourCoroutine then if not self:_neverYield() then local thread, isMain = coroutine.running() if not isMain and (self:_cmdCount() % self:_yieldRatio()) == 0 then coroutine.applicationYield() end end end end --- hs.canvas.turtle:pos() -> table --- Method --- Returns the turtle’s current position, as a table containing two numbers, the X and Y coordinates. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the X and Y coordinates of the turtle. local _pos = turtleMT.pos turtleMT.pos = function(...) local result = _pos(...) return setmetatable(result, { __tostring = function(_) return string.format("{ %.2f, %.2f }", _[1], _[2]) end }) end --- hs.canvas.turtle:pensize() -> turtleViewObject --- Method --- Returns a table of two positive integers, specifying the horizontal and vertical thickness of the turtle pen. --- --- Parameters: --- * None --- --- Returns: --- * a table specifying the horizontal and vertical thickness of the turtle pen. --- --- Notes: --- * in this implementation the two numbers will always be equal as the macOS uses a single width for determining stroke size. local _pensize = turtleMT.pensize turtleMT.pensize = function(...) local result = _pensize(...) return setmetatable(result, { __tostring = function(_) return string.format("{ %.2f, %.2f }", _[1], _[2]) end }) end --- hs.canvas.turtle:scrunch() -> table --- Method --- Returns a table containing the current X and Y scrunch factors. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the X and Y scrunch factors for the turtle view local _scrunch = turtleMT.scrunch turtleMT.scrunch = function(...) local result = _scrunch(...) return setmetatable(result, { __tostring = function(_) return string.format("{ %.2f, %.2f }", _[1], _[2]) end }) end --- hs.canvas.turtle:labelsize() -> table --- Method --- Returns a table containing the height and width of characters rendered by [hs.canvas.turtle:label](#label). --- --- Parameters: --- * None --- --- Returns: --- * A table containing the width and height of characters. --- --- Notes: --- * On most modern machines, font widths are variable for most fonts; as this is not easily calculated unless the specific text to be rendered is known, the height, as specified with [hs.canvas.turtle:setlabelheight](#setlabelheight) is returned for both values by this method. local _labelsize = turtleMT.labelsize turtleMT.labelsize = function(...) local result = _labelsize(...) return setmetatable(result, { __tostring = function(_) return string.format("{ %.2f, %.2f }", _[1], _[2]) end }) end local __visibleAxes = turtleMT._visibleAxes turtleMT._visibleAxes = function(...) local result = __visibleAxes(...) return setmetatable(result, { __tostring = function(_) return string.format("{ { %.2f, %.2f }, { %.2f, %.2f } }", _[1][1], _[1][2], _[2][1], _[2][2]) end }) end --- hs.canvas.turtle:pencolor() -> int | table --- Method --- Get the current pen color, either as a palette index number or as an RGB(A) list, whichever way it was most recently set. --- --- Parameters: --- * None --- --- Returns: --- * if the background color was most recently set by palette index, returns the integer specifying the index; if it was set as a 3 or 4 value table representing RGB(A) values, the table is returned; otherwise returns a color table as defined in `hs.drawing.color`. --- --- Notes: --- * Synonym: `hs.canvas.turtle:pc()` local _pencolor = turtleMT.pencolor turtleMT.pencolor = function(...) local result = _pencolor(...) if type(result) == "number" then return result end local defaultToString = finspect(result) return setmetatable(result, { __tostring = function(_) if #_ == 3 then return string.format("{ %.2f, %.2f, %.2f }", _[1], _[2], _[3]) elseif #_ == 4 then return string.format("{ %.2f, %.2f, %.2f, %.2f }", _[1], _[2], _[3], _[4]) else return defaultToString end end }) end --- hs.canvas.turtle:background() -> int | table --- Method --- Get the background color, either as a palette index number or as an RGB(A) list, whichever way it was most recently set. --- --- Parameters: --- * None --- --- Returns: --- * if the background color was most recently set by palette index, returns the integer specifying the index; if it was set as a 3 or 4 value table representing RGB(A) values, the table is returned; otherwise returns a color table as defined in `hs.drawing.color`. --- --- Notes: --- * Synonym: `hs.canvas.turtle:bg()` local _background = turtleMT.background turtleMT.background = function(...) local result = _background(...) if type(result) == "number" then return result end local defaultToString = finspect(result) return setmetatable(result, { __tostring = function(_) if #_ == 3 then return string.format("{ %.2f, %.2f, %.2f }", _[1], _[2], _[3]) elseif #_ == 4 then return string.format("{ %.2f, %.2f, %.2f, %.2f }", _[1], _[2], _[3], _[4]) else return defaultToString end end }) end --- hs.canvas.turtle:palette(index) -> table --- Method --- Returns the color defined at the specified palette index. --- --- Parameters: --- * `index` - an integer between 0 and 255 specifying the index in the palette of the desired coloe --- --- Returns: --- * a table specifying the color as a list of 3 or 4 numbers representing the intensity of the red, green, blue, and optionally alpha channels as a number between 0.0 and 100.0. If the color cannot be represented in RGB(A) format, then a table as described in `hs.drawing.color` is returned. local _palette = turtleMT.palette turtleMT.palette = function(...) local result = _palette(...) local defaultToString = finspect(result) return setmetatable(result, { __tostring = function(_) if #_ == 3 then return string.format("{ %.2f, %.2f, %.2f }", _[1], _[2], _[3]) elseif #_ == 4 then return string.format("{ %.2f, %.2f, %.2f, %.2f }", _[1], _[2], _[3], _[4]) else return defaultToString end end }) end --- hs.canvas.turtle:towards(pos) -> number --- Method --- Returns the heading at which the turtle should be facing so that it would point from its current position to the position specified. --- --- Parameters: --- * `pos` - a position table containing the x and y coordinates as described in [hs.canvas.turtle:pos](#pos) of the point the turtle should face. --- --- Returns: --- * a number representing the heading the turtle should face to point to the position specified in degrees clockwise from the positive Y axis. turtleMT.towards = function(self, pos) local x, y = pos[1], pos[2] assert(type(x) == "number", "expected a number for the x coordinate") assert(type(y) == "number", "expected a number for the y coordinate") local cpos = self:pos() return (90 - math.atan(y - cpos[2],x - cpos[1]) * 180 / math.pi) % 360 end --- hs.canvas.turtle:screenmode() -> string --- Method --- Returns a string describing the current screen mode for the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * "FULLSCREEN" --- --- Notes: --- * This method always returns "FULLSCREEN" for compatibility with translated Logo code; since this module only implements `textscreen`, `fullscreen`, and `splitscreen` as no-op methods to simplify conversion, no other return value is possible. turtleMT.screenmode = function(self, ...) return "FULLSCREEN" end --- hs.canvas.turtle:turtlemode() -> string --- Method --- Returns a string describing the current turtle mode for the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * "WINDOW" --- --- Notes: --- * This method always returns "WINDOW" for compatibility with translated Logo code; since this module only implements `window`, `wrap`, and `fence` as no-op methods to simplify conversion, no other return value is possible. turtleMT.turtlemode = function(self, ...) return "WINDOW" end --- hs.canvas.turtle:pen() -> table --- Method --- Returns a table containing the pen’s position, mode, thickness, and hardware-specific characteristics. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the contents of the following as entries: --- * [hs.canvas.turtle:pendownp()](#pendownp) --- * [hs.canvas.turtle:penmode()](#penmode) --- * [hs.canvas.turtle:pensize()](#pensize) --- * [hs.canvas.turtle:pencolor()](#pencolor) --- * [hs.canvas.turtle:penpattern()](#penpattern) --- --- Notes: --- * the resulting table is suitable to be used as input to [hs.canvas.turtle:setpen](#setpen). turtleMT.pen = function(self, ...) local pendown = self:pendownp() and "PENDOWN" or "PENUP" local penmode = self:penmode() local pensize = self:pensize() local pencolor = self:pencolor() local penpattern = self:penpattern() return setmetatable({ pendown, penmode, pensize, pencolor, penpattern }, { __tostring = function(_) return string.format("{ %s, %s, %s, %s, %s }", pendown, penmode, tostring(pensize), tostring(pencolor), tostring(penpattern) ) end }) end turtleMT.penpattern = function(self, ...) return nil end --- hs.canvas.turtle:setpen(state) -> turtleViewObject --- Method --- Sets the pen’s position, mode, thickness, and hardware-dependent characteristics. --- --- Parameters: --- * `state` - a table containing the results of a previous invocation of [hs.canvas.turtle:pen](#pen). --- --- Returns: --- * the turtleViewObject turtleMT.setpen = function(self, ...) local args = table.pack(...) assert(args.n == 1, "setpen: expected only one argument") assert(type(args[1]) == "table", "setpen: expected table of pen state values") local details = args[1] assert(({ penup = true, pendown = true })[details[1]:lower()], "setpen: invalid penup/down state at index 1") assert(({ paint = true, erase = true, reverse = true })[details[2]:lower()], "setpen: invalid penmode state at index 2") assert((type(details[3]) == "table") and (#details[3] == 2) and (type(details[3][1]) == "number") and (type(details[3][2]) == "number"), "setpen: invalid pensize table at index 3") assert(({ string = true, number = true, table = true })[type(details[4])], "setpen: invalid pencolor at index 4") assert(true, "setpen: invalid penpattern at index 5") -- in case I add it turtleMT["pen" .. details[2]:lower()](self) -- penpaint, penerase, or penreverse turtleMT[details[1]:lower()](self) -- penup or pendown (has to come after mode since mode sets pendown) self:setpensize(details[3]) self:setpencolor(details[4]) self:setpenpattern(details[5]) -- its a nop currently, but we're supressing it's output message return self end --- hs.canvas.turtle:_background(func, ...) -> turtleViewObject --- Method --- Perform the specified function asynchronously as coroutine that yields after a certain number of turtle commands have been executed. This gives turtle drawing which involves many steps the appearance of being run in the background, allowing other functions within Hammerspoon the opportunity to handle callbacks, etc. --- --- Parameters: --- * `func` - the function which contains the turtle commands to be executed asynchronously. This function should expect at least 1 argument -- `self`, which will be the turtleViewObject itself, and any other arguments passed to this method. --- * `...` - optional additional arguments to be passed to `func` when it is invoked. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * If a background function is already being run on the turtle view, this method will queue the new function to be executed when the currently running function, and any previously queued functions, have completed. --- --- * Backgrounding like this may take a little longer to complete the function, but will not block Hammerspoon from completing other tasks and will make your system significantly more responsive during long running tasks. --- * See [hs.canvas.turtle:_yieldRatio](#_yieldRatio) to adjust how many turtle commands are executed before each yield. This can have an impact on the total time a function takes to complete by trading Hammerspoon responsiveness for function speed. --- * See [hs.canvas.turtle:_neverYield](#_neverYield) to prevent this behavior and cause the queued function(s) to run to completion before returning. If a function has already been backgrounded, once it resumes, the function will continue (followed by any additionally queued background functions) without further yielding. --- --- * As an example, consider this function which generates a fern frond: --- --- ``` --- fern = function(self, size, sign) --- print(size, sign) --- if (size >= 1) then --- self:forward(size):right(70 * sign) --- fern(self, size * 0.5, sign * -1) --- self:left(70 * sign):forward(size):left(70 * sign) --- fern(self, size * 0.5, sign) --- self:right(70 * sign):right(7 * sign) --- fern(self, size - 1, sign) --- self:left(7 * sign):back(size * 2) --- end --- end --- --- tc = require("hs.canvas.turtle") --- --- -- drawing the two fronds without backgrounding: --- t = os.time() --- tc1 = tc.turtleCanvas() --- tc1:penup():back(150):pendown() --- fern(tc1, 25, 1) --- fern(tc1, 25, -1) --- print("Blocked for", os.time() - t) -- 4 seconds on my machine --- --- -- drawing the two fronds with backgrounding --- -- note that if we don't hide this while its drawing, it will take significantly longer --- -- as Hammerspoon has to update the view as it's being built. With the hiding, this --- -- also took 4 seconds on my machine to complete; without, it took 24. In both cases, --- -- however, it didn't block Hammerspoon and allowed for a more responsive experience. --- t = os.time() --- tc2 = tc.turtleCanvas() --- tc2:hide():penup() --- :back(150) --- :pendown() --- :_background(fern, 25, 1) --- :_background(fern, 25, -1) --- :_background(function(self) --- self:show() --- print("Completed in", os.time() - t) --- end) --- print("Blocked for", os.time() - t) --- ``` turtleMT._background = function(self, func, ...) if not (type(func) == "function" or (getmetatable(func) or {}).__call) then error("expected function for argument 1", 2) end local runner = _backgroundQueues[self] or { queue = {} } table.insert(runner.queue, fnutils.partial(func, self, ...)) if not runner.ourCoroutine then _backgroundQueues[self] = runner runner.ourCoroutine = coroutine.wrap(function() while #runner.queue ~= 0 do table.remove(runner.queue, 1)() end runner.ourCoroutine = nil end) runner.ourCoroutine() end return self end turtleMT.bye = function(self, doItNoMatterWhat) local c = self:_canvas() if c then doItNoMatterWhat = doItNoMatterWhat or (c[#c].canvas == self and c[#c].id == "turtleView") if doItNoMatterWhat then if c[#c].canvas == self then c[#c].canvas = nil else for i = 1, #c, 1 do if c[i].canvas == self then c[i].canvas = nil break end end end c:delete() else log.f("bye - not a known turtle only canvas; apply delete method to parent canvas, or pass in `true` as argument to this method") end else log.f("bye - not attached to a canvas") end end turtleMT.show = function(self, doItNoMatterWhat) local c = self:_canvas() if c then doItNoMatterWhat = doItNoMatterWhat or (c[#c].canvas == self and c[#c].id == "turtleView") if doItNoMatterWhat then c:show() else log.f("show - not a known turtle only canvas; apply show method to parent canvas, or pass in `true` as argument to this method") end else log.f("show - not attached to a canvas") end return self end turtleMT.hide = function(self, doItNoMatterWhat) local c = self:_canvas() if c then doItNoMatterWhat = doItNoMatterWhat or (c[#c].canvas == self and c[#c].id == "turtleView") if doItNoMatterWhat then c:hide() else log.f("hide - not a known turtle only canvas; apply hide method to parent canvas, or pass in `true` as argument to this method") end else log.f("hide - not attached to a canvas") end return self end -- 6.1 Turtle Motion --- hs.canvas.turtle:forward(dist) -> turtleViewObject --- Method --- Moves the turtle forward in the direction that it’s facing, by the specified distance. The heading of the turtle does not change. --- --- Parameters: --- * `dist` - the distance the turtle should move forwards. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:fd(dist)` --- hs.canvas.turtle:back(dist) -> turtleViewObject --- Method --- Move the turtle backward, (i.e. opposite to the direction that it's facing) by the specified distance. The heading of the turtle does not change. --- --- Parameters: --- * `dist` - the distance the turtle should move backwards. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:bk(dist)` --- hs.canvas.turtle:left(angle) -> turtleViewObject --- Method --- Turns the turtle counterclockwise by the specified angle, measured in degrees --- --- Parameters: --- * `angle` - the number of degrees to adjust the turtle's heading counterclockwise. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:lt(angle)` --- hs.canvas.turtle:right(angle) -> turtleViewObject --- Method --- Turns the turtle clockwise by the specified angle, measured in degrees --- --- Parameters: --- * `angle` - the number of degrees to adjust the turtle's heading clockwise. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:rt(angle)` --- hs.canvas.turtle:setpos(pos) -> turtleViewObject --- Method --- Moves the turtle to an absolute position in the graphics window. Does not change the turtle's heading. --- --- Parameters: --- * `pos` - a table containing two numbers specifying the `x` and the `y` position within the turtle view to move the turtle to. (Note that this is *not* a point table with key-value pairs). --- --- Returns: --- * the turtleViewObject --- hs.canvas.turtle:setxy(x, y) -> turtleViewObject --- Method --- Moves the turtle to an absolute position in the graphics window. Does not change the turtle's heading. --- --- Parameters: --- * `x` - the x coordinate of the turtle's new position within the turtle view --- * `y` - the y coordinate of the turtle's new position within the turtle view --- --- Returns: --- * the turtleViewObject --- hs.canvas.turtle:setx(x) -> turtleViewObject --- Method --- Moves the turtle horizontally from its old position to a new absolute horizontal coordinate. Does not change the turtle's heading. --- --- Parameters: --- * `x` - the x coordinate of the turtle's new position within the turtle view --- --- Returns: --- * the turtleViewObject --- hs.canvas.turtle:sety(y) -> turtleViewObject --- Method --- Moves the turtle vertically from its old position to a new absolute vertical coordinate. Does not change the turtle's heading. --- --- Parameters: --- * `y` - the y coordinate of the turtle's new position within the turtle view --- --- Returns: --- * the turtleViewObject --- hs.canvas.turtle:setheading(angle) -> turtleViewObject --- Method --- Sets the heading of the turtle to a new absolute heading. --- --- Parameters: --- * `angle` - The heading, in degrees clockwise from the positive Y axis, of the new turtle heading. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:seth(angle)` --- hs.canvas.turtle:home() -> turtleViewObject --- Method --- Moves the turtle to the center of the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * this is equivalent to `hs.canvas.turtle:setxy(0, 0):setheading(0)`. --- * this does not change the pen state, so if the pen is currently down, a line may be drawn from the previous position to the home position. --- hs.canvas.turtle:arc(angle, radius) -> turtleViewObject --- Method --- Draws an arc of a circle, with the turtle at the center, with the specified radius, starting at the turtle’s heading and extending clockwise through the specified angle. The turtle does not move. --- --- Parameters: --- * `angle` - the number of degrees the arc should extend from the turtle's current heading. Positive numbers indicate that the arc should extend in a clockwise direction, negative numbers extend in a counter-clockwise direction. --- * `radius` - the distance from the turtle's current position that the arc should be drawn. --- --- Returns: --- * the turtleViewObject -- 6.2 Turtle Motion Queries -- pos - documented where defined -- xcor - documented where defined -- ycor - documented where defined -- heading - documented where defined -- towards - documented where defined -- scrunch - documented where defined -- 6.3 Turtle and Window Control -- showturtle - documented where defined -- hideturtle - documented where defined -- clean - documented where defined -- clearscreen - documented where defined -- wrap - no-op -- implemented, but does nothing to simplify conversion to/from logo -- window - no-op -- implemented, but does nothing to simplify conversion to/from logo -- fence - no-op -- implemented, but does nothing to simplify conversion to/from logo -- fill - not implemented at present -- filled - not implemented at present; a similar effect can be had with `:fillStart()` and `:fillEnd()` --- hs.canvas.turtle:label(text) -> turtleViewObject --- Method --- Displays a string at the turtle’s position current position in the current pen mode and color. --- --- Parameters: --- * `text` - --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * does not move the turtle --- hs.canvas.turtle:setlabelheight(height) -> turtleViewObject --- Method --- Sets the font size for text displayed with the [hs.canvas.turtle:label](#label) method. --- --- Parameters: --- * `height` - a number specifying the font size --- --- Returns: --- * the turtleViewObject -- textscreen - no-op -- implemented, but does nothing to simplify conversion to/from logo -- fullscreen - no-op -- implemented, but does nothing to simplify conversion to/from logo -- splitscreen - no-op -- implemented, but does nothing to simplify conversion to/from logo --- hs.canvas.turtle:setscrunch(xscale, yscale) -> turtleViewObject --- Method --- Adjusts the aspect ratio and scaling within the turtle view. Further turtle motion will be adjusted by multiplying the horizontal and vertical extent of the motion by the two numbers given as inputs. --- --- Parameters: --- * `xscale` - a number specifying the horizontal scaling applied to the turtle position --- * `yscale` - a number specifying the vertical scaling applied to the turtle position --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * On old CRT monitors, it was common that pixels were not exactly square and this method could be used to compensate. Now it is more commonly used to create scaling effects. -- refresh - no-op -- implemented, but does nothing to simplify conversion to/from logo -- norefresh - no-op -- implemented, but does nothing to simplify conversion to/from logo -- 6.4 Turtle and Window Queries -- shownp - documented where defined -- screenmode - documented where defined -- turtlemode - documented where defined -- labelsize - documented where defined -- 6.5 Pen and Background Control --- hs.canvas.turtle:pendown() -> turtleViewObject --- Method --- Sets the pen’s position to down so that movement methods will draw lines in the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:pd()` --- hs.canvas.turtle:penup() -> turtleViewObject --- Method --- Sets the pen’s position to up so that movement methods do not draw lines in the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:pu()` --- hs.canvas.turtle:penpaint() -> turtleViewObject --- Method --- Sets the pen’s position to DOWN and mode to PAINT. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:ppt()` --- --- * this mode is equivalent to `hs.canvas.compositeTypes.sourceOver` --- hs.canvas.turtle:penerase() -> turtleViewObject --- Method --- Sets the pen’s position to DOWN and mode to ERASE. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:pe()` --- --- * this mode is equivalent to `hs.canvas.compositeTypes.destinationOut` --- hs.canvas.turtle:penreverse() -> turtleViewObject --- Method --- Sets the pen’s position to DOWN and mode to REVERSE. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:px()` --- --- * this mode is equivalent to `hs.canvas.compositeTypes.XOR` --- hs.canvas.turtle:setpencolor(color) -> turtleViewObject --- Method --- Sets the pen color (the color the turtle draws when it moves and the pen is down). --- --- Parameters: --- * `color` - one of the following types: --- * an integer greater than or equal to 0 specifying an entry in the color palette (see [hs.canvas.turtle:setpalette](#setpalette)). If the index is outside of the defined palette, defaults to black (index entry 0). --- * a string matching one of the names of the predefined colors as described in [hs.canvas.turtle:setpalette](#setpalette). --- * a string starting with "#" followed by 6 hexadecimal digits specifying a color in the HTML style. --- * a table of 3 or 4 numbers between 0.0 and 100.0 specifying the percent saturation of red, green, blue, and optionally the alpha channel. --- * a color as defined in `hs.drawing.color` --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:setpc(color)` --- hs.canvas.turtle:setpalette(index, color) -> turtleViewObject --- Method --- Assigns the color to the palette at the given index. --- --- Parameters: --- * `index` - an integer between 8 and 255 inclusive specifying the slot within the palette to assign the specified color. --- * `color` - one of the following types: --- * an integer greater than or equal to 0 specifying an entry in the color palette (see Notes). If the index is outside the range of the defined palette, defaults to black (index entry 0). --- * a string matching one of the names of the predefined colors as described in the Notes. --- * a string starting with "#" followed by 6 hexadecimal digits specifying a color in the HTML style. --- * a table of 3 or 4 numbers between 0.0 and 100.0 specifying the percent saturation of red, green, blue, and optionally the alpha channel. --- * a color as defined in `hs.drawing.color` --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Attempting to modify color with an index of 0-7 are silently ignored. --- --- * An assigned color has no label for use when doing a string match with [hs.canvas.turtle:setpencolor](#setpencolor) or [hs.canvas.turtle:setbackground](#setbackground). Changing the assigned color to indexes 8-15 will clear the default label. --- --- * The initial palette is defined as follows: --- * 0 - "black" 1 - "blue" 2 - "green" 3 - "cyan" --- * 4 - "red" 5 - "magenta" 6 - "yellow" 7 - "white" --- * 8 - "brown" 9 - "tan" 10 - "forest" 11 - "aqua" --- * 12 - "salmon" 13 - "purple" 14 - "orange" 15 - "gray" --- hs.canvas.turtle:setpensize(size) -> turtleViewObject --- Method --- Sets the thickness of the pen. --- --- Parameters: --- * `size` - a number or table of two numbers (for horizontal and vertical thickness) specifying the size of the turtle's pen. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * this method accepts two numbers for compatibility reasons - macOS uses a square pen for drawing. -- setpenpattern - no-op -- implemented, but does nothing to simplify conversion to/from logo -- setpen - documented where defined --- hs.canvas.turtle:setbackground(color) -> turtleViewObject --- Method --- Sets the turtle view background color. --- --- Parameters: --- * `color` - one of the following types: --- * an integer greater than or equal to 0 specifying an entry in the color palette (see [hs.canvas.turtle:setpalette](#setpalette)). If the index is outside of the defined palette, defaults to black (index entry 0). --- * a string matching one of the names of the predefined colors as described in [hs.canvas.turtle:setpalette](#setpalette). --- * a string starting with "#" followed by 6 hexadecimal digits specifying a color in the HTML style. --- * a table of 3 or 4 numbers between 0.0 and 100.0 specifying the percent saturation of red, green, blue, and optionally the alpha channel. --- * a color as defined in `hs.drawing.color` --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:setbg(...)` -- 6.6 Pen Queries -- pendownp - documented where defined -- penmode - documented where defined -- pencolor - documented where defined -- palette - documented where defined -- pensize - documented where defined -- penpattern - no-op -- implemented to simplify pen and setpen, but returns nil -- pen - documented where defined -- background - documented where defined -- 6.7 Saving and Loading Pictures -- savepict - not implemented at present -- loadpict - not implemented at present -- epspict - not implemented at present; a similar function can be found with `:_image()` -- 6.8 Mouse Queries -- mousepos - not implemented at present -- clickpos - not implemented at present -- buttonp - not implemented at present -- button - not implemented at present -- Others (unique to this module) -- _background - documented where defined -- _neverYield - not implemented at present -- _yieldRatio - not implemented at present -- _pause - -- _image -- _translate -- _visibleAxes -- _turtleImage -- _turtleSize -- bye -- fillend -- fillstart -- hide -- labelfont -- setlabelfont -- show -- Internal use only, no need to fully document at present -- _appendCommand -- _canvas -- _cmdCount -- _commands -- _palette -- _fontMap = {...}, -- new -- turtleCanvas for i, v in ipairs(_wrappedCommands) do local cmdLabel, cmdNumber = v[1], i - 1 -- local synonyms = v[2] or {} if not cmdLabel:match("^_") then if not turtleMT[cmdLabel] then -- this needs "special" help not worth changing the validation code in internal.m for if cmdLabel == "setpensize" then turtleMT[cmdLabel] = function(self, ...) local args = table.pack(...) if type(args[1]) ~= "table" then args[1] = { args[1], args[1] } end local result = self:_appendCommand(cmdNumber, table.unpack(args)) if type(result) == "string" then error(result, 2) ; end coroutineFriendlyCheck(self) return result end else turtleMT[cmdLabel] = function(self, ...) local result = self:_appendCommand(cmdNumber, ...) if type(result) == "string" then error(result, 2) ; end coroutineFriendlyCheck(self) return result end end else log.wf("%s - method already defined; can't wrap", cmdLabel) end end end for k, v in pairs(_nops) do if not turtleMT[k] then turtleMT[k] = function(self, ...) if not _nops[k] then log.f("%s - method is a nop and has no effect for this implemntation", k) _nops[k] = true end return self end else log.wf("%s - method already defined; can't assign as nop", k) end end -- Return Module Object -------------------------------------------------- turtleMT.__indexLookup = turtleMT.__index turtleMT.__index = function(self, key) -- handle the methods as they are defined if turtleMT.__indexLookup[key] then return turtleMT.__indexLookup[key] end -- no "logo like" command will start with an underscore if key:match("^_") then return nil end -- all logo commands are defined as lowercase, so convert the passed in key to lower case and... local lcKey = key:lower() -- check against the defined logo methods again if turtleMT.__indexLookup[lcKey] then return turtleMT.__indexLookup[lcKey] end -- check against the synonyms for the defined logo methods that wrap _appendCommand for i,v in ipairs(_wrappedCommands) do if lcKey == v[1] then return turtleMT.__indexLookup[v[1]] end for i2, v2 in ipairs(v[2]) do if lcKey == v2 then return turtleMT.__indexLookup[v[1]] end end end -- check against the synonyms for the defined logo methods that are defined explicitly for k,v in pairs(_unwrappedSynonyms) do for i2, v2 in ipairs(v) do if lcKey == v2 then return turtleMT.__indexLookup[k] end end end return nil -- not really necessary as none is interpreted as nil, but I like to be explicit end return module
mit
wrxck/mattata
plugins/time.lua
2
3199
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local time = {} local mattata = require('mattata') local https = require('ssl.https') local url = require('socket.url') local json = require('dkjson') local setloc = require('plugins.setloc') local redis = require('libs.redis') function time:init() time.commands = mattata.commands(self.info.username):command('time'):command('t'):command('d'):command('date').table time.help = '/time [query] - Sends your time, or the time for the given location. Aliases: /t, /d, /date.' end function time:on_message(message, configuration, language) local input = mattata.input(message.text:lower()) local location = false if message.reply and not input then -- If it's used in reply to someone, we want their time instead. message.from = message.reply.from end if not input and not setloc.get_loc(message.from.id) then local success = mattata.send_force_reply(message, 'Please specify the location you would like to get the time for:') if success then local action = mattata.command_action(message.chat.id, success.result.message_id) redis:set(action, '/time') end return elseif not input then location = setloc.get_loc(message.from.id) if location then location = json.decode(location) end end if not location then local jstr, res = https.request('https://api.opencagedata.com/geocode/v1/json?key=' .. configuration.keys.location .. '&pretty=0&q=' .. url.escape(input)) if res ~= 200 then return mattata.send_reply(message, language.errors.connection) end local jdat = json.decode(jstr) if jdat.total_results == 0 then return mattata.send_reply(message, language.errors.results) end location = { ['latitude'] = jdat.results[1].geometry.lat, ['longitude'] = jdat.results[1].geometry.lng, ['address'] = jdat.results[1].formatted } end local formatted_location = string.format('%s,%s', location.latitude, location.longitude) local jstr, res = https.request('https://maps.googleapis.com/maps/api/timezone/json?location=' .. formatted_location .. '&timestamp=' .. os.time() .. '&key=' .. configuration.keys.maps) if res ~= 200 then return mattata.send_reply(message, language.errors.connection) end local jdat = json.decode(jstr) if jdat.errorMessage then local output = string.format('Error `%s: %s`', jdat.status, jdat.errorMessage) return mattata.send_message(message, output, true) end local offset = os.time() + tonumber(jdat.rawOffset) + tonumber(jdat.dstOffset) local current = os.date('%c', offset) current = current:gsub('^(%w+ %w+ %d*) (%d*:%d*:%d*) (%d+)$', '%2</b> on <b>%1 %3') -- We want the time first! local output = 'It is currently <b>%s</b> <code>[%s]</code> in %s.' output = string.format(output, current, jdat.timeZoneName, location.address) return mattata.send_reply(message, output, 'html') end return time
mit
grimreaper/ValyriaTear
dat/maps/layna_village/layna_village_center_sophia_house_script.lua
1
3928
-- Set the namespace according to the map name. local ns = {}; setmetatable(ns, {__index = _G}); layna_village_center_sophia_house_script = ns; setfenv(1, ns); -- The map name, subname and location image map_name = "Mountain Village of Layna" map_image_filename = "img/menus/locations/mountain_village.png" map_subname = "" -- The music file used as default background music on this map. -- Other musics will have to handled through scripting. music_filename = "mus/Caketown_1-OGA-mat-pablo.ogg" -- c++ objects instances local Map = {}; local ObjectManager = {}; local DialogueManager = {}; local EventManager = {}; -- the main character handler local bronann = {}; -- the main map loading code function Load(m) Map = m; ObjectManager = Map.object_supervisor; DialogueManager = Map.dialogue_supervisor; EventManager = Map.event_supervisor; Map.unlimited_stamina = true; _CreateCharacters(); _CreateObjects(); -- Set the camera focus on bronann Map:SetCamera(bronann); _CreateEvents(); _CreateZones(); -- The only entrance close door sound AudioManager:PlaySound("snd/door_close.wav"); end -- the map update function handles checks done on each game tick. function Update() -- Check whether the character is in one of the zones _CheckZones(); end -- Character creation function _CreateCharacters() bronann = CreateSprite(Map, "Bronann", 28, 15); bronann:SetDirection(hoa_map.MapMode.SOUTH); bronann:SetMovementSpeed(hoa_map.MapMode.NORMAL_SPEED); Map:AddGroundObject(bronann); end function _CreateObjects() object = {} -- Bronann's room object = CreateObject(Map, "Bed1", 34, 28); if (object ~= nil) then Map:AddGroundObject(object) end; local chest = CreateTreasure(Map, "sophia_house_chest", "Wood_Chest1", 21, 22); if (chest ~= nil) then chest:AddObject(1, 1); Map:AddGroundObject(chest); end object = CreateObject(Map, "Chair1_inverted", 31, 19); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Small Wooden Table", 34, 20); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Left Window Light", 21, 21); object:SetCollisionMask(hoa_map.MapMode.NO_COLLISION); object:SetDrawOnSecondPass(true); -- Above any other ground object if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Flower Pot2", 21, 24); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Right Window Light", 35, 21); object:SetDrawOnSecondPass(true); -- Above any other ground object object:SetCollisionMask(hoa_map.MapMode.NO_COLLISION); if (object ~= nil) then Map:AddGroundObject(object) end; end -- Creates all events and sets up the entire event sequence chain function _CreateEvents() local event = {}; local dialogue = {}; local text = {}; -- Triggered events event = hoa_map.MapTransitionEvent("exit floor", "dat/maps/layna_village/layna_village_center_map.lua", "dat/maps/layna_village/layna_village_center_script.lua", "from sophia's house"); EventManager:RegisterEvent(event); end -- zones local room_exit_zone = {}; -- Create the different map zones triggering events function _CreateZones() -- N.B.: left, right, top, bottom room_exit_zone = hoa_map.CameraZone(26, 30, 12, 13, hoa_map.MapMode.CONTEXT_01); Map:AddZone(room_exit_zone); end -- Check whether the active camera has entered a zone. To be called within Update() function _CheckZones() if (room_exit_zone:IsCameraEntering() == true) then bronann:SetMoving(false); EventManager:StartEvent("exit floor"); AudioManager:PlaySound("snd/door_open2.wav"); end end -- Map Custom functions -- Used through scripted events map_functions = { }
gpl-2.0
czlc/skynet
examples/login/gated.lua
1
2467
-- Ï൱ÓÚwatchdog local msgserver = require "snax.msgserver" local crypt = require "skynet.crypt" local skynet = require "skynet" local loginservice = tonumber(...) local server = {} local users = {} local username_map = {} local internal_id = 0 -- login server disallow multi login, so login_handler never be reentry -- call by login server -- login step 7:G1 ÊÕµ½ step 6 µÄÇëÇóºó£¬½øÐÐ C µÇ½µÄ×¼±¸¹¤×÷£¨Í¨³£ÊǼÓÔØÊý¾ÝµÈ£©£¬¼Ç¼ secret £¬²¢ÓÉ G1 ·ÖÅäÒ»¸ö subid ·µ»Ø¸ø L¡£Í¨³£ subid ¶ÔÓÚÒ»¸ö userid ÊÇΨһ²»Öظ´µÄ function server.login_handler(uid, secret) if users[uid] then error(string.format("%s is already login", uid)) end internal_id = internal_id + 1 local id = internal_id -- don't use internal_id directly local username = msgserver.username(uid, id, servername) -- you can use a pool to alloc new agent local agent = skynet.newservice "msgagent" local u = { username = username, agent = agent, uid = uid, subid = id, } -- trash subid (no used) skynet.call(agent, "lua", "login", uid, id, secret) users[uid] = u username_map[username] = u msgserver.login(username, secret) -- you should return unique subid return id end -- call by agent function server.logout_handler(uid, subid) local u = users[uid] if u then local username = msgserver.username(uid, subid, servername) assert(u.username == username) msgserver.logout(u.username) users[uid] = nil username_map[u.username] = nil skynet.call(loginservice, "lua", "logout",uid, subid) end end -- call by login server function server.kick_handler(uid, subid) local u = users[uid] if u then local username = msgserver.username(uid, subid, servername) assert(u.username == username) -- NOTICE: logout may call skynet.exit, so you should use pcall. pcall(skynet.call, u.agent, "lua", "logout") end end -- call by self (when socket disconnect) function server.disconnect_handler(username) local u = username_map[username] if u then skynet.call(u.agent, "lua", "afk") end end -- call by self (when recv a request from client) function server.request_handler(username, msg) local u = username_map[username] return skynet.tostring(skynet.rawcall(u.agent, "client", msg)) end -- call by self (when gate open) -- ×¢²á×Ô¼º¸øloginservice£¬ÕâÑùloginservice¿ÉÒÔ¸æÖªÓû§½«ÒªµÇ¼×Ô¼º function server.register_handler(name) servername = name skynet.call(loginservice, "lua", "register_gate", servername, skynet.self()) end msgserver.start(server)
mit
cpascal/skynet
lualib/sharedata/corelib.lua
64
2453
local core = require "sharedata.core" local type = type local next = next local rawget = rawget local conf = {} conf.host = { new = core.new, delete = core.delete, getref = core.getref, markdirty = core.markdirty, incref = core.incref, decref = core.decref, } local meta = {} local isdirty = core.isdirty local index = core.index local needupdate = core.needupdate local len = core.len local function findroot(self) while self.__parent do self = self.__parent end return self end local function update(root, cobj, gcobj) root.__obj = cobj root.__gcobj = gcobj local children = root.__cache if children then for k,v in pairs(children) do local pointer = index(cobj, k) if type(pointer) == "userdata" then update(v, pointer, gcobj) else children[k] = nil end end end end local function genkey(self) local key = tostring(self.__key) while self.__parent do self = self.__parent key = self.__key .. "." .. key end return key end local function getcobj(self) local obj = self.__obj if isdirty(obj) then local newobj, newtbl = needupdate(self.__gcobj) if newobj then local newgcobj = newtbl.__gcobj local root = findroot(self) update(root, newobj, newgcobj) if obj == self.__obj then error ("The key [" .. genkey(self) .. "] doesn't exist after update") end obj = self.__obj end end return obj end function meta:__index(key) local obj = getcobj(self) local v = index(obj, key) if type(v) == "userdata" then local children = self.__cache if children == nil then children = {} self.__cache = children end local r = children[key] if r then return r end r = setmetatable({ __obj = v, __gcobj = self.__gcobj, __parent = self, __key = key, }, meta) children[key] = r return r else return v end end function meta:__len() return len(getcobj(self)) end function meta:__pairs() return conf.next, self, nil end function conf.next(obj, key) local cobj = getcobj(obj) local nextkey = core.nextkey(cobj, key) if nextkey then return nextkey, obj[nextkey] end end function conf.box(obj) local gcobj = core.box(obj) return setmetatable({ __parent = false, __obj = obj, __gcobj = gcobj, __key = "", } , meta) end function conf.update(self, pointer) local cobj = self.__obj assert(isdirty(cobj), "Only dirty object can be update") core.update(self.__gcobj, pointer, { __gcobj = core.box(pointer) }) end return conf
mit
tianxiawuzhei/cocos-quick-lua
quick/welcome/src/app/scenes/ListViewEx.lua
1
2422
local ListViewEx = class("ListViewEx", cc.ui.UIListView) function ListViewEx:ctor(params) params.bgScale9 = true ListViewEx.super.ctor(self, params) self.currentIndex_ = 0 self.currentItem_ = nil self:onTouch(handler(self, self.touchCallback)) end function ListViewEx:setHighlightNode(node) self.highlightNode_ = node if node then self.container:addChild(node, -1) end end function ListViewEx:getItemCount() return #self.items_ end function ListViewEx:getCurrentIndex() return self.currentIndex_ end function ListViewEx:currentNode() return self.currentItem_ end function ListViewEx:setCurrentIndex(index) if index > 0 and index <= #self.items_ then self.currentIndex_ = index self.currentItem_ = self.items_[index] self:highlightItem_(self.currentItem_) end end function ListViewEx:setCurrentNode(item) local index = self:getItemPos(item) if item and index then self.currentIndex_ = index self.currentItem_ = item self:highlightItem_(item) end end function ListViewEx:removeCurrentItem() if self.currentItem_ then self:removeItem(self.currentItem_, true) self.currentItem_ = nil self.currentIndex_ = 0 end if #self.items_ <= 0 and self.highlightNode_ then self.highlightNode_:setVisible(false) end end function ListViewEx:touchCallback(event) if not event.listView:isItemInViewRect(event.itemPos) then return end local listView = event.listView if "clicked" == event.name then self:highlightItem_(event.item) self.currentIndex_ = event.itemPos self.currentItem_ = event.item end end -- helper function ListViewEx:highlightItem_(item) if self.highlightNode_ then self.highlightNode_:setVisible(true) local y = (self:getItemCount() - self:getItemPos(item)) * item:getContentSize().height transition.moveTo(self.highlightNode_, {time = 0.1, x = 0, y = y-4, easing = "sineOut", onComplete = function() self:elasticScroll() end}) end end return ListViewEx
mit
abbasgh12345/abbas
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
hfjgjfg/shatel
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
tianxiawuzhei/cocos-quick-lua
quick/framework/cc/ui/init.lua
10
3321
--[[ Copyright (c) 2011-2014 chukong-inc.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. ]] -------------------------------- -- @module ui -- @parent_module cc --[[-- 初始化 cc.ui 扩展 cc.ui 提供了一套 quick 专属的纯 lua UI控件模块 ]] local c = cc local ui = {} function makeUIControl_(control) cc(control) control:addComponent("components.ui.LayoutProtocol"):exportMethods() control:addComponent("components.behavior.EventProtocol"):exportMethods() control:setCascadeOpacityEnabled(true) control:setCascadeColorEnabled(true) control:addNodeEventListener(c.NODE_EVENT, function(event) if event.name == "cleanup" then control:removeAllEventListeners() end end) end function reAddUIComponent_(control) -- control:removeComponent("components.ui.LayoutProtocol") -- control:removeComponent("components.behavior.EventProtocol") print("lua remove all node listener") -- control:removeAllNodeEventListeners() control:addComponent("components.ui.LayoutProtocol"):exportMethods() control:addComponent("components.behavior.EventProtocol"):exportMethods() print("lua add node listener") control:addNodeEventListener(c.NODE_EVENT, function(event) if event.name == "cleanup" then control:removeAllEventListeners() end end) end ui.TEXT_ALIGN_LEFT = cc.TEXT_ALIGNMENT_LEFT ui.TEXT_ALIGN_CENTER = cc.TEXT_ALIGNMENT_CENTER ui.TEXT_ALIGN_RIGHT = cc.TEXT_ALIGNMENT_RIGHT ui.TEXT_VALIGN_TOP = cc.VERTICAL_TEXT_ALIGNMENT_TOP ui.TEXT_VALIGN_CENTER = cc.VERTICAL_TEXT_ALIGNMENT_CENTER ui.TEXT_VALIGN_BOTTOM = cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM ui.UIGroup = import(".UIGroup") ui.UIImage = import(".UIImage") ui.UIPushButton = import(".UIPushButton") ui.UICheckBoxButton = import(".UICheckBoxButton") ui.UICheckBoxButtonGroup = import(".UICheckBoxButtonGroup") ui.UIInput = import(".UIInput") ui.UILabel = import(".UILabel") ui.UISlider = import(".UISlider") ui.UIBoxLayout = import(".UIBoxLayout") ui.UIScrollView = import(".UIScrollView") ui.UIListView = import(".UIListView") ui.UIPageView = import(".UIPageView") ui.UILoadingBar = import(".UILoadingBar") return ui
mit
bizkut/BudakJahat
Rotations/Monk/Mistweaver/Laksweaver.lua
1
71794
local rotationName = "Laksweaver" local function createToggles() -- Define custom toggles -- Cooldown Button DPSModes = { [1] = { mode = "Auto", value = 1, overlay = "DPS Auto", tip = "Auto DPS Enabled", highlight = 0, icon = br.player.spell.tigerPalm }, [2] = { mode = "Single", value = 2, overlay = "DPS Single", tip = "Single DPS Disabled", highlight = 0, icon = br.player.spell.blackoutKick }, [3] = { mode = "Multi", value = 3, overlay = "DPS Multi", tip = "Multi DPS Enabled", highlight = 0, icon = br.player.spell.spinningCraneKick }, [4] = { mode = "Off", value = 4, overlay = "DPS Disabled", tip = "DPS Disabled", highlight = 0, icon = br.player.spell.soothingMist } }; CreateButton("DPS", 1, 0) CooldownModes = { [1] = { mode = "On", value = 1, overlay = "Cooldowns Enabled", tip = "Cooldowns will be used.", highlight = 0, icon = br.player.spell.revival }, [2] = { mode = "Off", value = 2, overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.revival } }; CreateButton("Cooldown", 2, 0) -- Defensive Button DefensiveModes = { [1] = { mode = "On", value = 1, overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 0, icon = br.player.spell.dampenHarm }, [2] = { mode = "Off", value = 2, overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.dampenHarm } }; CreateButton("Defensive", 3, 0) -- Interrupt Button InterruptModes = { [1] = { mode = "On", value = 1, overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 0, icon = br.player.spell.legSweep }, [2] = { mode = "Off", value = 2, overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.legSweep } }; CreateButton("Interrupt", 4, 0) --Detox Button DetoxModes = { [1] = { mode = "On", value = 1, overlay = "Detox Enabled", tip = "Detox Enabled", highlight = 0, icon = br.player.spell.detox }, [2] = { mode = "Off", value = 2, overlay = "Detox Disabled", tip = "Detox Disabled", highlight = 0, icon = br.player.spell.detox } }; CreateButton("Detox", 5, 0) -- DPS Button PrehotModes = { [1] = { mode = "On", value = 1, overlay = "Pre-Hot", tip = "Pre-hot Enabled", highlight = 0, icon = br.player.spell.renewingMist }, [2] = { mode = "Off", value = 3, overlay = "Pre-Hot", tip = "Pre-hots on Tank", highlight = 0, icon = br.player.spell.renewingMist } }; CreateButton("Prehot", 5, -1) end -- semi-globals local last_statue_location = { x = 0, y = 0, z = 0 } local jadeUnitsCount = 0 local jadeUnits = nil local RM_counter = 0 --------------- --- OPTIONS --- ---------------options local function createOptions() local optionTable local function rotationOptions() local section section = br.ui:createSection(br.ui.window.profile, "Key Options - 200421-0829") br.ui:createDropdownWithout(section, "DPS Key", br.dropOptions.Toggle, 6, "DPS key will override any heal/dispel logic") br.ui:createCheckbox(section, "WotC as part of DPS", "Use WotC as part of DPS key") br.ui:createDropdownWithout(section, "Heal Key", br.dropOptions.Toggle, 6, "Will ignore automated logic and heal mouseover target") br.ui:checkSectionState(section) section = br.ui:createSection(br.ui.window.profile, "Heal Options") br.ui:createSpinnerWithout(section, "Critical HP", 30, 0, 100, 5, "", "When to stop what we do, emergency heals!") br.ui:createSpinner(section, "Renewing Mist", 0, 0, 100, 1, "Health Percent to Cast At - 0 for on CD") br.ui:createSpinner(section, "Refreshing Jade Wind", 80, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "RJW Targets", 3, 1, 10, 1, "Minimum hurting friends") br.ui:createSpinner(section, "Essence Font", 80, 1, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Essence Font targets", 3, 1, 20, 5, "Number of hurt people before triggering spell") br.ui:createSpinner(section, "Essence Font delay(Upwelling)", 18, 1, 18, 5, "Delay in seconds fox max Upwelling bonus") br.ui:createSpinner(section, "Surging Mist", 70, 1, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section, "Vivify", 60, 1, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Vivify Spam", 3, 1, 20, 1, "Amount of Renewing Mists rolling before switching to vivify") br.ui:createSpinnerWithout(section, "Vivify Spam Health", 75, 1, 100, 1, "min HP to spam vivify w/RM") br.ui:createSpinner(section, "Enveloping Mist Tank", 50, 1, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section, "Enveloping Mist", 50, 1, 100, 5, "Health Percent to Cast At") -- br.ui:createCheckbox(section, "Soothing Mist Instant Cast", "Use Soothing Mist first for instant casts") br.ui:createDropdownWithout(section, "EM Casts", { "pre-soothe", "hard" }, 1, "EM Cast Mode") br.ui:createDropdownWithout(section, "Vivify Casts", { "pre-soothe", "hard" }, 1, "Vivify Cast Mode") br.ui:createSpinner(section, "Life Cocoon", 50, 1, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section, "Revival", 40, 1, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Revival Targets", 3, 1, 20, 5, "Number of hurt people before triggering spell") br.ui:createSpinner(section, "Chi Ji", 50, 1, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Chi Ji Targets", 3, 1, 20, 5, "Number of hurt people before triggering spell") br.ui:createSpinner(section, "Soothing Mist", 40, 1, 100, 5, "Health Percent to Cast At") br.ui:createCheckbox(section, "OOC Healing", "Enables/Disables out of combat healing.", 1) br.ui:createCheckbox(section, "Summon Jade Serpent", "Place statue yes/no") br.ui:checkSectionState(section) section = br.ui:createSection(br.ui.window.profile, "Fistweaving options") br.ui:createSpinnerWithout(section, "Fistweave Hots", 3, 1, 20, 5, "Num of hots before kicking") br.ui:createSpinnerWithout(section, "DPS Threshold", 40, 1, 100, 5, "Health limit where we focus on getting kicks in") br.ui:checkSectionState(section) section = br.ui:createSection(br.ui.window.profile, "Defensive Options") br.ui:createSpinner(section, "Healing Elixir /Dampen Harm / Diffuse Magic", 60, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinner(section, "Fortifying Brew", 45, 0, 100, 1, "Fortifying Brew", "Health Percent to Cast At") br.ui:createSpinner(section, "Health stone/pot", 30, 0, 100, 5, "Health Percent to Cast At") br.ui:checkSectionState(section) section = br.ui:createSection(br.ui.window.profile, "Utility Options") br.ui:createSpinner(section, "Mana Tea", 30, 1, 100, 1, "Mana to use tea at") br.ui:createCheckbox(section, "Enforce Lifecycles buff", "Ensures we only cast vivify/envelope with mana reduction buff") br.ui:createSpinner(section, "Use Revival as detox", 3, 1, 20, 5, "Number of hurt people before triggering spell") br.ui:createDropdown(section, "Tiger's Lust", { "All", "Self only", "on CD" }, 1, "Potential Tiger's lust targets") br.ui:createSpinner(section, "Auto Drink", 30, 0, 100, 5, "Mana to drink at") br.ui:createDropdown(section, "Ring of Peace", br.dropOptions.Toggle, 6, "Hold this key to cast Ring of Peace at Mouseover") br.ui:createSpinner(section, "Mana Potion", 50, 0, 100, 1, "Mana Percent to Cast At") br.ui:createSpinner(section, "Thunder Focus Tea", 50, 0, 100, 1, "Mana Percent to Cast At - 0 for on CD") br.ui:createDropdownWithout(section, "Thunder Focus Mode", { "Auto", "Enveloping M", "Renewing M", "Vivify", "Rising Sun Kick" }, 1, "", "") br.ui:checkSectionState(section) section = br.ui:createSection(br.ui.window.profile, "DPS") br.ui:createCheckbox(section, "Crackling Jade Lightning", "Enables" .. "/" .. "Disables " .. "the use of Crackling Jade Lightning.") br.ui:createCheckbox(section, "Rising Sun Kick", "Enables" .. "/" .. "Disables " .. " use of Rising Sun Kick on DPS rotation") br.ui:createCheckbox(section, "Spinning Crane Kick", "Enables" .. "/" .. "Disables " .. " use of Spinning Crane Kick on DPS rotation") br.ui:createCheckbox(section, "ChiBurst/ChiWave", "Enables" .. "/" .. "Disables " .. "use of ChiBurst/ChiWave as part of DPS rotation") br.ui:checkSectionState(section) section = br.ui:createSection(br.ui.window.profile, "M+") br.ui:createSpinner(section, "Bursting", 1, 0, 10, 4, "", "Burst Targets") br.ui:createCheckbox(section, "Temple of Seth heal logic", 1) br.ui:createCheckbox(section, "Freehold - pig", 1) br.ui:createCheckbox(section, "Grievous Wounds", "Grievous support") br.ui:checkSectionState(section) -- Trinkets section = br.ui:createSection(br.ui.window.profile, "Trinkets") br.ui:createSpinner(section, "Trinket 1", 70, 0, 100, 5, "Percent to Cast At") br.ui:createSpinnerWithout(section, "Min Trinket 1 Targets", 3, 1, 40, 1, "", "Minimum Trinket 1 Targets(This includes you)", true) br.ui:createDropdownWithout(section, "Trinket 1 Mode", { "Normal", "Target", "Ground", "Pocket-Sized CP", "Mana" }, 1, "", "") br.ui:createSpinner(section, "Trinket 2", 70, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Min Trinket 2 Targets", 3, 1, 40, 1, "", "Minimum Trinket 2 Targets(This includes you)", true) br.ui:createDropdownWithout(section, "Trinket 2 Mode", { "|cffFFFFFFNormal", "|cffFFFFFFTarget", "|cffFFFFFFGround", "|cffFFFFFFPocket-Sized CP", "DPS target" }, 1, "", "") br.ui:checkSectionState(section) section = br.ui:createSection(br.ui.window.profile, "Corruption") br.ui:createDropdownWithout(section, "Use Cloak", { "snare", "Eye", "THING", "Never" }, 4, "", "") br.ui:createSpinnerWithout(section, "Eye Stacks", 3, 1, 10, 1, "How many stacks before using cloak") br.ui:checkSectionState(section) -- Essences --"Memory of Lucid Dreams" section = br.ui:createSection(br.ui.window.profile, "Essences") br.ui:createSpinner(section, "ConcentratedFlame - Heal", 50, 0, 100, 5, "", "health to heal at") br.ui:createCheckbox(section, "ConcentratedFlame - DPS") br.ui:createSpinner(section, "Memory of Lucid Dreams", 50, 0, 100, 5, "", "mana to pop it at") br.ui:createDropdown(section, "Ever Rising Tide", { "Always", "Pair with CDs", "Based on health" }, 1, "When to use this essence") br.ui:createSpinner(section, "Ever Rising Tide - Mana", 30, 0, 100, 5, "", "min mana to use") br.ui:createSpinner(section, "Ever Rising Tide - Health", 30, 0, 100, 5, "", "health threshold to pop at") br.ui:createSpinner(section, "Well of Existence - Health", 30, 0, 100, 5, "", "health threshold to pop at") br.ui:createSpinner(section, "Seed of Eonar", 80, 0, 100, 5, "Health Percent to Cast At") br.ui:createSpinnerWithout(section, "Seed of Eonar Targets", 3, 0, 40, 1, "Minimum hurting friends") br.ui:checkSectionState(section) end optionTable = { { [1] = "Rotation Options", [2] = rotationOptions, } } return optionTable end ---------------- --- ROTATION --- ---------------- --- local function runRotation() --------------- --- Toggles --- --------------- --[[ --OBSOLETE UpdateToggle("Rotation", 0.25) UpdateToggle("Cooldown", 0.25) UpdateToggle("Defensive", 0.25) UpdateToggle("Interrupt", 0.25) UpdateToggle("Detox", 0.25) UpdateToggle("DPS", 0.25) ]] br.player.ui.mode.detox = br.data.settings[br.selectedSpec].toggles["Detox"] br.player.ui.mode.dps = br.data.settings[br.selectedSpec].toggles["DPS"] --br.player.ui.mode.prehot = br.data.settings[br.selectedSpec].toggles["prehot"] ------------- --- Locals --- -------------- --- local buff = br.player.buff local cast = br.player.cast local combatTime = getCombatTime() local cd = br.player.cd local charges = br.player.charges local debuff = br.player.debuff local drinking = getBuffRemain("player", 192002) ~= 0 or getBuffRemain("player", 167152) ~= 0 or getBuffRemain("player", 192001) ~= 0 local enemies = br.player.enemies local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), GetUnitSpeed("player") > 0 local gcd = br.player.gcd local healPot = getHealthPot() local inCombat = br.player.inCombat local inInstance = br.player.instance == "party" local inRaid = br.player.instance == "raid" local level = br.player.level local BleedFriend = nil local BleedFriendCount = 0 local BleedStack = 0 local ttd = getTTD local essence = br.player.essence local mana = br.player.power.mana.percent() local mode = br.player.ui.mode local perk = br.player.perk local php = br.player.health local power, powmax, powgen = br.player.power.mana.amount(), br.player.power.mana.max(), br.player.power.mana.regen() local pullTimer = br.DBM:getPulltimer() local race = br.player.race local racial = br.player.getRacial() local spell = br.player.spell local talent = br.player.talent local ttd = getTTD local ttm = br.player.power.mana.ttm() local units = br.player.units local lowest = {} --Lowest Unit lowest.hp = br.friend[1].hp lowest.role = br.friend[1].role lowest.unit = br.friend[1].unit lowest.range = br.friend[1].range lowest.guid = br.friend[1].guid local enemies = br.player.enemies local lastSpell = lastSpellCast local resable = UnitIsPlayer("target") and UnitIsDeadOrGhost("target") and GetUnitIsFriend("target", "player") local mode = br.player.ui.mode local pullTimer = br.DBM:getPulltimer() local units = br.player.units local tanks = getTanksTable() if leftCombat == nil then leftCombat = GetTime() end if profileStop == nil then profileStop = false end units.dyn5 = units.get(5) units.dyn8 = units.get(8) units.dyn15 = units.get(15) units.dyn30 = units.get(30) units.dyn40 = units.get(40) units.dyn5AoE = units.get(5, true) units.dyn30AoE = units.get(30, true) units.dyn40AoE = units.get(40, true) enemies.yards5 = enemies.get(5) enemies.get(5, "player", false, true) enemies.yards8 = enemies.get(8) enemies.yards10 = enemies.get(10) enemies.yards15 = enemies.get(15) enemies.yards20 = enemies.get(20) enemies.yards30 = enemies.get(30) enemies.yards40 = enemies.get(40) local enemy_count_facing_5 = enemies.get(5, "player", false, true) focustea = nil --functions local function renewingMistFunc() --tanks first if getValue("Renewing Mist") == 0 then if #tanks > 0 then for i = 1, #tanks do if not buff.renewingMist.exists(tanks[i].unit) and UnitInRange(tanks[i].unit) then if cast.renewingMist(tanks[i].unit) then br.addonDebug("[RenewMist]:" .. UnitName(tanks[i].unit) .. " - RM on Tank") return true end end end end for i = 1, #br.friend do if not buff.renewingMist.exists(br.friend[i].unit) and UnitInRange(br.friend[i].unit) then if cast.renewingMist(br.friend[i].unit) then br.addonDebug("[RenewMist]:" .. UnitName(br.friend[i].unit) .. " - Auto") return true end end end end end local function hotcountFunc() local hotcounter = 0 for i = 1, #br.friend do local hotUnit = br.friend[i].unit if buff.envelopingMist.exists(hotUnit) then hotcounter = hotcounter + 1 end if buff.essenceFont.exists(hotUnit) then hotcounter = hotcounter + 1 end if buff.renewingMist.exists(hotUnit) then hotcounter = hotcounter + 1 end end return hotcounter end local function risingSunKickFunc() if cast.able.risingSunKick() and isChecked("Rising Sun Kick") then if #enemy_count_facing_5 > 0 then if (talent.risingMist and hotcountFunc() >= getValue("Fistweave Hots") or focustea == "kick" and buff.thunderFocusTea.exists() or buff.wayOfTheCrane.exists() or #br.friend == 1) then --solo play if cast.risingSunKick(units.dyn5) then br.addonDebug("Rising Sun Kick on : " .. UnitName(units.dyn5) .. " BAMF!") return true end end end end if not cast.able.risingSunKick() and getHP(br.friend[1]) > getValue("DPS Threshold") and #enemy_count_facing_5 > 0 then if cast.able.blackoutKick() and not buff.thunderFocusTea.exists() and (buff.teachingsOfTheMonastery.stack() == 1 and cd.risingSunKick.remain() < 12) or buff.teachingsOfTheMonastery.stack() == 3 then if cast.blackoutKick(units.dyn5) then return true end end if cast.able.tigerPalm() and buff.teachingsOfTheMonastery.stack() < 3 or buff.teachingsOfTheMonastery.remain() < 2 then if cast.tigerPalm(units.dyn5) then return true end end end end local function thunderFocusTea() if not cast.able.thunderFocusTea() then --not cd.thunderFocusTea.ready() or Print("I should not be here!") end -- Print(hotcountFunc()) -- auto mode if isChecked("Thunder Focus Tea") and cast.able.thunderFocusTea() and not buff.thunderFocusTea.exists() then if cast.able.envelopingMist() and getOptionValue("Thunder Focus Mode") == 1 and burst == false and getLowAllies(70) < 3 and lowest.hp < 50 or getOptionValue("Thunder Focus Mode") == 2 then focustea = "singleHeal" end if cast.able.renewingMist() and (getOptionValue("Thunder Focus Mode") == 1 and (burst == true or getLowAllies(70) > 3 and not talent.risingMist) or getOptionValue("Thunder Focus Mode") == 3) then focustea = "AOEHeal" end if getOptionValue("Thunder Focus Mode") == 1 and mana <= getValue("Thunder Focus Tea") or getOptionValue("Thunder Focus Mode") == 4 and cast.able.vivify() then focustea = "manaEffiency" end if cast.able.risingSunKick() and #enemy_count_facing_5 > 0 and (hotcountFunc() >= getValue("Fistweave Hots") and ((getOptionValue("Thunder Focus Mode") == 1 and talent.risingMist) or getOptionValue("Thunder Focus Mode") == 5)) or #br.friend == 1 then focustea = "kick" end end if focustea ~= nil and not buff.thunderFocusTea.exists() and cast.able.thunderFocusTea() then if (focustea == "singleHeal" and cast.able.envelopingMist() and getHP(healUnit) <= getValue("Enveloping Mist")) or (focustea == "AOEHeal" and cast.able.renewingMist() and getHP(br.friend[1]) <= getValue("Renewing Mist")) or (focustea == "manaEffiency" and cast.able.vivify() and getHP(br.friend[1]) < getValue("Vivify")) or (focustea == "kick" and cast.able.risingSunKick() and #enemy_count_facing_5 > 0) then if cast.thunderFocusTea() then br.addonDebug("[Thundertea]: " .. focustea) end end elseif focustea == nil then -- Print("ERROR ERROR") end -- Print("Focustea1: " .. focustea) if focustea ~= nil and buff.thunderFocusTea.exists() then if focustea == "singleHeal" then if cast.envelopingMist(lowest.unit) then return true end end if focustea == "AOEHeal" or (focustea == "kick" and #enemy_count_facing_5 == 0) then if renewingMistFunc() then return true end end if focustea == "manaEffiency" then if cast.vivify(lowest.unit) and not cast.last.vivify(1) and buff.thunderFocusTea.exists() then -- Print("[Vivify]: ......") return true end end if focustea == "kick" and #enemy_count_facing_5 > 0 and isChecked("Rising Sun Kick") then if risingSunKickFunc() then return true end end --fallback ..do SOMETHING Print("!!FALLBACK!! - Report this -" .. focustea) if renewingMistFunc() then return true end if cast.envelopingMist(lowest.unit) then return true end end --Print("really?") --return false end local function jadestatue() --Jade Statue local statue_buff_check = 0 local px, py, pz -- Print("{x=" .. last_statue_location.x .. ",y=" .. last_statue_location.y .. ",z=" .. last_statue_location.z .. "}") if cast.able.summonJadeSerpentStatue() and (GetTotemTimeLeft(1) < 100 or GetTotemTimeLeft(1) == 0 or getDistanceToObject("player", last_statue_location.x, last_statue_location.y, last_statue_location.z) > 30) then for i = 1, #br.friend do if hasBuff(198533, br.friend[i].unit) then statue_buff_check = 1 end end if statue_buff_check == 0 then if #tanks > 0 then px, py, pz = GetObjectPosition(tanks[1].unit) else px, py, pz = GetObjectPosition("player") end px = px + math.random(-2, 2) py = py + math.random(-2, 2) if castGroundAtLocation({ x = px, y = py, z = pz }, spell.summonJadeSerpentStatue) then SpellStopTargeting() last_statue_location = { x = px, y = py, z = pz } return true end end end end local function tigers_lust() -- Tiger's Lust --[[ 1 = any, 2 = self, 3 == CD]] if br.player.talent.tigersLust and br.player.cast.able.tigersLust() and isChecked("Tiger's Lust") then if getValue("Tiger's Lust") == 1 then for i = 1, #br.friend do thisUnit = br.friend[i].unit if hasNoControl(spell.tigersLust, thisUnit) then if br.player.cast.tigersLust(thisUnit) then return true end end end elseif getValue("Tiger's Lust") == 2 then if hasNoControl(spell.tigersLust, "player") then if br.player.cast.tigersLust("Player") then return true end end elseif getValue("Tiger's Lust") == 3 and GetUnitSpeed("player") > 1 then if br.player.cast.tigersLust("Player") then return true end end end end local HOJ_unitList = { [131009] = "Spirit of Gold", [134388] = "A Knot of Snakes", [129758] = "Irontide Grenadier", [313301] = "Thing From Beyond", [161895] = "More things from Beyond", } local HOJ_list = { [274400] = true, [274383] = true, [257756] = true, [276292] = true, [268273] = true, [256897] = true, [272542] = true, [272888] = true, [269266] = true, [258317] = true, [258864] = true, [259711] = true, [258917] = true, [264038] = true, [253239] = true, [269931] = true, [270084] = true, [270482] = true, [270506] = true, [270507] = true, [267433] = true, [267354] = true, [268702] = true, [268846] = true, [268865] = true, [258908] = true, [264574] = true, [272659] = true, [272655] = true, [267237] = true, [265568] = true, [277567] = true, [265540] = true } local function isCC(unit) if getOptionCheck("Don't break CCs") then return isLongTimeCCed(Unit) end return false end local function noDamageCheck(unit) if isChecked("Dont DPS spotter") and GetObjectID(unit) == 135263 then return true end if isCC(unit) then return true end if isCasting(302415, unit) then -- emmisary teleporting home return true end if hasBuff(263246, unit) then -- shields on first boss in temple return true end if hasBuff(260189, unit) then -- shields on last boss in MOTHERLODE return true end if hasBuff(261264, unit) or hasBuff(261265, unit) or hasBuff(261266, unit) then -- shields on witches in wm return true end return false --catchall end local function dps() -- Print("Number of enemies: " .. tostring(#br.enemies)) if SpecificToggle("DPS Key") and not GetCurrentKeyBoardFocus() and essence.conflict.active then if isChecked("WotC as part of DPS") then if talent.manaTea and cast.able.manaTea() and getSpellCD(216113) == 0 then if cast.manaTea() then return true end end if getSpellCD(216113) == 0 then CastSpellByID(216113, "player") return true end end end if (br.player.ui.mode.dps < 4 or buff.wayOfTheCrane.exists()) and not buff.thunderFocusTea.exists() then local dps_mode if br.player.ui.mode.dps == 1 then dps_mode = "auto" elseif br.player.ui.mode.dps == 2 then dps_mode = "single" elseif br.player.ui.mode.dps == 3 then dps_mode = "multi" end if getDistance(units.dyn5) < 5 and #enemies.yards5 > 0 then StartAttack(units.dyn5) end --Print("dps_mode: " .. dps_mode) --[[ if inCombat and (isInMelee() and getFacing("player", "target") == true) then StartAttack() end ]] --lets check for mysticTouch debuff local mysticTouchCounter = 0 if #enemies.yards8 > 0 then for i = 1, #enemies.yards8 do thisUnit = enemies.yards8[i] if not noDamageCheck(thisUnit) and (not debuff.mysticTouch.exists(thisUnit) or debuff.mysticTouch.remain(thisUnit) < 1) then mysticTouchCounter = mysticTouchCounter + 1 --Print("Counter:" .. tostring(mysticTouchCounter)) end end if br.player.ui.mode.dps ~= 2 and isChecked("Spinning Crane Kick") and not isCastingSpell(spell.spinningCraneKick) and ((mysticTouchCounter > 0 and #enemies.yards8 > 1) or #enemies.yards8 >= 4 or #enemy_count_facing_5 == 0) then if cast.spinningCraneKick() then return true end end end if #enemy_count_facing_5 > 0 and not noDamageCheck(units.dyn5) then --- single target DPS if isChecked("Rising Sun Kick") and cast.able.risingSunKick() then if risingSunKickFunc() then return true end end if (buff.teachingsOfTheMonastery.stack() == 1 and cd.risingSunKick.remain() < 12) or buff.teachingsOfTheMonastery.stack() == 3 then if cast.blackoutKick(units.dyn5) then return end end if isChecked("ChiBurst/ChiWave") then if talent.chiBurst then if cast.chiBurst("player") then return end elseif talent.chiWave then if cast.chiWave("player") then return end end end if buff.teachingsOfTheMonastery.stack() < 3 or buff.teachingsOfTheMonastery.remain() < 2 then if cast.tigerPalm(units.dyn5) then return true end end end if #enemies.yards10 == 0 and not isCastingSpell(spell.cracklingJadeLightning) and isChecked("Crackling Jade Lightning") and not isMoving("player") then if cast.cracklingJadeLightning() then return true end end end end local function high_prio() --emissary stuff removed end local function heal() local healUnit = nil local specialHeal = false local burst = false local crit_count = 0 local why = "dunno" local CurrentBleedstack = 0 --Bursting --Print("Check" ..isChecked("Bursting").."#: "..getOptionValue("Bursting")) if isChecked("Bursting") and inInstance and #tanks > 0 then local ourtank = tanks[1].unit local Burststack = getDebuffStacks(ourtank, 240443) if Burststack >= getOptionValue("Bursting") then burst = true why = "burst" else burst = false end end -- Determining heal target / healUnit if isChecked("Grievous Wounds") then for i = 1, #br.friend do local GrievUnit = br.friend[i].unit CurrentBleedstack = getDebuffStacks(GrievUnit, 240559) if getDebuffStacks(GrievUnit, 240559) > 0 then -- Print(GrievUnit.unit) BleedFriendCount = BleedFriendCount + 1 end if CurrentBleedstack > BleedStack then BleedStack = CurrentBleedstack BleedFriend = GrievUnit end end if BleedFriend ~= nil then healUnit = BleedFriend specialHeal = true why = "[GRIEVOUS]" -- Print("GrievTarget: " .. thisUnit.name) else -- No Units with Griev below 90% Health BleedStack = 99 end end -- end grievous --instance logic if inInstance and inCombat then if isChecked("Temple of Seth heal logic") and br.player.eID and br.player.eID == 2127 then for i = 1, GetObjectCountBR() do local sethObject = GetObjectWithIndex(i) if GetObjectID(sethObject) == 133392 then if getHP(sethObject) < 100 and getBuffRemain(sethObject, 274148) == 0 then healUnit = sethObject end end end if healUnit ~= nil and getHP(thisUnit) < 100 then specialHeal = true why = "Seth-Logic" end -- Jagged Nettles and Dessication logic / triad in WM and mummy dude in KR elseif (select(8, GetInstanceInfo()) == 1862 or select(8, GetInstanceInfo()) == 1762) then for i = 1, #br.friend do if getDebuffRemain(br.friend[i].unit, 260741) ~= 0 or getDebuffRemain(br.friend[i].unit, 267626) ~= 0 then healUnit = br.friend[i].unit end if healUnit ~= nil and getHP(healUnit) < 90 then specialHeal = true why = "Jagged/Dessication" end end -- Sacrifical Pits / Atal -- Devour elseif select(8, GetInstanceInfo()) == 1763 then for i = 1, #br.friend do if (getDebuffRemain(br.friend[i].unit, 255421) or getDebuffRemain(br.friend[i].unit, 255434)) ~= 0 then healUnit = br.friend[i].unit end if healUnit ~= nil and getHP(healUnit) < 90 then specialHeal = true why = "Devour" end end end end --end instance logic -- critical if burst == false and getValue("Critical HP") ~= 0 then local crit_health_base = 100 local crit_health_current = 0 for i = 1, #br.friend do if UnitInRange(br.friend[i].unit) and br.friend[i].hp <= getValue("Critical HP") then crit_count = crit_count + 1 if br.friend[i].hp < crit_health_base then crit_health_base = br.friend[i].hp healUnit = br.friend[i].unit why = "[CRITICAL]" end end if crit_count >= getOptionValue("Bursting") then burst = true why = "[GROUP CRITICAL]" end end end --single heal on mouseover target override - old "HAM" mode if SpecificToggle("Heal Key") and GetUnitExists("mouseover") then healUnit = GetUnit("mouseover") specialHeal = true why = "Heal Key" end --default healUnit rollback to whoever needs it -- for i = 1, #br.friend do if healUnit == nil then healUnit = br.friend[1].unit why = "[STD]" end --br.addonDebug("Heal Target: " .. healUnit .. " at: " .. getHP(healUnit)) --[[ --always kick with rising -- fist weaving if talent.risingMist then if lowest.hp > getValue("Critical HP") then if (buff.teachingsOfTheMonastery.stack() == 1 and cd.risingSunKick.remain() < 12) or buff.teachingsOfTheMonastery.stack() == 3 then if cast.blackoutKick(units.dyn5) then return true end end end if cast.risingSunKick(units.dyn5) then return true end end ]] --Life Cocoon if isChecked("Life Cocoon") and cast.able.lifeCocoon() and inCombat then if (isChecked("Bursting") and burst and getDebuffStacks("player", 240443) >= getOptionValue("Bursting")) or (isChecked("Grievous Wounds") and getDebuffStacks("player", 240559) > 3) then if cast.lifeCocoon("player") then br.addonDebug(tostring(burst) .. "[LifCoc]:" .. "SELF" .. " / " .. why) return true end end if isChecked("Grievous Wounds") and (getDebuffStacks(healUnit, 240559) > 3 or BleedStack == 99) or not isChecked("Grievous Wounds") then --override cause people leave settings on in non griev weeks if (getHP(healUnit) <= getValue("Life Cocoon") or specialHeal) and not buff.lifeCocoon.exists(healUnit) then if cast.lifeCocoon(healUnit) then br.addonDebug(tostring(burst) .. "[LifCoc]:" .. UnitName(healUnit) .. " / " .. why .. " HP: " .. tostring(getHP(healUnit))) -- Print("Bleedstack: " .. tostring(BleedStack)) return true end end end end -- maintain one soothing mist always, if using statue local soothing_counter = 0 if inCombat and talent.summonJadeSerpentStatue and getDistanceToObject("player", last_statue_location.x, last_statue_location.y, last_statue_location.z) < 30 then for i = 1, #br.friend do if select(7, UnitBuffID(br.friend[i].unit, 198533, "exact")) == "player" then soothing_counter = soothing_counter + 1 end --[[if buff.soothingMistJadeStatue.exists(br.friend[i].unit,"exact") then soothing_counter = soothing_counter + 1 end]] -- Print(tostring(soothing_counter)) end if soothing_counter == 0 then if cast.soothingMist(healUnit) then br.addonDebug("[Statue Soothing] HealUnit: " .. healUnit) return true end end end -- Enveloping Mist if cast.able.envelopingMist() and not cast.last.envelopingMist(1) then for i = 1, #tanks do if getHP(tanks[i].unit) <= getValue("Enveloping Mist Tank") and not buff.envelopingMist.exists(tanks[i].unit) then -- br.ui:createDropdown(section, "EM Casts", { "pre-soothe", "hard" }, 1, "EM Cast Mode") if getOptionValue("EM Casts") == 1 and not buff.soothingMist.exists(tanks[i].unit, "exact") then -- if isChecked("Soothing Mist Instant Cast") and not buff.soothingMist.exists(tanks[i].unit, "exact") then if cast.soothingMist(tanks[i].unit) then br.addonDebug("[EM-PRE]:" .. UnitName(tanks[i].unit) .. " / " .. "PRE-SOOTHE - TANK") return true end end if buff.soothingMist.exists(tanks[i].unit, "EXACT") or getOptionValue("EM Casts") == 2 then if cast.envelopingMist(tanks[i].unit) then br.addonDebug("[EM]:" .. UnitName(tanks[i].unit) .. " - EM on Tank") return true end end end end end if not isMoving("player") and cast.able.envelopingMist() and getHP(healUnit) <= getValue("Enveloping Mist") or specialHeal then if talent.lifecycle and isChecked("Enforce Lifecycles buff") and buff.lifeCyclesEnvelopingMist.exists() or not talent.lifecycle or not isChecked("Enforce Lifecycles buff") then if getOptionValue("EM Casts") == 1 and not buff.soothingMist.exists(healUnit, "exact") then -- if isChecked("Soothing Mist Instant Cast") and not isMoving("player") then if not buff.soothingMist.exists(healUnit, "exact") then if cast.soothingMist(healUnit) then br.addonDebug("[pre-soothe]:" .. UnitName(healUnit) .. " EM: " .. tostring(buff.soothingMist.exists(healUnit, "EXACT"))) return true end elseif buff.envelopingMist.remains(healUnit) < 2 and (buff.soothingMist.exists(healUnit, "EXACT")) then if cast.envelopingMist(healUnit) then br.addonDebug("[EM1]:" .. UnitName(healUnit) .. " SM: " .. tostring(buff.soothingMist.exists(healUnit, "EXACT"))) end end elseif (getOptionValue("EM Casts") == 2 or buff.soothingMist.exists(healUnit, "exact")) and buff.envelopingMist.remains(healUnit) < 2 then if cast.envelopingMist(healUnit) then br.addonDebug("[EM2]:" .. UnitName(healUnit) .. " SM: " .. tostring(buff.soothingMist.exists(healUnit, "EXACT"))) return end end end end --Revival if isChecked("Revival") and cast.able.revival() then if isChecked("Use Revival as detox") and br.player.ui.mode.detox == 1 and not cast.last.detox() and cd.detox.exists() then local detoxCounter = 0 for i = 1, #br.friend do if canDispel(br.friend[i].unit, spell.detox) and getLineOfSight(br.friend[i].unit) and getDistance(br.friend[i].unit) <= 40 then detoxCounter = detoxCounter + 1 end end if detoxCounter >= getValue("Use Revival as detox") then why = "MASS DISPEL" if cast.revival() then br.addonDebug("[Revival]:" .. why) return true end end end if getLowAllies(getValue("Revival")) >= getValue("Revival Targets") or burst then if cast.revival() then br.addonDebug(tostring(burst) .. "[Revival]:" .. UnitName(healUnit) .. " / " .. why) return end end end --vivify on targets with essence font hot if isChecked("Vivify") and cast.able.vivify() and buff.essenceFont.exists(healUnit) and getHP(healUnit) < 80 then if getOptionValue("Vivify Casts") == 1 and not buff.soothingMist.exists(healUnit, "exact") then -- if isChecked("Soothing Mist Instant Cast") and not buff.soothingMist.exists(healUnit, "EXACT") then if cast.soothingMist(healUnit) then br.addonDebug(tostring(burst) .. "[SooMist]:" .. UnitName(healUnit) .. " / " .. "FONT-BUFF") return true end elseif buff.soothingMist.exists(healUnit, "EXACT") or getOptionValue("Vivify Casts") == 2 then if cast.vivify(healUnit) then br.addonDebug(tostring(burst) .. "[Vivify]:" .. UnitName(healUnit) .. " / " .. "FONT-BUFF") return true end end end --vivify if hotcount >= 5 if isChecked("Vivify") and cast.able.vivify() and getHP(healUnit) < getValue("Vivify Spam Health") and buff.renewingMist.exists(healUnit) or specialHeal then RM_counter = 0 -- local SM_counter = 0 for i = 1, #br.friend do if buff.renewingMist.exists(br.friend[i].unit) then RM_counter = RM_counter + 1 end --[[ if buff.soothingMist.exists(br.friend[i].unit) then SM_counter = SM_counter + 1 end ]] end if RM_counter >= getValue("Vivify Spam") then -- do we have a soothing mist rolling if getOptionValue("Vivify Casts") == 1 and not buff.soothingMist.exists("player", "exact") then -- if isChecked("Soothing Mist Instant Cast") and not buff.soothingMist.exists("player", "EXACT") then if cast.soothingMist("player") then br.addonDebug("[SooMist]:" .. UnitName("player") .. " / " .. "VIVIFY-SPAM - presoothe (" .. tostring(RM_counter) .. ")") return true end end if getOptionValue("Vivify Casts") == 2 or buff.soothingMist.exists("player", "exact") then if cast.vivify("player") then br.addonDebug(tostring(burst) .. "[Vivify]:" .. UnitName("player") .. " / " .. "VIVIFY-SPAM") return true end end end end --Essence Font if isChecked("Essence Font") then if talent.upwelling and br.timer:useTimer("EssenceFont Seconds", getValue("Essence Font delay(Upwelling)")) or not talent.upwelling then if getLowAllies(getValue("Essence Font")) >= getValue("Essence Font targets") or burst then if cast.essenceFont() then br.addonDebug(tostring(burst) .. "[E-Font]:" .. UnitName(healUnit) .. " / " .. why) return true end end end end --Surging Mist if isChecked("Surging Mist") then if getHP(healUnit) <= getValue("Surging Mist") or specialHeal then if cast.surgingMist(healUnit) then br.addonDebug(tostring(burst) .. "[SurgMist]:" .. UnitName(healUnit) .. " / " .. why .. math.floor(tostring(getHP(healUnit))) .. "/ " .. getValue("Surging Mist")) return true end end end --all the channeling crap -- Vivify if not isMoving("player") and (getHP(healUnit) <= getValue("Vivify") or specialHeal) then if talent.lifecycle and isChecked("Enforce Lifecycles buff") and buff.lifeCyclesVivify.exists() or not talent.lifecycle or not isChecked("Enforce Lifecycles buff") then if getOptionValue("Vivify Casts") == 1 and not buff.soothingMist.exists(healUnit, "exact") then -- if isChecked("Soothing Mist Instant Cast") and not buff.soothingMist.exists(healUnit, "EXACT") then if cast.soothingMist(healUnit) then br.addonDebug("[pre-soothe]:" .. UnitName(healUnit) .. " - VIVIFY") return true end end if buff.soothingMist.exists(healUnit, "EXACT") or getOptionValue("Vivify Casts") == 2 then if cast.vivify(healUnit) then br.addonDebug("[Vivify]: " .. UnitName(healUnit)) return end end end end --end vivify if isChecked("Soothing Mist") and not isMoving("player") then if getHP(healUnit) <= getValue("Soothing Mist") or specialHeal then if getBuffRemain(healUnit, spell.soothingMist, "EXACT") == 0 then -- and not buff.soothingMist.exists(healUnit, "exact") then if cast.soothingMist(healUnit) then br.addonDebug("[Sooth] Fallback: " .. UnitName(healUnit)) return true end end end end -- end end --end of heal() local function cooldowns() if (SpecificToggle("Ring of Peace") and not GetCurrentKeyBoardFocus()) and isChecked("Ring of Peace") then if cast.able.ringOfPeace() then if CastSpellByName(GetSpellInfo(spell.ringOfPeace), "cursor") then return true end end end -- item support --Wraps of wrapsOfElectrostaticPotential if br.player.equiped.wrapsOfElectrostaticPotential and canUseItem(br.player.items.wrapsOfElectrostaticPotential) and ttd("target") >= 10 then if br.player.use.wrapsOfElectrostaticPotential() then br.addonDebug("Using HBracers") end end --staff of neural if br.player.equiped.neuralSynapseEnhancer and canUseItem(br.player.items.neuralSynapseEnhancer) and ttd("target") >= 15 and getDebuffStacks("player", 267034) < 2 -- not if we got stacks on last boss of shrine then if br.player.use.neuralSynapseEnhancer() then br.addonDebug("Using neuralSynapseEnhancer ") end end -- Corruption stuff -- 1 = snare 2 = eye 3 = thing 4 = never -- snare = 315176 if br.player.equiped.shroudOfResolve and canUseItem(br.player.items.shroudOfResolve) then if getValue("Use Cloak") == 1 and debuff.graspingTendrils.exists("player") or getValue("Use Cloak") == 2 and debuff.eyeOfCorruption.stack("player") >= getValue("Eye Stacks") or getValue("Use Cloak") == 3 and debuff.grandDelusions.exists("player") then if br.player.use.shroudOfResolve() then br.addonDebug("Using shroudOfResolve") end end end --jade statue if isChecked("Summon Jade Serpent") and talent.summonJadeSerpentStatue and not isMoving("player") then if jadestatue() then return true end end -- Renewing Mists if isChecked("Renewing Mist") and cast.able.renewingMist() and not cast.last.thunderFocusTea(1) and not buff.thunderFocusTea.exists() and (talent.risingMist and (cd.risingSunKick.remain() < 1.5 or cd.risingSunKick.remain() > 5) or not talent.risingMist) then if renewingMistFunc() then return true end end --Chi Ji if talent.invokeChiJiTheRedCrane and isChecked("Chi Ji") then if getLowAllies(getValue("Chi Ji")) >= getValue("Chi Ji Targets") or burst == true then if cast.invokeChiJi() then br.addonDebug(tostring(burst) .. "[ChiJi]") return true end end end --Refreshing Jade Wind if talent.refreshingJadeWind and isChecked("Refreshing Jade Wind") and cast.able.refreshingJadeWind() and not buff.refreshingJadeWind.exists() then local refreshJadeFriends = getAllies("player", 10) if #refreshJadeFriends > 0 then for i = 1, #refreshJadeFriends do jadeUnits = refreshJadeFriends[i].unit if getHP(jadeUnits) < getValue("Refreshing Jade Wind") then jadeUnitsCount = jadeUnitsCount + 1 if jadeUnitsCount >= getValue("RJW Targets") or burst then if cast.refreshingJadeWind() then br.addonDebug("[RefJade] - [" .. tostring(jadeUnitsCount) .. "/" .. tostring(getValue("RJW Targets")) .. "]") jadeUnitsCount = 0 return true end end end end end end -- Trinkets if isChecked("Trinket 1") and canUseItem(13) then if getOptionValue("Trinket 1 Mode") == 1 then if getLowAllies(getValue("Trinket 1")) >= getValue("Min Trinket 1 Targets") then useItem(13) return true end elseif getOptionValue("Trinket 1 Mode") == 2 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Trinket 1") then UseItemByName(select(1, GetInventoryItemID("player", 13)), br.friend[i].unit) return true end end elseif getOptionValue("Trinket 1 Mode") == 3 and #tanks > 0 then for i = 1, #tanks do -- get the tank's target local tankTarget = UnitTarget(tanks[i].unit) if tankTarget ~= nil then -- get players in melee range of tank's target local meleeFriends = getAllies(tankTarget, 5) -- get the best ground circle to encompass the most of them local loc = nil if #meleeFriends >= 8 then loc = getBestGroundCircleLocation(meleeFriends, 4, 6, 10) else local meleeHurt = {} for j = 1, #meleeFriends do if meleeFriends[j].hp < getValue("Trinket 1") then tinsert(meleeHurt, meleeFriends[j]) end end if #meleeHurt >= getValue("Min Trinket 1 Targets") or burst == true then loc = getBestGroundCircleLocation(meleeHurt, 2, 6, 10) end end if loc ~= nil then local px, py, pz = ObjectPosition("player") loc.z = select(3, TraceLine(loc.x, loc.y, loc.z + 5, loc.x, loc.y, loc.z - 5, 0x110)) -- Raytrace correct z, Terrain and WMO hit if loc.z ~= nil and TraceLine(px, py, pz + 2, loc.x, loc.y, loc.z + 1, 0x100010) == nil and TraceLine(loc.x, loc.y, loc.z + 4, loc.x, loc.y, loc.z, 0x1) == nil then -- Check z and LoS, ignore terrain and m2 collisions useItem(13) ClickPosition(loc.x, loc.y, loc.z) return true end end end end end end if isChecked("Trinket 2") and canUseItem(14) then if getOptionValue("Trinket 2 Mode") == 1 then if getLowAllies(getValue("Trinket 2")) >= getValue("Min Trinket 2 Targets") then useItem(14) return true end elseif getOptionValue("Trinket 2 Mode") == 2 then for i = 1, #br.friend do if br.friend[i].hp <= getValue("Trinket 2") then UseItemByName(select(1, GetInventoryItemID("player", 14)), br.friend[i].unit) return true end end elseif getOptionValue("Trinket 2 Mode") == 3 and #tanks > 0 then for i = 1, #tanks do -- get the tank's target local tankTarget = UnitTarget(tanks[i].unit) if tankTarget ~= nil then -- get players in melee range of tank's target local meleeFriends = getAllies(tankTarget, 5) -- get the best ground circle to encompass the most of them local loc = nil if #meleeFriends >= 8 then loc = getBestGroundCircleLocation(meleeFriends, 4, 6, 10) else local meleeHurt = {} for j = 1, #meleeFriends do if meleeFriends[j].hp < getValue("Trinket 2") then tinsert(meleeHurt, meleeFriends[j]) end end if #meleeHurt >= getValue("Min Trinket 2 Targets") or burst == true then loc = getBestGroundCircleLocation(meleeHurt, 2, 6, 10) end end if loc ~= nil then local px, py, pz = ObjectPosition("player") loc.z = select(3, TraceLine(loc.x, loc.y, loc.z + 5, loc.x, loc.y, loc.z - 5, 0x110)) -- Raytrace correct z, Terrain and WMO hit if loc.z ~= nil and TraceLine(px, py, pz + 2, loc.x, loc.y, loc.z + 1, 0x100010) == nil and TraceLine(loc.x, loc.y, loc.z + 4, loc.x, loc.y, loc.z, 0x1) == nil then -- Check z and LoS, ignore terrain and m2 collisions useItem(13) ClickPosition(loc.x, loc.y, loc.z) return true end end end end elseif getOptionValue("Trinket 2 Mode") == 5 then -- Generic fallback if Trinket13 ~= 168905 and Trinket13 ~= 167555 then if canUseItem(13) then useItem(13) end end if Trinket14 ~= 168905 and Trinket14 ~= 167555 then if canUseItem(14) then useItem(14) end end end end --pocket size computing device if isChecked("Trinket 1") and canUseItem(13) and getOptionValue("Trinket 1 Mode") == 4 or isChecked("Trinket 2") and canUseItem(14) and getOptionValue("Trinket 2 Mode") == 4 then local Trinket13 = GetInventoryItemID("player", 13) local Trinket14 = GetInventoryItemID("player", 14) if (Trinket13 == 167555 or Trinket14 == 167555) and lowest.hp >= 60 and ttd("target") > 10 and not isMoving("player") and not noDamageCheck("target") and not buff.innervate.exists("player") and burst == false then if canUseItem(167555) then br.player.use.pocketSizedComputationDevice() end end end -- Mana Potion if isChecked("Mana Potion") and mana <= getValue("Mana Potion") then if hasItem(152495) and canUseItem(152495) then useItem(152495) if hasItem(127835) and canUseItem(127835) then useItem(127835) end end if isChecked("Auto use Pots") and burst == true then if hasItem(169300) and canUseItem(169300) then useItem(169300) end end end -- essences/ --Essence Support if isChecked("ConcentratedFlame - Heal") and lowest.hp <= getValue("ConcentratedFlame - Heal") then if cast.concentratedFlame(lowest.unit) then return true end end if isChecked("ConcentratedFlame - DPS") and ttd("target") > 5 and not debuff.concentratedFlame.exists("target") then if cast.concentratedFlame("target") then return true end end --overchargeMana if isChecked("Ever Rising Tide") and essence.overchargeMana.active and getSpellCD(296072) <= gcd then if getOptionValue("Ever Rising Tide") == 1 then if cast.overchargeMana() then return end end if getOptionValue("Ever Rising Tide") == 2 then if cd.lifeCocoon.exists() or buff.manaTea.exists() or cd.revival.exists() or burst == true then if cast.overchargeMana() then return end end end if getOptionValue("Ever Rising Tide") == 3 then if lowest.hp < getOptionValue("Ever Rising Tide - Health") or burst == true then if cast.overchargeMana() then return end end end end --lucid dreams if isChecked("Memory of Lucid Dreams") and getSpellCD(298357) <= gcd and mana <= getValue("Memory of Lucid Dreams") then if cast.memoryOfLucidDreams() then return end end --"Well of Existence - Health" if isChecked("Well of Existence - Health") and essence.refreshment.active and getSpellCD(296197) <= gcd then if lowest.hp < getOptionValue("Well of Existence - Health") or burst == true then if cast.refreshment(lowest.unit) then return true end end end --Seed of Eonar if isChecked("Seed of Eonar") and essence.lifeBindersInvocation.active and cast.able.lifeBindersInvocation and not moving then for i = 1, #br.friend do if UnitInRange(br.friend[i].unit) then local lowHealthCandidates = getUnitsToHealAround(br.friend[i].unit, 30, getValue("Seed of Eonar"), #br.friend) if #lowHealthCandidates >= getValue("Seed of Eonar Targets") and not moving or burst == true then if cast.lifeBindersInvocation() then return true end end end end end --Mana Tea if isChecked("Mana Tea") and talent.manaTea and not buff.wayOfTheCrane.exists() then if (mana <= getValue("Mana Tea") or getValue("Mana Tea") == 0) then if cast.manaTea("player") then return end end end end local function Defensive() if useDefensive() then if isChecked("Healing Elixir /Dampen Harm / Diffuse Magic") and php <= getValue("Healing Elixir /Dampen Harm / Diffuse Magic") then --Healing Elixir if talent.healingElixir then if cast.healingElixir("player") then return true end --Dampen Harm elseif talent.dampenHarm then if cast.dampenHarm("player") then return true end elseif talent.diffuseMagic then if cast.diffuseMagic("player") then return end end end --Fortifying Brew if isChecked("Fortifying Brew") and php <= getValue("Fortifying Brew") and cd.fortifyingBrew.remain() == 0 then if cast.fortifyingBrew() then return end end --Healthstone if isChecked("Health stone/pot") and php <= getOptionValue("Health stone/pot") and inCombat and (hasHealthPot() or hasItem(5512) or hasItem(166799)) then if canUseItem(5512) then useItem(5512) elseif canUseItem(healPot) then useItem(healPot) elseif hasItem(166799) and canUseItem(166799) then useItem(166799) end end end --End defensive check if br.player.ui.mode.detox == 1 and cast.able.detox() and not cast.last.detox() then for i = 1, #br.friend do if canDispel(br.friend[i].unit, spell.detox) and (getLineOfSight(br.friend[i].unit) and getDistance(br.friend[i].unit) <= 40 or br.friend[i].unit == "player") then if cast.detox(br.friend[i].unit) then return true end end end end if tigers_lust() then return true end end -- end defensives local function interrupts() for i = 1, #enemies.yards20 do thisUnit = enemies.yards20[i] if isChecked("Paralysis") and (HOJ_unitList[GetObjectID(thisUnit)] ~= nil or HOJ_list[select(9, UnitCastingInfo(thisUnit))] ~= nil or HOJ_list[select(7, GetSpellInfo(UnitChannelInfo(thisUnit)))] ~= nil) and getBuffRemain(thisUnit, 226510) == 0 and distance <= 20 then if cast.paralysis(thisUnit) then return true end end if useInterrupts() then distance = getDistance(thisUnit) if canInterrupt(thisUnit, getOptionValue("InterruptAt")) then -- Leg Sweep if isChecked("Leg Sweep") and not isCastingSpell(spell.essenceFont) then if cast.legSweep(thisUnit) then return end end -- Paralysis if isChecked("Paralysis") and not isCastingSpell(spell.essenceFont) then if cast.paralysis(thisUnit) then return end end end end end -- End Interrupt Check end --end interrupts ----------------- --- Rotations --- ----------------- if pause(true) or IsMounted() or flying or drinking or isCastingSpell(spell.essenceFont) or isCasting(293491) or isCasting(212051) or hasBuff(250873) or hasBuff(115834) or hasBuff(58984) then return true else --------------------------------- --- Out Of Combat - Rotations --- --------------------------------- if not inCombat then --Print("test") --[[ Print("-------------") Print("My Soothe: " .. tostring(select(7, UnitBuffID("target", 115175, "exact")) == "player")) Print("My Statue: " .. tostring(select(7, UnitBuffID("target", 198533, "exact")) == "player")) Print(tostring(buff.soothingMist.exists("target","exact"))) Print(tostring(buff.soothingMist.exists("target"))) Print("Target has my sooth - method 1: " .. tostring(getBuffRemain("target", 115175, "EXACT") ~= 0)) Print("Target has my sooth - method 2: " .. tostring(buff.soothingMist.exists("target"))) Print("Target has other sooth - method 1: " .. tostring(getBuffRemain("target", 115175) ~= 0)) Print("Target has STATUE sooth - method 1: " .. tostring(getBuffRemain("target", 198533, "EXACT") ~= 0)) Print("Target has STATUE sooth - method 2: " .. tostring(getBuffRemain("target", 198533) ~= 0)) -- Print("Target has STATUE sooth - method 3 - time remains: " .. getBuffRemain("target", 198533, "player")) ]] -- Print(hotcountFunc()) --Print(tostring(mode.prehot)) if isChecked("OOC Healing") and not (IsMounted() or flying or drinking or isCastingSpell(spell.essenceFont) or isCasting(293491) or hasBuff(250873) or hasBuff(115834) or hasBuff(58984) or isLooting()) then if mode.prehot == 1 then if renewingMistFunc() then return true end end if heal() then return true end end if isChecked("Tiger's Lust") then if tigers_lust() then return true end end if isChecked("Freehold - pig") then bossHelper() end if isChecked("Auto Drink") and mana <= getOptionValue("Auto Drink") and not moving and getDebuffStacks("player", 240443) == 0 then --240443 == bursting --drink list --[[ item=65499/conjured mana cookies - TW food item=159867/rockskip-mineral-wate (alliance bfa) item=163784/seafoam-coconut-water (horde bfa) item=113509/conjured-mana-bun item=126936/sugar-crusted-fish-feast ff ]] if hasItem(65499) and canUseItem(65499) then useItem(65499) end if hasItem(113509) and canUseItem(113509) then useItem(113509) end if hasItem(159867) and canUseItem(159867) then useItem(159867) end if hasItem(163784) and canUseItem(163784) then useItem(163784) end end -- end auto-drink --ring out of combat if (SpecificToggle("Ring of Peace") and not GetCurrentKeyBoardFocus()) and isChecked("Ring of Peace") then if cast.able.ringOfPeace() then if CastSpellByName(GetSpellInfo(spell.ringOfPeace), "cursor") then return true end end end end -- end ooc --------------------------------- --- In Combat - Rotations --- --------------------------------- if inCombat then if ((talent.focusedThunder and buff.thunderFocusTea.stack == 2) or buff.thunderFocusTea.exists() or cd.thunderFocusTea.ready() or cast.last.thunderFocusTea(1) and not (buff.thunderFocusTea.stack() == 1 and talent.focusedThunder)) then if thunderFocusTea() then return true end end -- dps key if (SpecificToggle("DPS Key") and not GetCurrentKeyBoardFocus()) or (buff.wayOfTheCrane.exists() and #enemies.yards8 > 0 and getHP(healUnit) >= getValue("Critical HP")) then if dps() then return true end end if (lowest.hp > getValue("Critical HP") or lowest.unit == "player") then if Defensive() then return true end end if high_prio() then return true end if cooldowns() then return true end if interrupts() then return true end if talent.risingMist and cast.able.risingSunKick() and #enemy_count_facing_5 > 0 and isChecked("Rising Sun Kick") then risingSunKickFunc() return true end if isChecked("Freehold - pig") then bossHelper() end if heal() then return true end if dps() then return true end end end -- end pause end --end Runrotation local id = 270 if br.rotations[id] == nil then br.rotations[id] = {} end tinsert(br.rotations[id], { name = rotationName, toggles = createToggles, options = createOptions, run = runRotation, })
gpl-3.0
bigdogmat/wire
lua/wire/gates/logic.lua
18
2870
--[[ Logic Gates ]] GateActions("Logic") GateActions["not"] = { name = "Not (Invert)", inputs = { "A" }, output = function(gate, A) if (A > 0) then return 0 end return 1 end, label = function(Out, A) return "not "..A.." = "..Out end } GateActions["and"] = { name = "And (All)", inputs = { "A", "B", "C", "D", "E", "F", "G", "H" }, compact_inputs = 2, output = function(gate, ...) for k,v in ipairs({...}) do if (v) and (v <= 0) then return 0 end end return 1 end, label = function(Out, ...) local txt = "" for k,v in ipairs({...}) do if (v) then txt = txt..v.." and " end end return string.sub(txt, 1, -6).." = "..Out end } GateActions["or"] = { name = "Or (Any)", inputs = { "A", "B", "C", "D", "E", "F", "G", "H" }, compact_inputs = 2, output = function(gate, ...) for k,v in ipairs({...}) do if (v) and (v > 0) then return 1 end end return 0 end, label = function(Out, ...) local txt = "" for k,v in ipairs({...}) do if (v) then txt = txt..v.." or " end end return string.sub(txt, 1, -5).." = "..Out end } GateActions["xor"] = { name = "Exclusive Or (Odd)", inputs = { "A", "B", "C", "D", "E", "F", "G", "H" }, compact_inputs = 2, output = function(gate, ...) local result = 0 for k,v in ipairs({...}) do if (v) and (v > 0) then result = (1-result) end end return result end, label = function(Out, ...) local txt = "" for k,v in ipairs({...}) do if (v) then txt = txt..v.." xor " end end return string.sub(txt, 1, -6).." = "..Out end } GateActions["nand"] = { name = "Not And (Not All)", inputs = { "A", "B", "C", "D", "E", "F", "G", "H" }, compact_inputs = 2, output = function(gate, ...) for k,v in ipairs({...}) do if (v) and (v <= 0) then return 1 end end return 0 end, label = function(Out, ...) local txt = "" for k,v in ipairs({...}) do if (v) then txt = txt..v.." nand " end end return string.sub(txt, 1, -7).." = "..Out end } GateActions["nor"] = { name = "Not Or (None)", inputs = { "A", "B", "C", "D", "E", "F", "G", "H" }, compact_inputs = 2, output = function(gate, ...) for k,v in ipairs({...}) do if (v) and (v > 0) then return 0 end end return 1 end, label = function(Out, ...) local txt = "" for k,v in ipairs({...}) do if (v) then txt = txt..v.." nor " end end return string.sub(txt, 1, -6).." = "..Out end } GateActions["xnor"] = { name = "Exclusive Not Or (Even)", inputs = { "A", "B", "C", "D", "E", "F", "G", "H" }, compact_inputs = 2, output = function(gate, ...) local result = 1 for k,v in ipairs({...}) do if (v) and (v > 0) then result = (1-result) end end return result end, label = function(Out, ...) local txt = "" for k,v in ipairs({...}) do if (v) then txt = txt..v.." xnor " end end return string.sub(txt, 1, -7).." = "..Out end } GateActions()
apache-2.0
FireFor/RPG_Other_Dream
otherdream/AdvTiledLoader/Map.lua
1
13858
--------------------------------------------------------------------------------------------------- -- -= Map =- --------------------------------------------------------------------------------------------------- -- Setup -- Import the other classes TILED_LOADER_PATH = TILED_LOADER_PATH or ({...})[1]:gsub("[%.\\/][Mm]ap$", "") .. '.' local Tile = require( TILED_LOADER_PATH .. "Tile") local TileSet = require( TILED_LOADER_PATH .. "TileSet") local TileLayer = require( TILED_LOADER_PATH .. "TileLayer") local Object = require( TILED_LOADER_PATH .. "Object") local ObjectLayer = require( TILED_LOADER_PATH .. "ObjectLayer") -- Localize some functions so they are faster local pairs = pairs local ipairs = ipairs local assert = assert local love = love local table = table local ceil = math.ceil local floor = math.floor -- Make our map class local Map = {class = "Map"} Map.__index = Map --------------------------------------------------------------------------------------------------- -- Returns a new map function Map:new(name, width, height, tileWidth, tileHeight, orientation, properties) -- Our map local map = setmetatable({}, Map) -- Public: map.name = name or "Unnamed Nap" -- Name of the map map.width = width or 0 -- Width of the map in tiles map.height = height or 0 -- Height of the map in tiles map.tileWidth = tileWidth or 0 -- Width in pixels of each tile map.tileHeight = tileHeight or 0 -- Height in pixels of each tile map.orientation = orientation or "orthogonal" -- Type of map. "orthogonal" or "isometric" map.properties = properties or {} -- Properties of the map set by Tiled map.useSpriteBatch = true -- If true then TileLayers use sprite batches. map.visible = true -- If false then the map will not be drawn map.layers = {} -- Layers of the map indexed by name map.tilesets = {} -- Tilesets indexed by name map.tiles = {} -- Tiles indexed by id map.layerOrder = {} -- The order of the layers. Callbacks are called in this order. map.drawObjects = true -- If true then object layers will be drawn map.drawRange = {} -- Limits the drawing of tiles and objects. -- [1]:x [2]:y [3]:width [4]:height -- Private: map._widestTile = 0 -- The widest tile on the map. map._highestTile = 0 -- The tallest tile on the map. map._tileRange = {} -- The range of drawn tiles. [1]:x [2]:y [3]:width [4]:height map._previousTileRange = {} -- The previous _tileRange. If this changed then we redraw sprite batches. map._redraw = true -- If true then the map needs to redraw sprite batches. map._forceRedraw = false -- If true then the next redraw is forced map._previousUseSpriteBatch = false -- The previous useSpiteBatch. If this changed then we redraw sprite batches. map._tileClipboard = nil -- The value that stored for TileLayer:tileCopy() and TileLayer:tilePaste() -- Return the new map return map end --------------------------------------------------------------------------------------------------- -- Creates a new tileset and adds it to the map. The map will then auto-update its tiles. function Map:newTileSet(img, name, tilew, tileh, width, height, firstgid, space, marg, tprop) assert(name, "Map:newTileSet - The name parameter is invalid") self.tilesets[name] = TileSet:new(img, name, tilew, tileh, width, height, firstgid, space, marg, tprop) self:updateTiles() return self.tilesets[name] end --------------------------------------------------------------------------------------------------- -- Creates a new TileLayer and adds it to the map. The position parameter is the position to insert -- the layer into the layerOrder. function Map:newTileLayer(name, opacity, properties, position) if self.layers[name] then error( string.format("Map:newTileLayer - The layer name \"%s\" already exists.", name) ) end self.layers[name] = TileLayer:new(self, name, opacity, properties) table.insert(self.layerOrder, position or #self.layerOrder + 1, self.layers[name]) return self.layers[name] end --------------------------------------------------------------------------------------------------- -- Creates a new ObjectLayer and inserts it into the map function Map:newObjectLayer(name, color, opacity, properties, position) if self.layers[name] then error( string.format("Map:newObjectLayer - The layer name \"%s\" already exists.", name) ) end self.layers[name] = ObjectLayer:new(self, name, color, opacity, properties) table.insert(self.layerOrder, position or #self.layerOrder + 1, self.layers[name]) return self.layers[name] end --------------------------------------------------------------------------------------------------- -- Add a custom layer to the map. You can include a predefined layer table or one will be created. function Map:newCustomLayer(name, position, layer) if self.layers[name] then error( string.format("Map:newCustomLayer - The layer name \"%s\" already exists.", name) ) end self.layers[name] = layer or {name=name} self.layers[name].class = "CustomLayer" table.insert(self.layerOrder, position or #self.layerOrder + 1, self.layers[name]) return self.layers[name] end --------------------------------------------------------------------------------------------------- -- Cuts tiles out of tilesets and stores them in the tiles tables under their id -- Call this after the tilesets are set up function Map:updateTiles() self.tiles = {} self._widestTile = 0 self._highestTile = 0 for _, ts in pairs(self.tilesets) do if ts.tileWidth > self._widestTile then self._widestTile = ts.tileWidth end if ts.tileHeight > self._highestTile then self._highestTile = ts.tileHeight end for id, val in pairs(ts:getTiles()) do self.tiles[id] = val end end end --------------------------------------------------------------------------------------------------- -- Forces the map to redraw the sprite batches. function Map:forceRedraw() self._redraw = true self._forceRedraw = true end --------------------------------------------------------------------------------------------------- -- Performs a callback on all map layers. local layer function Map:callback(cb, ...) if cb == "draw" then self:_updateTileRange() end for i = 1, #self.layerOrder do layer = self.layerOrder[i] if layer[cb] then layer[cb](layer, ...) end end end --------------------------------------------------------------------------------------------------- -- Draw the map. function Map:draw() if self.visible then self:callback("draw") end end --------------------------------------------------------------------------------------------------- -- Returns the position of the layer inside the map's layerOrder. Can be the layer name or table. function Map:layerPosition(layer) if type(layer) == "string" then layer = self.layers[layer] end for i = 1,#self.layerOrder do if self.layerOrder[i] == layer then return i end end end --------------------------------------------------------------------------------------------------- -- Returns the position of the layer inside the map's layerOrder. The passed layers can be the -- layer name, the layer tables themselves, or the layer positions. function Map:swapLayers(layer1, layer2) if type(layer1) ~= "number" then layer1 = self:layerPosition(layer1) end if type(layer2) ~= "number" then layer2 = self:layerPosition(layer2) end local bubble = self.layers[layer1] self.layers[layer1] = self.layers[layer2] self.layers[layer2] = bubble end --------------------------------------------------------------------------------------------------- -- Removes a layer from the map function Map:removeLayer(layer) if type(layer) ~= "number" then layer = self:layerPosition(layer) end layer = table.remove(self.layerOrder, layer) self.layers[layer.name] = nil return layer end --------------------------------------------------------------------------------------------------- -- Turns an isometric location into a world location. The unit length for isometric tiles is always -- the map's tileHeight. This is both for width and height. local h, tw, th function Map:fromIso(x, y) h, tw, th = self.height, self.tileWidth, self.tileHeight return ((x-y)/th + h - 1)*tw/2, (x+y)/2 end --------------------------------------------------------------------------------------------------- -- Turns a world location into an isometric location local ix, iy function Map:toIso(a, b) a, b = a or 0, b or 0 h, tw, th = self.height, self.tileWidth, self.tileHeight ix = b - (h-1)*th/2 + (a*th)/tw iy = 2*b - ix return ix, iy end --------------------------------------------------------------------------------------------------- -- Sets the draw range function Map:setDrawRange(x,y,w,h) self.drawRange[1], self.drawRange[2], self.drawRange[3], self.drawRange[4] = x, y, w, h end --------------------------------------------------------------------------------------------------- -- Gets the draw range function Map:getDrawRange() return self.drawRange[1], self.drawRange[2], self.drawRange[3], self.drawRange[4] end --------------------------------------------------------------------------------------------------- -- Automatically sets the draw range to fit the display function Map:autoDrawRange(tx, ty, scale, pad) tx, ty, scale, pad = tx or 0, ty or 0, scale or 1, pad or 0 if scale > 0.001 then self:setDrawRange(-tx-pad,-ty-pad,love.graphics.getWidth()/scale+pad*2, love.graphics.getHeight()/scale+pad*2) end end ---------------------------------------------------------------------------------------------------- -- Private Functions ---------------------------------------------------------------------------------------------------- -- This is an internal function used to update the map's _tileRange, _previousTileRange, and -- _specialRedraw local x1, y1, x2, y2, highOffset, widthOffset, tr, ptr function Map:_updateTileRange() -- Offset to make sure we can always draw the highest and widest tile heightOffset = self._highestTile - self.tileHeight widthOffset = self._widestTile - self.tileWidth -- Set the previous tile range for i=1,4 do self._previousTileRange[i] = self._tileRange[i] end -- Get the draw range. We will replace these values with the tile range. x1, y1, x2, y2 = self.drawRange[1], self.drawRange[2], self.drawRange[3], self.drawRange[4] -- Calculate the _tileRange for orthogonal tiles if self.orientation == "orthogonal" then -- Limit the drawing range. We must make sure we can draw the tiles that are bigger -- than the self's tileWidth and tileHeight. if x1 and y1 and x2 and y2 then x2 = ceil(x2/self.tileWidth) y2 = ceil((y2+heightOffset)/self.tileHeight) x1 = floor((x1-widthOffset)/self.tileWidth) y1 = floor(y1/self.tileHeight) -- Make sure that we stay within the boundry of the map x1 = x1 > 0 and x1 or 0 y1 = y1 > 0 and y1 or 0 x2 = x2 < self.width and x2 or self.width - 1 y2 = y2 < self.height and y2 or self.height - 1 else -- If the drawing range isn't defined then we draw all the tiles x1, y1, x2, y2 = 0, 0, self.width-1, self.height-1 end -- Calculate the _tileRange for isometric tiles. else -- If the drawRange is set if x1 and y1 and x2 and y2 then x1, y1 = self:toIso(x1-self._widestTile,y1) x1, y1 = ceil(x1/self.tileHeight), ceil(y1/self.tileHeight)-1 x2 = ceil((x2+self._widestTile)/self.tileWidth) y2 = ceil((y2+heightOffset)/self.tileHeight) -- else draw everything else x1 = 0 y1 = 0 x2 = self.width - 1 y2 = self.height - 1 end end -- Assign the new values to the tile range tr, ptr = self._tileRange, self._previousTileRange tr[1], tr[2], tr[3], tr[4] = x1, y1, x2, y2 -- If the tile range or useSpriteBatch is different than the last frame then we need to -- update sprite batches. self._redraw = self.useSpriteBatch ~= self._previousUseSpriteBatch or self._forceRedraw or tr[1] ~= ptr[1] or tr[2] ~= ptr[2] or tr[3] ~= ptr[3] or tr[4] ~= ptr[4] -- Set the previous useSpritebatch self._previousUseSpriteBatch = self.useSpriteBatch -- Reset the forced special redraw self._forceRedraw = false end --------------------------------------------------------------------------------------------------- -- Calling the map as a function will return the layer function Map:__call(layerName) return self.layers[layerName] end --------------------------------------------------------------------------------------------------- -- Returns the Map class return Map --[[Copyright (c) 2011-2012 Casey Baxter 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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.--]]
unlicense
mahdikord/baran
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0