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
liruqi/bigfoot
Interface/AddOns/DBM-Party-MoP/ShadoPanMonastery/GuCloudstrike.lua
1
4251
local mod = DBM:NewMod(673, "DBM-Party-MoP", 3, 312) local L = mod:GetLocalizedStrings() local sndWOP = mod:SoundMM("SoundWOP") mod:SetRevision(("$Revision: 10172 $"):sub(12, -3)) mod:SetCreatureID(56747)--56747 (Gu Cloudstrike), 56754 (Azure Serpent) mod:SetZone() mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_AURA_APPLIED", "SPELL_DAMAGE", "SPELL_MISSED", "SPELL_CAST_START", "UNIT_DIED" ) local warnInvokeLightning = mod:NewSpellAnnounce(106984, 2, nil, false) local warnStaticField = mod:NewAnnounce("warnStaticField", 3, 106923)--Target scanning verified working local warnChargingSoul = mod:NewSpellAnnounce(110945, 3)--Phase 2 local warnLightningBreath = mod:NewSpellAnnounce(102573, 3) local warnMagneticShroud = mod:NewSpellAnnounce(107140, 4) local warnOverchargedSoul = mod:NewSpellAnnounce(110852, 3)--Phase 3 local specWarnStaticField = mod:NewSpecialWarningMove(106923) local specWarnStaticFieldNear = mod:NewSpecialWarningClose(106923) local yellStaticField = mod:NewYell(106923) local specWarnMagneticShroud = mod:NewSpecialWarningSpell(107140) local timerInvokeLightningCD = mod:NewNextTimer(6, 106984)--Phase 1 ability local timerStaticFieldCD = mod:NewNextTimer(8, 106923)--^^ local timerLightningBreathCD = mod:NewNextTimer(9.7, 102573)--Phase 2 ability local timerMagneticShroudCD = mod:NewCDTimer(12.5, 107140)--^^ local staticFieldText = GetSpellInfo(106923) -- very poor code. not clean. (to replace %%s -> %s) local targetFormatText do local originalText = DBM_CORE_AUTO_ANNOUNCE_TEXTS.target local startIndex = string.find(originalText, "%%%%") local tmp1 = string.sub(originalText, 1, startIndex) local tmp2 = string.sub(originalText, startIndex+2) targetFormatText = tmp1..tmp2 end function mod:StaticFieldTarget(targetname, uId) if not targetname then--No one is targeting/focusing the cloud serpent, so just use generic warning staticFieldText = GetSpellInfo(106923) warnStaticField:Show(staticFieldText) else--We have a valid target, so use target warnings. staticFieldText = targetFormatText:format(GetSpellInfo(106923), targetname) warnStaticField:Show(staticFieldText) if targetname == UnitName("player") then specWarnStaticField:Show() yellStaticField:Yell() sndWOP:Play("runaway")--快躲開 else if uId then local inRange = DBM.RangeCheck:GetDistance("player", uId) if inRange and inRange < 6 then specWarnStaticFieldNear:Show(targetname) sndWOP:Play("runaway")--快躲開 end end end end end function mod:OnCombatStart(delay) timerInvokeLightningCD:Start(-delay) timerStaticFieldCD:Start(18-delay) end function mod:SPELL_AURA_APPLIED(args) if args.spellId == 110945 then warnChargingSoul:Show() warnInvokeLightning:Cancel() timerStaticFieldCD:Cancel() timerLightningBreathCD:Start() timerMagneticShroudCD:Start(20) elseif args.spellId == 110852 then warnOverchargedSoul:Show() end end function mod:SPELL_AURA_REMOVED(args) if args.spellId == 110945 then warnInvokeLightning:Cancel() timerStaticFieldCD:Cancel() end end function mod:SPELL_CAST_START(args) if args.spellId == 106923 then self:BossTargetScanner(56754, "StaticFieldTarget", 0.05, 20) timerStaticFieldCD:Start() elseif args.spellId == 106984 then warnInvokeLightning:Show() timerInvokeLightningCD:Start() elseif args.spellId == 102573 then warnLightningBreath:Show() timerLightningBreathCD:Start() elseif args.spellId == 107140 then warnMagneticShroud:Show() specWarnMagneticShroud:Show() if mod:IsHealer() then sndWOP:Play("healall")--注意群療 end timerMagneticShroudCD:Start() end end function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 56754 then timerMagneticShroudCD:Cancel() timerStaticFieldCD:Cancel() timerLightningBreathCD:Cancel() end end function mod:SPELL_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId) if spellId == 128889 and destGUID == UnitGUID("player") and self:AntiSpam() then sndWOP:Play("runaway")--快躲開 specWarnStaticField:Show() end end mod.SPELL_MISSED = mod.SPELL_DAMAGE
mit
DavidAlphaFox/wax
lib/stdlib/luaspec/luaspec.lua
19
9172
spec = { contexts = {}, passed = 0, failed = 0, pending = 0, current = nil } Report = {} Report.__index = Report function Report:new(spec) local report = { num_passed = spec.passed, num_failed = spec.failed, num_pending = spec.pending, total = spec.passed + spec.failed + spec.pending, results = {} } report.percent = report.num_passed/report.total*100 local contexts = spec.contexts for index = 1, #contexts do report.results[index] = { name = contexts[index], spec_results = contexts[contexts[index]] } end return report end function spec:report(verbose) local report = Report:new(self) if report.num_failed ~= 0 or verbose then for i, result in pairs(report.results) do print(("\n%s\n================================"):format(result.name)) for description, r in pairs(result.spec_results) do local outcome = r.passed and 'pass' or "FAILED" if verbose or not (verbose and r.passed) then print(("%-70s [ %s ]"):format(" - " .. description, outcome)) table.foreach(r.errors, function(index, error) print(" " .. index ..". Failed expectation : " .. error.message .. "\n "..error.trace) end) end end end end local summary = [[ ========== %s ============= %s Failed %s Passed -------------------------------- %s Run, %.2f%% Success rate ]] print(summary:format(report.num_failed == 0 and "Success" or "Failure", report.num_failed, report.num_passed, report.total, report.percent)) end function spec:add_results(success, message, trace) if self.current.passed then self.current.passed = success end if success then self.passed = self.passed + 1 else table.insert(self.current.errors, { message = message, trace = trace }) self.failed = self.failed + 1 end end function spec:add_context(name) self.contexts[#self.contexts+1] = name self.contexts[name] = {} end function spec:add_spec(context_name, spec_name) local context = self.contexts[context_name] context[spec_name] = { passed = true, errors = {} } self.current = context[spec_name] end function spec:add_pending_spec(context_name, spec_name, pending_description) end -- create tables to support pending specifications local pending = {} function pending.__newindex() error("You can't set properties on pending") end function pending.__index(_, key) if key == "description" then return nil else error("You can't get properties on pending") end end function pending.__call(_, description) local o = { description = description} setmetatable(o, pending) return o end setmetatable(pending, pending) -- -- define matchers matchers = { should_be = function(value, expected) if value ~= expected then return false, "expecting "..tostring(expected)..", not ".. tostring(value) end return true end; should_not_be = function(value, expected) if value == expected then return false, "should not be "..tostring(value) end return true end; should_be_greater_than = function(value, expected) if expected >= value then return false, "got " .. tostring(value) .. " expecting value > " .. tostring(expected) end return true end; should_be_less_than = function(value, expected) if expected <= value then return false, "got " .. tostring(value) .. " expecting value < " .. tostring(expected) end return true end; should_error = function(f) if pcall(f) then return false, "expecting an error but received none" end return true end; should_match = function(value, pattern) if type(value) ~= 'string' then return false, "type error, should_match expecting target as string" end if not string.match(value, pattern) then return false, value .. "doesn't match pattern ".. pattern end return true end; should_be_kind_of = function(value, class) if type(value) == "userdata" then if not value:isKindOfClass(class) then return false, tostring(value) .. " is not a " .. tostring(class) end elseif type(value) ~= class then return false, type(value) .. " is not a " .. tostring(class) end return true end; should_exist = function(value) if not value then return false, tostring(value) .. " evaluates to false." else return true end end; should_not_exist = function(value) if value then return false, value .. " evaluates to true." else return true end end; } matchers.should_equal = matchers.should_be -- -- expect returns an empty table with a 'method missing' metatable -- which looks up the matcher. The 'method missing' function -- runs the matcher and records the result in the current spec local function expect(target) return setmetatable({}, { __index = function(_, matcher) return function(...) local success, message = matchers[matcher](target, ...) spec:add_results(success, message, debug.traceback()) end end }) end -- Context = {} Context.__index = Context function Context:new(context) for i, child in ipairs(context.children) do child.parent = context end return setmetatable(context, self) end function Context:run_befores(env) if self.parent then self.parent:run_befores(env) end if self.before then setfenv(self.before, env) self.before() end end function Context:run_afters(env) if self.after then setfenv(self.after, env) self.after() end if self.parent then self.parent:run_afters(env) end end function Context:run() -- run all specs for spec_name, spec_func in pairs(self.specs) do if getmetatable(spec_func) == pending then else spec:add_spec(self.name, spec_name) local mocks = {} -- setup the environment that the spec is run in, each spec is run in a new environment local env = { track_error = function(f) local status, err = pcall(f) return err end, expect = expect, mock = function(table, key, mock_value) mocks[{ table = table, key = key }] = table[key] -- store the old value table[key] = mock_value or Mock:new() return table[key] end } setmetatable(env, { __index = _G }) -- run each spec with proper befores and afters self:run_befores(env) setfenv(spec_func, env) local message local traceback local success = xpcall(spec_func, function(err) message = err traceback = debug.traceback("", 2) end) self:run_afters(env) if not success then io.write("x") spec:add_results(false, message, traceback) else io.write(".") end io.flush() -- restore stored values for mocks for key, old_value in pairs(mocks) do key.table[key.key] = old_value end end end for i, child in pairs(self.children) do child:run() end end -- dsl for creating contexts local function make_it_table() -- create and set metatables for 'it' local specs = {} local it = {} setmetatable(it, { -- this is called when it is assigned a function (e.g. it["spec name"] = function() ...) __newindex = function(_, spec_name, spec_function) specs[spec_name] = spec_function end }) return it, specs end local make_describe_table -- create an environment to run a context function in as well as the tables to collect -- the subcontexts and specs local function create_context_env() local it, specs = make_it_table() local describe, sub_contexts = make_describe_table() -- create an environment to run the function in local context_env = { it = it, describe = describe, pending = pending } return context_env, sub_contexts, specs end -- Note: this is declared locally earlier so it is still local function make_describe_table(auto_run) local describe = {} local contexts = {} local describe_mt = { -- This function is called when a function is assigned to a describe table -- (e.g. describe["context name"] = function() ...) __newindex = function(_, context_name, context_function) spec:add_context(context_name) local context_env, sub_contexts, specs = create_context_env() -- set the environment setfenv(context_function, context_env) -- run the context function which collects the data into context_env and sub_contexts context_function() -- store the describe function in contexts contexts[#contexts+1] = Context:new { name = context_name, before = context_env.before, after = context_env.after, specs = specs, children = sub_contexts } if auto_run then contexts[#contexts]:run() end end } setmetatable(describe, describe_mt) return describe, contexts end describe = make_describe_table(true)
mit
ingran/balzac
custom_feeds/teltonika_luci/applications/luci-ntpc/luasrc/model/cbi/ntpc/ntpc.lua
1
6152
--[[ 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: ntpc.lua 6065 2010-04-14 11:36:13Z ben $ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") local utl = require "luci.util" local sys = require "luci.sys" local has_gps = utl.trim(luci.sys.exec("uci get hwinfo.hwinfo.gps")) local port local function cecho(string) luci.sys.call("echo \"" .. string .. "\" >> /tmp/log.log") end m = Map("ntpclient", translate("Time Synchronisation"), translate("")) --------- General s = m:section(TypedSection, "ntpclient", translate("General")) s.anonymous = true s.addremove = false --s:option(DummyValue, "_time", translate("Current system time")).value = os.date("%c") o = s:option(DummyValue, "_time", translate("Current system time"), translate("Device\\'s current system time. Format [year-month-day, hours:minutes:seconds]")) o.template = "admin_system/clock_status" local tzone = s:option(ListValue, "zoneName", translate("Time zone"), translate("Time zone of your country")) tzone:value(translate("UTC")) for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tzone:value(zone[1]) end function tzone.write(self, section, value) local cfgName local cfgTimezone Value.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end m.uci:foreach("system", "system", function(s) cfgName = s[".name"] cfgTimezone = s.timezone end) local timezone = lookup_zone(value) or "GMT0" m.uci:set("system", cfgName, "timezone", timezone) m.uci:save("system") m.uci:commit("system") luci.fs.writefile("/etc/TZ", timezone .. "\n") end s:option(Flag, "enabled", translate("Enable NTP"), translate("Enable system\\'s time synchronization with time server using NTP (Network Time Protocol)")) el1 = s:option(Value, "interval", translate("Update interval (in seconds)"), translate("How often the router should update system\\'s time")) el1.rmempty = true el1.datatype = "integer" el = s:option(Value, "save", translate("Save time to flash"), translate("Save last synchronized time to flash memory")) el.template = "cbi/flag" function el1.validate(self, value, section) aaa=luci.http.formvalue("cbid.ntpclient.cfg0c8036.save") if tonumber(aaa) == 1 then if tonumber(value) >= 3600 then return value else return nil, "The value is invalid because min value 3600" end else if tonumber(value) >= 10 then return value else return nil, "The value is invalid because min value 10" end end end a = s:option(Value, "count", translate("Count of time synchronizations"), translate("How many time synchronizations NTP (Network Time Protocol) client should perform. Empty value - infinite")) a.datatype = "fieldvalidation('^[0-9]+$',0)" a.rmempty = true ------ GPS synchronisation if has_gps == "1" then gps = s:option(Flag, "gps_sync", translate("GPS synchronization"), translate("Enable periodic time synchronization of the system, using GPS module (does not require internet connection)")) gps_int = s:option(ListValue, "gps_interval", translate("GPS time update interval"), translate("Update period for updating system time from GPS module")) gps_int:value("1", translate("Every 5 minutes")) gps_int:value("2", translate("Every 30 minutes")) gps_int:value("3", translate("Every hour")) gps_int:value("4", translate("Every 6 hours")) gps_int:value("5", translate("Every 12 hours")) gps_int:value("6", translate("Every 24 hours")) gps_int:value("7", translate("Every week")) gps_int:value("8", translate("Every month")) gps_int:depends("gps_sync", "1") gps_int.default = "6" gps_int.rmempty = true gps_int.datatype = "integer" end ------- Clock Adjustment s2 = m:section(TypedSection, "ntpdrift", translate("Clock Adjustment")) s2.anonymous = true s2.addremove = false b = s2:option(Value, "freq", translate("Offset frequency"), translate("Adjust the drift of the local clock to make it run more accurately")) b.datatype = "fieldvalidation('^[0-9]+$',0)" b.rmempty = true function m.on_after_commit(self) luci.sys.call("export ACTION=ifdown; sh /etc/hotplug.d/iface/20-ntpclient") luci.sys.call("export ACTION=; sh /etc/hotplug.d/iface/20-ntpclient") if has_gps == "1" then local gps_service_enabled = utl.trim(luci.sys.exec("uci get gps.gps.enabled")) local gps_sync_enabled = utl.trim(luci.sys.exec("uci get ntpclient.@ntpclient[0].gps_sync")) local gps_sync_period = utl.trim(luci.sys.exec("uci get ntpclient.@ntpclient[0].gps_interval")) luci.sys.exec('sed -i "/gps_time_sync.sh/d" /etc/crontabs/root') if gps_sync_enabled == "1" then cron_conf = io.open("/etc/crontabs/root", "a") if gps_sync_period == "1" then cron_conf:write("*/5 * * * * /sbin/gps_time_sync.sh") --every 5 min elseif gps_sync_period == "2" then cron_conf:write("*/30 * * * * /sbin/gps_time_sync.sh") --every 30 min elseif gps_sync_period == "3" then cron_conf:write("0 * * * * /sbin/gps_time_sync.sh") --every hour elseif gps_sync_period == "4" then cron_conf:write("* */6 * * * /sbin/gps_time_sync.sh") --every 6 hours elseif gps_sync_period == "5" then cron_conf:write("* */12 * * * /sbin/gps_time_sync.sh") -- every 12 hours elseif gps_sync_period == "6" then cron_conf:write("0 0 * * * /sbin/gps_time_sync.sh") -- every 24h (day) elseif gps_sync_period == "7" then cron_conf:write("* * * * 0 /sbin/gps_time_sync.sh") --every week elseif gps_sync_period == "8" then cron_conf:write("0 0 1 * * /sbin/gps_time_sync.sh") --every month end cron_conf:close() if gps_service_enabled ~= "1" then luci.sys.exec("uci set gps.gps.enabled='1'") luci.sys.exec("uci commit gps") luci.sys.exec("/sbin/luci-reload") end end end end return m
gpl-2.0
Admicos/luapp
test.lua
1
6049
--luapp test local function _split(str, splitter) local t = {} local function helper(line) table.insert(t, line) return "" end helper((str:gsub("(.-)" .. splitter, helper))) return t end local function runShellProgramWithErrors(program, arg) local path = shell.resolveProgram(program) local prog = loadfile(path) local args = _split(arg, " ") setfenv(prog, setmetatable({shell = shell, multishell = multishell}, {__index = _G})) return assert(prog)(table.unpack(args)) end local tests = { buildyourself = function() shell.run(".test/luapp -o .test/luapp_b luapp.lua -s") return {".test/luapp_b", ".test/luapp"} end; buildalog = function() --TODO: find repo contents automatically fs.makeDir(".test/alog") local _lpp = http.get("https://raw.githubusercontent.com/Admicos/alog/master/alog.lua") local _lpp_f = fs.open(shell.resolve(".test/alog/alog.lua"), "w") _lpp_f.write(_lpp.readAll()) _lpp_f.close() _lpp.close() fs.makeDir(".test/alog/inc") local _lpp = http.get("https://raw.githubusercontent.com/Admicos/alog/master/inc/pads.lua") local _lpp_f = fs.open(shell.resolve(".test/alog/inc/pads.lua"), "w") _lpp_f.write(_lpp.readAll()) _lpp_f.close() _lpp.close() local _lpp = http.get("https://raw.githubusercontent.com/Admicos/alog/master/inc/logHandle.lua") local _lpp_f = fs.open(shell.resolve(".test/alog/inc/logHandle.lua"), "w") _lpp_f.write(_lpp.readAll()) _lpp_f.close() _lpp.close() shell.run("cd .test/alog/") shell.run("../../luapp_build -o ../alogtest alog.lua -s") shell.run("../luapp -o ../alogtest_b alog.lua -s") shell.run("cd ../../") return {".test/alogtest", ".test/alogtest_b"} end; iftest = function() shell.run("luapp_build -o .test/iftest tests/iftest.lua -s") shell.run(".test/luapp -o .test/iftest_b tests/iftest.lua -s") return {".test/iftest_b", ".test/iftest"} end; definetest = function() shell.run("luapp_build -o .test/definetest tests/definetest.lua -s") shell.run(".test/luapp -o .test/definetest_b tests/definetest.lua -s") return {".test/definetest_b", ".test/definetest"} end; includetest = function() shell.run("luapp_build -o .test/includetest tests/includetest.lua -s") shell.run(".test/luapp -o .test/includetest_b tests/includetest.lua -s") return {".test/includetest_b", ".test/includetest"} end; versioncheck_newer = function() local ok, err = pcall(runShellProgramWithErrors, ".test/luapp", "-o .test/versioncheck_newer_b tests/versioncheck_newer.lua -s") if not ok then --Successful without creating a file so we just return the --Already existing test file twice to make it pass return {"tests/versioncheck_newer.lua", "tests/versioncheck_newer.lua"} end return {"tests/versioncheck_newer.lua", "tests/versioncheck_older.lua"} end; versioncheck_older = function() local ok, err = pcall(runShellProgramWithErrors, ".test/luapp", "-o .test/versioncheck_older_b tests/versioncheck_older.lua -s") if ok then --Successful without creating a file so we just return the --Already existing test file twice to make it pass return {"tests/versioncheck_newer.lua", "tests/versioncheck_newer.lua"} end return {"tests/versioncheck_newer.lua", "tests/versioncheck_older.lua"} end; ["error"] = function() local ok, err = pcall(runShellProgramWithErrors, ".test/luapp", "-o .test/error tests/error.lua -s") if not ok then --Successful without creating a file so we just return the --Already existing test file twice to make it pass return {"tests/error.lua", "tests/error.lua"} end return {"tests/iftest.lua", "tests/error.lua"} end; filelinetest = function() shell.run("luapp_build -o .test/filelinetest tests/filelinetest.lua -s") shell.run(".test/luapp -o .test/filelinetest_b tests/filelinetest.lua -s") return {".test/filelinetest_b", ".test/filelinetest"} end; } local function test_passed(tname) if howlci then howlci.status("pass", "Test " .. tname .. " passed!") end term.setTextColor(colors.green) print("passed!") term.setTextColor(colors.white) end local function test_failed(tname) if howlci then howlci.status("fail", "Test " .. tname .. " failed!") end term.setTextColor(colors.red) print("failed!") term.setTextColor(colors.white) end local function compare(fileName1, fileName2) local ret = false local f1 = fs.open(shell.resolve(fileName1), "r") local f2 = fs.open(shell.resolve(fileName2), "r") ret = (f1.readAll() == f2.readAll()) f2.close() f1.close() return ret end local function main() print("Getting dependencies...") local _lpp = http.get("http://pastebin.com/raw/aLcLbJsA") local _lpp_f = fs.open(shell.resolve("getopt"), "w") _lpp_f.write(_lpp.readAll()) _lpp_f.close() _lpp.close() print("Building current luapp...") fs.makeDir(".test/") fs.copy(shell.resolve("getopt"), shell.resolve(".test/getopt")) shell.run("luapp_build -o .test/luapp luapp.lua -s") for tname, tfunc in pairs(tests) do term.setTextColor(colors.yellow) write("Running test: " .. tname .. " ") term.setTextColor(colors.white) if compare(table.unpack(tfunc())) then --test went ok test_passed(tname) else test_failed(tname) return end end end main() print("Cleaning up...") fs.delete(shell.resolve("getopt")) fs.delete(shell.resolve(".test")) if howlci then howlci.close() end
mit
mario0582/devenserver
data/npc/lib/npcsystem/npchandler.lua
13
21971
-- Advanced NPC System by Jiddo if NpcHandler == nil then -- Constant talkdelay behaviors. TALKDELAY_NONE = 0 -- No talkdelay. Npc will reply immedeatly. TALKDELAY_ONTHINK = 1 -- Talkdelay handled through the onThink callback function. (Default) TALKDELAY_EVENT = 2 -- Not yet implemented -- Currently applied talkdelay behavior. TALKDELAY_ONTHINK is default. NPCHANDLER_TALKDELAY = TALKDELAY_ONTHINK -- Constant indexes for defining default messages. MESSAGE_GREET = 1 -- When the player greets the npc. MESSAGE_FAREWELL = 2 -- When the player unGreets the npc. MESSAGE_BUY = 3 -- When the npc asks the player if he wants to buy something. MESSAGE_ONBUY = 4 -- When the player successfully buys something via talk. MESSAGE_BOUGHT = 5 -- When the player bought something through the shop window. MESSAGE_SELL = 6 -- When the npc asks the player if he wants to sell something. MESSAGE_ONSELL = 7 -- When the player successfully sells something via talk. MESSAGE_SOLD = 8 -- When the player sold something through the shop window. MESSAGE_MISSINGMONEY = 9 -- When the player does not have enough money. MESSAGE_NEEDMONEY = 10 -- Same as above, used for shop window. MESSAGE_MISSINGITEM = 11 -- When the player is trying to sell an item he does not have. MESSAGE_NEEDITEM = 12 -- Same as above, used for shop window. MESSAGE_NEEDSPACE = 13 -- When the player don't have any space to buy an item MESSAGE_NEEDMORESPACE = 14 -- When the player has some space to buy an item, but not enough space MESSAGE_IDLETIMEOUT = 15 -- When the player has been idle for longer then idleTime allows. MESSAGE_WALKAWAY = 16 -- When the player walks out of the talkRadius of the npc. MESSAGE_DECLINE = 17 -- When the player says no to something. MESSAGE_SENDTRADE = 18 -- When the npc sends the trade window to the player MESSAGE_NOSHOP = 19 -- When the npc's shop is requested but he doesn't have any MESSAGE_ONCLOSESHOP = 20 -- When the player closes the npc's shop window MESSAGE_ALREADYFOCUSED = 21 -- When the player already has the focus of this npc. MESSAGE_WALKAWAY_MALE = 22 -- When a male player walks out of the talkRadius of the npc. MESSAGE_WALKAWAY_FEMALE = 23 -- When a female player walks out of the talkRadius of the npc. -- Constant indexes for callback functions. These are also used for module callback ids. CALLBACK_CREATURE_APPEAR = 1 CALLBACK_CREATURE_DISAPPEAR = 2 CALLBACK_CREATURE_SAY = 3 CALLBACK_ONTHINK = 4 CALLBACK_GREET = 5 CALLBACK_FAREWELL = 6 CALLBACK_MESSAGE_DEFAULT = 7 CALLBACK_PLAYER_ENDTRADE = 8 CALLBACK_PLAYER_CLOSECHANNEL = 9 CALLBACK_ONBUY = 10 CALLBACK_ONSELL = 11 CALLBACK_ONADDFOCUS = 18 CALLBACK_ONRELEASEFOCUS = 19 CALLBACK_ONTRADEREQUEST = 20 -- Addidional module callback ids CALLBACK_MODULE_INIT = 12 CALLBACK_MODULE_RESET = 13 -- Constant strings defining the keywords to replace in the default messages. TAG_PLAYERNAME = "|PLAYERNAME|" TAG_ITEMCOUNT = "|ITEMCOUNT|" TAG_TOTALCOST = "|TOTALCOST|" TAG_ITEMNAME = "|ITEMNAME|" NpcHandler = { keywordHandler = nil, focuses = nil, talkStart = nil, idleTime = 120, talkRadius = 3, talkDelayTime = 1, -- Seconds to delay outgoing messages. talkDelay = nil, callbackFunctions = nil, modules = nil, shopItems = nil, -- They must be here since ShopModule uses 'static' functions eventSay = nil, eventDelayedSay = nil, topic = nil, messages = { -- These are the default replies of all npcs. They can/should be changed individually for each npc. [MESSAGE_GREET] = "Greetings, |PLAYERNAME|.", [MESSAGE_FAREWELL] = "Good bye, |PLAYERNAME|.", [MESSAGE_BUY] = "Do you want to buy |ITEMCOUNT| |ITEMNAME| for |TOTALCOST| gold coins?", [MESSAGE_ONBUY] = "Here you are.", [MESSAGE_BOUGHT] = "Bought |ITEMCOUNT|x |ITEMNAME| for |TOTALCOST| gold.", [MESSAGE_SELL] = "Do you want to sell |ITEMCOUNT| |ITEMNAME| for |TOTALCOST| gold coins?", [MESSAGE_ONSELL] = "Here you are, |TOTALCOST| gold.", [MESSAGE_SOLD] = "Sold |ITEMCOUNT|x |ITEMNAME| for |TOTALCOST| gold.", [MESSAGE_MISSINGMONEY] = "You don't have enough money.", [MESSAGE_NEEDMONEY] = "You don't have enough money.", [MESSAGE_MISSINGITEM] = "You don't have so many.", [MESSAGE_NEEDITEM] = "You do not have this object.", [MESSAGE_NEEDSPACE] = "You do not have enough capacity.", [MESSAGE_NEEDMORESPACE] = "You do not have enough capacity for all items.", [MESSAGE_IDLETIMEOUT] = "Good bye.", [MESSAGE_WALKAWAY] = "Good bye.", [MESSAGE_DECLINE] = "Then not.", [MESSAGE_SENDTRADE] = "Of course, just browse through my wares.", [MESSAGE_NOSHOP] = "Sorry, I'm not offering anything.", [MESSAGE_ONCLOSESHOP] = "Thank you, come back whenever you're in need of something else.", [MESSAGE_ALREADYFOCUSED]= "|PLAYERNAME|, I am already talking to you.", [MESSAGE_WALKAWAY_MALE] = "Good bye.", [MESSAGE_WALKAWAY_FEMALE] = "Good bye." } } -- Creates a new NpcHandler with an empty callbackFunction stack. function NpcHandler:new(keywordHandler) local obj = {} obj.callbackFunctions = {} obj.modules = {} obj.eventSay = {} obj.eventDelayedSay = {} obj.topic = {} obj.focuses = {} obj.talkStart = {} obj.talkDelay = {} obj.keywordHandler = keywordHandler obj.messages = {} obj.shopItems = {} setmetatable(obj.messages, self.messages) self.messages.__index = self.messages setmetatable(obj, self) self.__index = self return obj end -- Re-defines the maximum idle time allowed for a player when talking to this npc. function NpcHandler:setMaxIdleTime(newTime) self.idleTime = newTime end -- Attaches a new keyword handler to this npchandler function NpcHandler:setKeywordHandler(newHandler) self.keywordHandler = newHandler end -- Function used to change the focus of this npc. function NpcHandler:addFocus(newFocus) if self:isFocused(newFocus) then return end self.focuses[#self.focuses + 1] = newFocus self.topic[newFocus] = 0 local callback = self:getCallback(CALLBACK_ONADDFOCUS) if callback == nil or callback(newFocus) then self:processModuleCallback(CALLBACK_ONADDFOCUS, newFocus) end self:updateFocus() end -- Function used to verify if npc is focused to certain player function NpcHandler:isFocused(focus) for k,v in pairs(self.focuses) do if v == focus then return true end end return false end -- This function should be called on each onThink and makes sure the npc faces the player it is talking to. -- Should also be called whenever a new player is focused. function NpcHandler:updateFocus() for pos, focus in pairs(self.focuses) do if focus ~= nil then doNpcSetCreatureFocus(focus) return end end doNpcSetCreatureFocus(0) end -- Used when the npc should un-focus the player. function NpcHandler:releaseFocus(focus) if shop_cost[focus] ~= nil then table.remove(shop_amount, focus) table.remove(shop_cost, focus) table.remove(shop_rlname, focus) table.remove(shop_itemid, focus) table.remove(shop_container, focus) table.remove(shop_npcuid, focus) table.remove(shop_eventtype, focus) table.remove(shop_subtype, focus) table.remove(shop_destination, focus) table.remove(shop_premium, focus) end if self.eventDelayedSay[focus] then self:cancelNPCTalk(self.eventDelayedSay[focus]) end if not self:isFocused(focus) then return end local pos = nil for k,v in pairs(self.focuses) do if v == focus then pos = k end end table.remove(self.focuses, pos) self.eventSay[focus] = nil self.eventDelayedSay[focus] = nil self.talkStart[focus] = nil self.topic[focus] = nil local callback = self:getCallback(CALLBACK_ONRELEASEFOCUS) if callback == nil or callback(focus) then self:processModuleCallback(CALLBACK_ONRELEASEFOCUS, focus) end if Player(focus) ~= nil then closeShopWindow(focus) --Even if it can not exist, we need to prevent it. self:updateFocus() end end -- Returns the callback function with the specified id or nil if no such callback function exists. function NpcHandler:getCallback(id) local ret = nil if self.callbackFunctions ~= nil then ret = self.callbackFunctions[id] end return ret end -- Changes the callback function for the given id to callback. function NpcHandler:setCallback(id, callback) if self.callbackFunctions ~= nil then self.callbackFunctions[id] = callback end end -- Adds a module to this npchandler and inits it. function NpcHandler:addModule(module) if self.modules ~= nil then self.modules[#self.modules +1] = module module:init(self) end end -- Calls the callback function represented by id for all modules added to this npchandler with the given arguments. function NpcHandler:processModuleCallback(id, ...) local ret = true for i, module in pairs(self.modules) do local tmpRet = true if id == CALLBACK_CREATURE_APPEAR and module.callbackOnCreatureAppear ~= nil then tmpRet = module:callbackOnCreatureAppear(...) elseif id == CALLBACK_CREATURE_DISAPPEAR and module.callbackOnCreatureDisappear ~= nil then tmpRet = module:callbackOnCreatureDisappear(...) elseif id == CALLBACK_CREATURE_SAY and module.callbackOnCreatureSay ~= nil then tmpRet = module:callbackOnCreatureSay(...) elseif id == CALLBACK_PLAYER_ENDTRADE and module.callbackOnPlayerEndTrade ~= nil then tmpRet = module:callbackOnPlayerEndTrade(...) elseif id == CALLBACK_PLAYER_CLOSECHANNEL and module.callbackOnPlayerCloseChannel ~= nil then tmpRet = module:callbackOnPlayerCloseChannel(...) elseif id == CALLBACK_ONBUY and module.callbackOnBuy ~= nil then tmpRet = module:callbackOnBuy(...) elseif id == CALLBACK_ONSELL and module.callbackOnSell ~= nil then tmpRet = module:callbackOnSell(...) elseif id == CALLBACK_ONTRADEREQUEST and module.callbackOnTradeRequest ~= nil then tmpRet = module:callbackOnTradeRequest(...) elseif id == CALLBACK_ONADDFOCUS and module.callbackOnAddFocus ~= nil then tmpRet = module:callbackOnAddFocus(...) elseif id == CALLBACK_ONRELEASEFOCUS and module.callbackOnReleaseFocus ~= nil then tmpRet = module:callbackOnReleaseFocus(...) elseif id == CALLBACK_ONTHINK and module.callbackOnThink ~= nil then tmpRet = module:callbackOnThink(...) elseif id == CALLBACK_GREET and module.callbackOnGreet ~= nil then tmpRet = module:callbackOnGreet(...) elseif id == CALLBACK_FAREWELL and module.callbackOnFarewell ~= nil then tmpRet = module:callbackOnFarewell(...) elseif id == CALLBACK_MESSAGE_DEFAULT and module.callbackOnMessageDefault ~= nil then tmpRet = module:callbackOnMessageDefault(...) elseif id == CALLBACK_MODULE_RESET and module.callbackOnModuleReset ~= nil then tmpRet = module:callbackOnModuleReset(...) end if not tmpRet then ret = false break end end return ret end -- Returns the message represented by id. function NpcHandler:getMessage(id) local ret = nil if self.messages ~= nil then ret = self.messages[id] end return ret end -- Changes the default response message with the specified id to newMessage. function NpcHandler:setMessage(id, newMessage) if self.messages ~= nil then self.messages[id] = newMessage end end -- Translates all message tags found in msg using parseInfo function NpcHandler:parseMessage(msg, parseInfo) local ret = msg for search, replace in pairs(parseInfo) do ret = string.gsub(ret, search, replace) end return ret end -- Makes sure the npc un-focuses the currently focused player function NpcHandler:unGreet(cid) if not self:isFocused(cid) then return end local callback = self:getCallback(CALLBACK_FAREWELL) if callback == nil or callback() then if self:processModuleCallback(CALLBACK_FAREWELL) then local msg = self:getMessage(MESSAGE_FAREWELL) local parseInfo = { [TAG_PLAYERNAME] = Player(cid):getName() } self:resetNpc(cid) msg = self:parseMessage(msg, parseInfo) self:say(msg, cid, true) self:releaseFocus(cid) end end end -- Greets a new player. function NpcHandler:greet(cid) if cid ~= 0 then local callback = self:getCallback(CALLBACK_GREET) if callback == nil or callback(cid) then if self:processModuleCallback(CALLBACK_GREET, cid) then local msg = self:getMessage(MESSAGE_GREET) local parseInfo = { [TAG_PLAYERNAME] = Player(cid):getName() } msg = self:parseMessage(msg, parseInfo) self:say(msg, cid, true) else return end else return end end self:addFocus(cid) end -- Handles onCreatureAppear events. If you with to handle this yourself, please use the CALLBACK_CREATURE_APPEAR callback. function NpcHandler:onCreatureAppear(creature) local cid = creature:getId() if cid == getNpcCid() and next(self.shopItems) ~= nil then local npc = Npc() local speechBubble = npc:getSpeechBubble() if speechBubble == 3 then npc:setSpeechBubble(4) else npc:setSpeechBubble(2) end end local callback = self:getCallback(CALLBACK_CREATURE_APPEAR) if callback == nil or callback(cid) then if self:processModuleCallback(CALLBACK_CREATURE_APPEAR, cid) then -- end end end -- Handles onCreatureDisappear events. If you with to handle this yourself, please use the CALLBACK_CREATURE_DISAPPEAR callback. function NpcHandler:onCreatureDisappear(creature) local cid = creature:getId() if getNpcCid() == cid then return end local callback = self:getCallback(CALLBACK_CREATURE_DISAPPEAR) if callback == nil or callback(cid) then if self:processModuleCallback(CALLBACK_CREATURE_DISAPPEAR, cid) then if self:isFocused(cid) then self:unGreet(cid) end end end end -- Handles onCreatureSay events. If you with to handle this yourself, please use the CALLBACK_CREATURE_SAY callback. function NpcHandler:onCreatureSay(creature, msgtype, msg) local cid = creature:getId() local callback = self:getCallback(CALLBACK_CREATURE_SAY) if callback == nil or callback(cid, msgtype, msg) then if self:processModuleCallback(CALLBACK_CREATURE_SAY, cid, msgtype, msg) then if not self:isInRange(cid) then return end if self.keywordHandler ~= nil then if self:isFocused(cid) and msgtype == TALKTYPE_PRIVATE_PN or not self:isFocused(cid) then local ret = self.keywordHandler:processMessage(cid, msg) if(not ret) then local callback = self:getCallback(CALLBACK_MESSAGE_DEFAULT) if callback ~= nil and callback(cid, msgtype, msg) then self.talkStart[cid] = os.time() end else self.talkStart[cid] = os.time() end end end end end end -- Handles onPlayerEndTrade events. If you wish to handle this yourself, use the CALLBACK_PLAYER_ENDTRADE callback. function NpcHandler:onPlayerEndTrade(creature) local cid = creature:getId() local callback = self:getCallback(CALLBACK_PLAYER_ENDTRADE) if callback == nil or callback(cid) then if self:processModuleCallback(CALLBACK_PLAYER_ENDTRADE, cid, msgtype, msg) then if self:isFocused(cid) then local parseInfo = { [TAG_PLAYERNAME] = Player(cid):getName() } local msg = self:parseMessage(self:getMessage(MESSAGE_ONCLOSESHOP), parseInfo) self:say(msg, cid) end end end end -- Handles onPlayerCloseChannel events. If you wish to handle this yourself, use the CALLBACK_PLAYER_CLOSECHANNEL callback. function NpcHandler:onPlayerCloseChannel(creature) local cid = creature:getId() local callback = self:getCallback(CALLBACK_PLAYER_CLOSECHANNEL) if callback == nil or callback(cid) then if self:processModuleCallback(CALLBACK_PLAYER_CLOSECHANNEL, cid, msgtype, msg) then if self:isFocused(cid) then self:unGreet(cid) end end end end -- Handles onBuy events. If you wish to handle this yourself, use the CALLBACK_ONBUY callback. function NpcHandler:onBuy(creature, itemid, subType, amount, ignoreCap, inBackpacks) local cid = creature:getId() local callback = self:getCallback(CALLBACK_ONBUY) if callback == nil or callback(cid, itemid, subType, amount, ignoreCap, inBackpacks) then if self:processModuleCallback(CALLBACK_ONBUY, cid, itemid, subType, amount, ignoreCap, inBackpacks) then -- end end end -- Handles onSell events. If you wish to handle this yourself, use the CALLBACK_ONSELL callback. function NpcHandler:onSell(creature, itemid, subType, amount, ignoreCap, inBackpacks) local cid = creature:getId() local callback = self:getCallback(CALLBACK_ONSELL) if callback == nil or callback(cid, itemid, subType, amount, ignoreCap, inBackpacks) then if self:processModuleCallback(CALLBACK_ONSELL, cid, itemid, subType, amount, ignoreCap, inBackpacks) then -- end end end -- Handles onTradeRequest events. If you wish to handle this yourself, use the CALLBACK_ONTRADEREQUEST callback. function NpcHandler:onTradeRequest(cid) local callback = self:getCallback(CALLBACK_ONTRADEREQUEST) if callback == nil or callback(cid) then if self:processModuleCallback(CALLBACK_ONTRADEREQUEST, cid) then return true end end return false end -- Handles onThink events. If you wish to handle this yourself, please use the CALLBACK_ONTHINK callback. function NpcHandler:onThink() local callback = self:getCallback(CALLBACK_ONTHINK) if callback == nil or callback() then if NPCHANDLER_TALKDELAY == TALKDELAY_ONTHINK then for cid, talkDelay in pairs(self.talkDelay) do if talkDelay.time ~= nil and talkDelay.message ~= nil and os.time() >= talkDelay.time then selfSay(talkDelay.message, cid, talkDelay.publicize and true or false) self.talkDelay[cid] = nil end end end if self:processModuleCallback(CALLBACK_ONTHINK) then for pos, focus in pairs(self.focuses) do if focus ~= nil then if not self:isInRange(focus) then self:onWalkAway(focus) elseif self.talkStart[focus] ~= nil and (os.time() - self.talkStart[focus]) > self.idleTime then self:unGreet(focus) else self:updateFocus() end end end end end end -- Tries to greet the player with the given cid. function NpcHandler:onGreet(cid) if self:isInRange(cid) then if not self:isFocused(cid) then self:greet(cid) return end end end -- Simply calls the underlying unGreet function. function NpcHandler:onFarewell(cid) self:unGreet(cid) end -- Should be called on this npc's focus if the distance to focus is greater then talkRadius. function NpcHandler:onWalkAway(cid) if self:isFocused(cid) then local callback = self:getCallback(CALLBACK_CREATURE_DISAPPEAR) if callback == nil or callback() then if self:processModuleCallback(CALLBACK_CREATURE_DISAPPEAR, cid) then local msg = self:getMessage(MESSAGE_WALKAWAY) local playerName = Player(cid):getName() if not playerName then playerName = -1 end local parseInfo = { [TAG_PLAYERNAME] = playerName } local message = self:parseMessage(msg, parseInfo) local msg_male = self:getMessage(MESSAGE_WALKAWAY_MALE) local message_male = self:parseMessage(msg_male, parseInfo) local msg_female = self:getMessage(MESSAGE_WALKAWAY_FEMALE) local message_female = self:parseMessage(msg_female, parseInfo) if message_female ~= message_male then if Player(cid):getSex() == 0 then selfSay(message_female) else selfSay(message_male) end elseif message ~= "" then selfSay(message) end self:resetNpc(cid) self:releaseFocus(cid) end end end end -- Returns true if cid is within the talkRadius of this npc. function NpcHandler:isInRange(cid) local distance = Player(cid) ~= nil and getDistanceTo(cid) or -1 if distance == -1 then return false end return distance <= self.talkRadius end -- Resets the npc into its initial state (in regard of the keywordhandler). -- All modules are also receiving a reset call through their callbackOnModuleReset function. function NpcHandler:resetNpc(cid) if self:processModuleCallback(CALLBACK_MODULE_RESET) then self.keywordHandler:reset(cid) end end function NpcHandler:cancelNPCTalk(events) for aux = 1, #events do stopEvent(events[aux].event) end events = nil end function NpcHandler:doNPCTalkALot(msgs, interval, pcid) if self.eventDelayedSay[pcid] then self:cancelNPCTalk(self.eventDelayedSay[pcid]) end self.eventDelayedSay[pcid] = {} local ret = {} for aux = 1, #msgs do self.eventDelayedSay[pcid][aux] = {} doCreatureSayWithDelay(getNpcCid(), msgs[aux], TALKTYPE_PRIVATE_NP, ((aux-1) * (interval or 4000)) + 700, self.eventDelayedSay[pcid][aux], pcid) ret[#ret +1] = self.eventDelayedSay[pcid][aux] end return(ret) end -- Makes the npc represented by this instance of NpcHandler say something. -- This implements the currently set type of talkdelay. -- shallDelay is a boolean value. If it is false, the message is not delayed. Default value is true. function NpcHandler:say(message, focus, publicize, shallDelay, delay) if type(message) == "table" then return self:doNPCTalkALot(message, delay or 6000, focus) end if self.eventDelayedSay[focus] then self:cancelNPCTalk(self.eventDelayedSay[focus]) end local shallDelay = not shallDelay and true or shallDelay if NPCHANDLER_TALKDELAY == TALKDELAY_NONE or shallDelay == false then selfSay(message, focus, publicize and true or false) return end stopEvent(self.eventSay[focus]) self.eventSay[focus] = addEvent(function(npcId, message, focusId) local npc = Npc(npcId) if npc == nil then return end local player = Player(focusId) if player then npc:say(message, TALKTYPE_PRIVATE_NP, false, player, npc:getPosition()) end end, self.talkDelayTime * 1000, Npc():getId(), message, focus) end end
gpl-2.0
bdowning/lj-cdefdb
ljclang/ljclang_Index_h.lua
1
56148
require('ffi').cdef[==========[ /*===-- clang-c/CXString.h - C Index strings --------------------*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header provides the interface to C Index strings. *| |* *| \*===----------------------------------------------------------------------===*/ typedef struct { const void *data; unsigned private_flags; } CXString; const char *clang_getCString(CXString string); void clang_disposeString(CXString string); /*===-- clang-c/Index.h - Indexing Public C Interface -------------*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header provides a public inferface to a Clang library for extracting *| |* high-level symbol information from source files without exposing the full *| |* Clang C++ API. *| |* *| \*===----------------------------------------------------------------------===*/ typedef void *CXIndex; typedef struct CXTranslationUnitImpl *CXTranslationUnit; typedef void *CXClientData; struct CXUnsavedFile { const char *Filename; const char *Contents; unsigned long Length; }; enum CXAvailabilityKind { CXAvailability_Available, CXAvailability_Deprecated, CXAvailability_NotAvailable, CXAvailability_NotAccessible }; typedef struct CXVersion { int Major; int Minor; int Subminor; } CXVersion; CXIndex clang_createIndex(int excludeDeclarationsFromPCH, int displayDiagnostics); void clang_disposeIndex(CXIndex index); typedef enum { CXGlobalOpt_None = 0x0, CXGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1, CXGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2, CXGlobalOpt_ThreadBackgroundPriorityForAll = CXGlobalOpt_ThreadBackgroundPriorityForIndexing | CXGlobalOpt_ThreadBackgroundPriorityForEditing } CXGlobalOptFlags; void clang_CXIndex_setGlobalOptions(CXIndex, unsigned options); unsigned clang_CXIndex_getGlobalOptions(CXIndex); typedef void *CXFile; CXString clang_getFileName(CXFile SFile); // time_t clang_getFileTime(CXFile SFile); typedef struct { unsigned long long data[3]; } CXFileUniqueID; int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID); unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file); CXFile clang_getFile(CXTranslationUnit tu, const char *file_name); typedef struct { const void *ptr_data[2]; unsigned int_data; } CXSourceLocation; typedef struct { const void *ptr_data[2]; unsigned begin_int_data; unsigned end_int_data; } CXSourceRange; CXSourceLocation clang_getNullLocation(void); unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2); CXSourceLocation clang_getLocation(CXTranslationUnit tu, CXFile file, unsigned line, unsigned column); CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu, CXFile file, unsigned offset); int clang_Location_isInSystemHeader(CXSourceLocation location); CXSourceRange clang_getNullRange(void); CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end); unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2); int clang_Range_isNull(CXSourceRange range); void clang_getExpansionLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset); void clang_getPresumedLocation(CXSourceLocation location, CXString *filename, unsigned *line, unsigned *column); void clang_getInstantiationLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset); void clang_getSpellingLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset); void clang_getFileLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset); CXSourceLocation clang_getRangeStart(CXSourceRange range); CXSourceLocation clang_getRangeEnd(CXSourceRange range); enum CXDiagnosticSeverity { CXDiagnostic_Ignored = 0, CXDiagnostic_Note = 1, CXDiagnostic_Warning = 2, CXDiagnostic_Error = 3, CXDiagnostic_Fatal = 4 }; typedef void *CXDiagnostic; typedef void *CXDiagnosticSet; unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags); CXDiagnostic clang_getDiagnosticInSet(CXDiagnosticSet Diags, unsigned Index); enum CXLoadDiag_Error { CXLoadDiag_None = 0, CXLoadDiag_Unknown = 1, CXLoadDiag_CannotLoad = 2, CXLoadDiag_InvalidFile = 3 }; CXDiagnosticSet clang_loadDiagnostics(const char *file, enum CXLoadDiag_Error *error, CXString *errorString); void clang_disposeDiagnosticSet(CXDiagnosticSet Diags); CXDiagnosticSet clang_getChildDiagnostics(CXDiagnostic D); unsigned clang_getNumDiagnostics(CXTranslationUnit Unit); CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit, unsigned Index); CXDiagnosticSet clang_getDiagnosticSetFromTU(CXTranslationUnit Unit); void clang_disposeDiagnostic(CXDiagnostic Diagnostic); enum CXDiagnosticDisplayOptions { CXDiagnostic_DisplaySourceLocation = 0x01, CXDiagnostic_DisplayColumn = 0x02, CXDiagnostic_DisplaySourceRanges = 0x04, CXDiagnostic_DisplayOption = 0x08, CXDiagnostic_DisplayCategoryId = 0x10, CXDiagnostic_DisplayCategoryName = 0x20 }; CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, unsigned Options); unsigned clang_defaultDiagnosticDisplayOptions(void); enum CXDiagnosticSeverity clang_getDiagnosticSeverity(CXDiagnostic); CXSourceLocation clang_getDiagnosticLocation(CXDiagnostic); CXString clang_getDiagnosticSpelling(CXDiagnostic); CXString clang_getDiagnosticOption(CXDiagnostic Diag, CXString *Disable); unsigned clang_getDiagnosticCategory(CXDiagnostic); CXString clang_getDiagnosticCategoryName(unsigned Category); CXString clang_getDiagnosticCategoryText(CXDiagnostic); unsigned clang_getDiagnosticNumRanges(CXDiagnostic); CXSourceRange clang_getDiagnosticRange(CXDiagnostic Diagnostic, unsigned Range); unsigned clang_getDiagnosticNumFixIts(CXDiagnostic Diagnostic); CXString clang_getDiagnosticFixIt(CXDiagnostic Diagnostic, unsigned FixIt, CXSourceRange *ReplacementRange); CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit); CXTranslationUnit clang_createTranslationUnitFromSourceFile( CXIndex CIdx, const char *source_filename, int num_clang_command_line_args, const char * const *clang_command_line_args, unsigned num_unsaved_files, struct CXUnsavedFile *unsaved_files); CXTranslationUnit clang_createTranslationUnit(CXIndex, const char *ast_filename); enum CXTranslationUnit_Flags { CXTranslationUnit_None = 0x0, CXTranslationUnit_DetailedPreprocessingRecord = 0x01, CXTranslationUnit_Incomplete = 0x02, CXTranslationUnit_PrecompiledPreamble = 0x04, CXTranslationUnit_CacheCompletionResults = 0x08, CXTranslationUnit_ForSerialization = 0x10, CXTranslationUnit_CXXChainedPCH = 0x20, CXTranslationUnit_SkipFunctionBodies = 0x40, CXTranslationUnit_IncludeBriefCommentsInCodeCompletion = 0x80 }; unsigned clang_defaultEditingTranslationUnitOptions(void); CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename, const char * const *command_line_args, int num_command_line_args, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, unsigned options); enum CXSaveTranslationUnit_Flags { CXSaveTranslationUnit_None = 0x0 }; unsigned clang_defaultSaveOptions(CXTranslationUnit TU); enum CXSaveError { CXSaveError_None = 0, CXSaveError_Unknown = 1, CXSaveError_TranslationErrors = 2, CXSaveError_InvalidTU = 3 }; int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, unsigned options); void clang_disposeTranslationUnit(CXTranslationUnit); enum CXReparse_Flags { CXReparse_None = 0x0 }; unsigned clang_defaultReparseOptions(CXTranslationUnit TU); int clang_reparseTranslationUnit(CXTranslationUnit TU, unsigned num_unsaved_files, struct CXUnsavedFile *unsaved_files, unsigned options); enum CXTUResourceUsageKind { CXTUResourceUsage_AST = 1, CXTUResourceUsage_Identifiers = 2, CXTUResourceUsage_Selectors = 3, CXTUResourceUsage_GlobalCompletionResults = 4, CXTUResourceUsage_SourceManagerContentCache = 5, CXTUResourceUsage_AST_SideTables = 6, CXTUResourceUsage_SourceManager_Membuffer_Malloc = 7, CXTUResourceUsage_SourceManager_Membuffer_MMap = 8, CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc = 9, CXTUResourceUsage_ExternalASTSource_Membuffer_MMap = 10, CXTUResourceUsage_Preprocessor = 11, CXTUResourceUsage_PreprocessingRecord = 12, CXTUResourceUsage_SourceManager_DataStructures = 13, CXTUResourceUsage_Preprocessor_HeaderSearch = 14, CXTUResourceUsage_MEMORY_IN_BYTES_BEGIN = CXTUResourceUsage_AST, CXTUResourceUsage_MEMORY_IN_BYTES_END = CXTUResourceUsage_Preprocessor_HeaderSearch, CXTUResourceUsage_First = CXTUResourceUsage_AST, CXTUResourceUsage_Last = CXTUResourceUsage_Preprocessor_HeaderSearch }; const char *clang_getTUResourceUsageName(enum CXTUResourceUsageKind kind); typedef struct CXTUResourceUsageEntry { /* \brief The memory usage category. */ enum CXTUResourceUsageKind kind; /* \brief Amount of resources used. The units will depend on the resource kind. */ unsigned long amount; } CXTUResourceUsageEntry; typedef struct CXTUResourceUsage { /* \brief Private data member, used for queries. */ void *data; /* \brief The number of entries in the 'entries' array. */ unsigned numEntries; /* \brief An array of key-value pairs, representing the breakdown of memory usage. */ CXTUResourceUsageEntry *entries; } CXTUResourceUsage; CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU); void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage); enum CXCursorKind { /* Declarations */ CXCursor_UnexposedDecl = 1, CXCursor_StructDecl = 2, CXCursor_UnionDecl = 3, CXCursor_ClassDecl = 4, CXCursor_EnumDecl = 5, CXCursor_FieldDecl = 6, CXCursor_EnumConstantDecl = 7, CXCursor_FunctionDecl = 8, CXCursor_VarDecl = 9, CXCursor_ParmDecl = 10, CXCursor_ObjCInterfaceDecl = 11, CXCursor_ObjCCategoryDecl = 12, CXCursor_ObjCProtocolDecl = 13, CXCursor_ObjCPropertyDecl = 14, CXCursor_ObjCIvarDecl = 15, CXCursor_ObjCInstanceMethodDecl = 16, CXCursor_ObjCClassMethodDecl = 17, CXCursor_ObjCImplementationDecl = 18, CXCursor_ObjCCategoryImplDecl = 19, CXCursor_TypedefDecl = 20, CXCursor_CXXMethod = 21, CXCursor_Namespace = 22, CXCursor_LinkageSpec = 23, CXCursor_Constructor = 24, CXCursor_Destructor = 25, CXCursor_ConversionFunction = 26, CXCursor_TemplateTypeParameter = 27, CXCursor_NonTypeTemplateParameter = 28, CXCursor_TemplateTemplateParameter = 29, CXCursor_FunctionTemplate = 30, CXCursor_ClassTemplate = 31, CXCursor_ClassTemplatePartialSpecialization = 32, CXCursor_NamespaceAlias = 33, CXCursor_UsingDirective = 34, CXCursor_UsingDeclaration = 35, CXCursor_TypeAliasDecl = 36, CXCursor_ObjCSynthesizeDecl = 37, CXCursor_ObjCDynamicDecl = 38, CXCursor_CXXAccessSpecifier = 39, CXCursor_FirstDecl = CXCursor_UnexposedDecl, CXCursor_LastDecl = CXCursor_CXXAccessSpecifier, /* References */ CXCursor_FirstRef = 40, /* Decl references */ CXCursor_ObjCSuperClassRef = 40, CXCursor_ObjCProtocolRef = 41, CXCursor_ObjCClassRef = 42, CXCursor_TypeRef = 43, CXCursor_CXXBaseSpecifier = 44, CXCursor_TemplateRef = 45, CXCursor_NamespaceRef = 46, CXCursor_MemberRef = 47, CXCursor_LabelRef = 48, CXCursor_OverloadedDeclRef = 49, CXCursor_VariableRef = 50, CXCursor_LastRef = CXCursor_VariableRef, /* Error conditions */ CXCursor_FirstInvalid = 70, CXCursor_InvalidFile = 70, CXCursor_NoDeclFound = 71, CXCursor_NotImplemented = 72, CXCursor_InvalidCode = 73, CXCursor_LastInvalid = CXCursor_InvalidCode, /* Expressions */ CXCursor_FirstExpr = 100, CXCursor_UnexposedExpr = 100, CXCursor_DeclRefExpr = 101, CXCursor_MemberRefExpr = 102, CXCursor_CallExpr = 103, CXCursor_ObjCMessageExpr = 104, CXCursor_BlockExpr = 105, CXCursor_IntegerLiteral = 106, CXCursor_FloatingLiteral = 107, CXCursor_ImaginaryLiteral = 108, CXCursor_StringLiteral = 109, CXCursor_CharacterLiteral = 110, CXCursor_ParenExpr = 111, CXCursor_UnaryOperator = 112, CXCursor_ArraySubscriptExpr = 113, CXCursor_BinaryOperator = 114, CXCursor_CompoundAssignOperator = 115, CXCursor_ConditionalOperator = 116, CXCursor_CStyleCastExpr = 117, CXCursor_CompoundLiteralExpr = 118, CXCursor_InitListExpr = 119, CXCursor_AddrLabelExpr = 120, CXCursor_StmtExpr = 121, CXCursor_GenericSelectionExpr = 122, CXCursor_GNUNullExpr = 123, CXCursor_CXXStaticCastExpr = 124, CXCursor_CXXDynamicCastExpr = 125, CXCursor_CXXReinterpretCastExpr = 126, CXCursor_CXXConstCastExpr = 127, CXCursor_CXXFunctionalCastExpr = 128, CXCursor_CXXTypeidExpr = 129, CXCursor_CXXBoolLiteralExpr = 130, CXCursor_CXXNullPtrLiteralExpr = 131, CXCursor_CXXThisExpr = 132, CXCursor_CXXThrowExpr = 133, CXCursor_CXXNewExpr = 134, CXCursor_CXXDeleteExpr = 135, CXCursor_UnaryExpr = 136, CXCursor_ObjCStringLiteral = 137, CXCursor_ObjCEncodeExpr = 138, CXCursor_ObjCSelectorExpr = 139, CXCursor_ObjCProtocolExpr = 140, CXCursor_ObjCBridgedCastExpr = 141, CXCursor_PackExpansionExpr = 142, CXCursor_SizeOfPackExpr = 143, /* \brief Represents a C++ lambda expression that produces a local function * object. * * \code * void abssort(float *x, unsigned N) { * std::sort(x, x + N, * [](float a, float b) { * return std::abs(a) < std::abs(b); * }); * } * \endcode */ CXCursor_LambdaExpr = 144, CXCursor_ObjCBoolLiteralExpr = 145, CXCursor_ObjCSelfExpr = 146, CXCursor_LastExpr = CXCursor_ObjCSelfExpr, /* Statements */ CXCursor_FirstStmt = 200, CXCursor_UnexposedStmt = 200, CXCursor_LabelStmt = 201, CXCursor_CompoundStmt = 202, CXCursor_CaseStmt = 203, CXCursor_DefaultStmt = 204, CXCursor_IfStmt = 205, CXCursor_SwitchStmt = 206, CXCursor_WhileStmt = 207, CXCursor_DoStmt = 208, CXCursor_ForStmt = 209, CXCursor_GotoStmt = 210, CXCursor_IndirectGotoStmt = 211, CXCursor_ContinueStmt = 212, CXCursor_BreakStmt = 213, CXCursor_ReturnStmt = 214, CXCursor_GCCAsmStmt = 215, CXCursor_AsmStmt = CXCursor_GCCAsmStmt, CXCursor_ObjCAtTryStmt = 216, CXCursor_ObjCAtCatchStmt = 217, CXCursor_ObjCAtFinallyStmt = 218, CXCursor_ObjCAtThrowStmt = 219, CXCursor_ObjCAtSynchronizedStmt = 220, CXCursor_ObjCAutoreleasePoolStmt = 221, CXCursor_ObjCForCollectionStmt = 222, CXCursor_CXXCatchStmt = 223, CXCursor_CXXTryStmt = 224, CXCursor_CXXForRangeStmt = 225, CXCursor_SEHTryStmt = 226, CXCursor_SEHExceptStmt = 227, CXCursor_SEHFinallyStmt = 228, CXCursor_MSAsmStmt = 229, CXCursor_NullStmt = 230, CXCursor_DeclStmt = 231, CXCursor_OMPParallelDirective = 232, CXCursor_LastStmt = CXCursor_OMPParallelDirective, CXCursor_TranslationUnit = 300, /* Attributes */ CXCursor_FirstAttr = 400, CXCursor_UnexposedAttr = 400, CXCursor_IBActionAttr = 401, CXCursor_IBOutletAttr = 402, CXCursor_IBOutletCollectionAttr = 403, CXCursor_CXXFinalAttr = 404, CXCursor_CXXOverrideAttr = 405, CXCursor_AnnotateAttr = 406, CXCursor_AsmLabelAttr = 407, CXCursor_LastAttr = CXCursor_AsmLabelAttr, /* Preprocessing */ CXCursor_PreprocessingDirective = 500, CXCursor_MacroDefinition = 501, CXCursor_MacroExpansion = 502, CXCursor_MacroInstantiation = CXCursor_MacroExpansion, CXCursor_InclusionDirective = 503, CXCursor_FirstPreprocessing = CXCursor_PreprocessingDirective, CXCursor_LastPreprocessing = CXCursor_InclusionDirective, /* Extra Declarations */ CXCursor_ModuleImportDecl = 600, CXCursor_FirstExtraDecl = CXCursor_ModuleImportDecl, CXCursor_LastExtraDecl = CXCursor_ModuleImportDecl }; typedef struct { enum CXCursorKind kind; int xdata; const void *data[3]; } CXCursor; typedef struct { const void *ASTNode; CXTranslationUnit TranslationUnit; } CXComment; CXCursor clang_getNullCursor(void); CXCursor clang_getTranslationUnitCursor(CXTranslationUnit); unsigned clang_equalCursors(CXCursor, CXCursor); int clang_Cursor_isNull(CXCursor cursor); unsigned clang_hashCursor(CXCursor); enum CXCursorKind clang_getCursorKind(CXCursor); unsigned clang_isDeclaration(enum CXCursorKind); unsigned clang_isReference(enum CXCursorKind); unsigned clang_isExpression(enum CXCursorKind); unsigned clang_isStatement(enum CXCursorKind); unsigned clang_isAttribute(enum CXCursorKind); unsigned clang_isInvalid(enum CXCursorKind); unsigned clang_isTranslationUnit(enum CXCursorKind); unsigned clang_isPreprocessing(enum CXCursorKind); unsigned clang_isUnexposed(enum CXCursorKind); enum CXLinkageKind { CXLinkage_Invalid, CXLinkage_NoLinkage, CXLinkage_Internal, CXLinkage_UniqueExternal, CXLinkage_External }; enum CXLinkageKind clang_getCursorLinkage(CXCursor cursor); enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor); typedef struct CXPlatformAvailability { CXString Platform; CXVersion Introduced; CXVersion Deprecated; CXVersion Obsoleted; int Unavailable; CXString Message; } CXPlatformAvailability; int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated, CXString *deprecated_message, int *always_unavailable, CXString *unavailable_message, CXPlatformAvailability *availability, int availability_size); void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability); enum CXLanguageKind { CXLanguage_Invalid = 0, CXLanguage_C, CXLanguage_ObjC, CXLanguage_CPlusPlus }; enum CXLanguageKind clang_getCursorLanguage(CXCursor cursor); CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor); typedef struct CXCursorSetImpl *CXCursorSet; CXCursorSet clang_createCXCursorSet(void); void clang_disposeCXCursorSet(CXCursorSet cset); unsigned clang_CXCursorSet_contains(CXCursorSet cset, CXCursor cursor); unsigned clang_CXCursorSet_insert(CXCursorSet cset, CXCursor cursor); CXCursor clang_getCursorSemanticParent(CXCursor cursor); CXCursor clang_getCursorLexicalParent(CXCursor cursor); void clang_getOverriddenCursors(CXCursor cursor, CXCursor **overridden, unsigned *num_overridden); void clang_disposeOverriddenCursors(CXCursor *overridden); CXFile clang_getIncludedFile(CXCursor cursor); CXCursor clang_getCursor(CXTranslationUnit, CXSourceLocation); CXSourceLocation clang_getCursorLocation(CXCursor); CXSourceRange clang_getCursorExtent(CXCursor); enum CXTypeKind { CXType_Invalid = 0, CXType_Unexposed = 1, /* Builtin types */ CXType_Void = 2, CXType_Bool = 3, CXType_Char_U = 4, CXType_UChar = 5, CXType_Char16 = 6, CXType_Char32 = 7, CXType_UShort = 8, CXType_UInt = 9, CXType_ULong = 10, CXType_ULongLong = 11, CXType_UInt128 = 12, CXType_Char_S = 13, CXType_SChar = 14, CXType_WChar = 15, CXType_Short = 16, CXType_Int = 17, CXType_Long = 18, CXType_LongLong = 19, CXType_Int128 = 20, CXType_Float = 21, CXType_Double = 22, CXType_LongDouble = 23, CXType_NullPtr = 24, CXType_Overload = 25, CXType_Dependent = 26, CXType_ObjCId = 27, CXType_ObjCClass = 28, CXType_ObjCSel = 29, CXType_FirstBuiltin = CXType_Void, CXType_LastBuiltin = CXType_ObjCSel, CXType_Complex = 100, CXType_Pointer = 101, CXType_BlockPointer = 102, CXType_LValueReference = 103, CXType_RValueReference = 104, CXType_Record = 105, CXType_Enum = 106, CXType_Typedef = 107, CXType_ObjCInterface = 108, CXType_ObjCObjectPointer = 109, CXType_FunctionNoProto = 110, CXType_FunctionProto = 111, CXType_ConstantArray = 112, CXType_Vector = 113, CXType_IncompleteArray = 114, CXType_VariableArray = 115, CXType_DependentSizedArray = 116 }; enum CXCallingConv { CXCallingConv_Default = 0, CXCallingConv_C = 1, CXCallingConv_X86StdCall = 2, CXCallingConv_X86FastCall = 3, CXCallingConv_X86ThisCall = 4, CXCallingConv_X86Pascal = 5, CXCallingConv_AAPCS = 6, CXCallingConv_AAPCS_VFP = 7, CXCallingConv_PnaclCall = 8, CXCallingConv_IntelOclBicc = 9, CXCallingConv_Invalid = 100, CXCallingConv_Unexposed = 200 }; typedef struct { enum CXTypeKind kind; void *data[2]; } CXType; CXType clang_getCursorType(CXCursor C); CXString clang_getTypeSpelling(CXType CT); CXType clang_getTypedefDeclUnderlyingType(CXCursor C); CXType clang_getEnumDeclIntegerType(CXCursor C); long long clang_getEnumConstantDeclValue(CXCursor C); unsigned long long clang_getEnumConstantDeclUnsignedValue(CXCursor C); int clang_getFieldDeclBitWidth(CXCursor C); int clang_Cursor_getNumArguments(CXCursor C); CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i); unsigned clang_equalTypes(CXType A, CXType B); CXType clang_getCanonicalType(CXType T); unsigned clang_isConstQualifiedType(CXType T); unsigned clang_isVolatileQualifiedType(CXType T); unsigned clang_isRestrictQualifiedType(CXType T); CXType clang_getPointeeType(CXType T); CXCursor clang_getTypeDeclaration(CXType T); CXString clang_getDeclObjCTypeEncoding(CXCursor C); CXString clang_getTypeKindSpelling(enum CXTypeKind K); enum CXCallingConv clang_getFunctionTypeCallingConv(CXType T); CXType clang_getResultType(CXType T); int clang_getNumArgTypes(CXType T); CXType clang_getArgType(CXType T, unsigned i); unsigned clang_isFunctionTypeVariadic(CXType T); CXType clang_getCursorResultType(CXCursor C); unsigned clang_isPODType(CXType T); CXType clang_getElementType(CXType T); long long clang_getNumElements(CXType T); CXType clang_getArrayElementType(CXType T); long long clang_getArraySize(CXType T); enum CXTypeLayoutError { CXTypeLayoutError_Invalid = -1, CXTypeLayoutError_Incomplete = -2, CXTypeLayoutError_Dependent = -3, CXTypeLayoutError_NotConstantSize = -4, CXTypeLayoutError_InvalidFieldName = -5 }; long long clang_Type_getAlignOf(CXType T); long long clang_Type_getSizeOf(CXType T); long long clang_Type_getOffsetOf(CXType T, const char *S); unsigned clang_Cursor_isBitField(CXCursor C); unsigned clang_isVirtualBase(CXCursor); enum CX_CXXAccessSpecifier { CX_CXXInvalidAccessSpecifier, CX_CXXPublic, CX_CXXProtected, CX_CXXPrivate }; enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor); unsigned clang_getNumOverloadedDecls(CXCursor cursor); CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index); CXType clang_getIBOutletCollectionType(CXCursor); enum CXChildVisitResult { CXChildVisit_Break, CXChildVisit_Continue, CXChildVisit_Recurse }; typedef enum CXChildVisitResult (*CXCursorVisitor)(CXCursor cursor, CXCursor parent, CXClientData client_data); unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor, CXClientData client_data); CXString clang_getCursorUSR(CXCursor); CXString clang_constructUSR_ObjCClass(const char *class_name); CXString clang_constructUSR_ObjCCategory(const char *class_name, const char *category_name); CXString clang_constructUSR_ObjCProtocol(const char *protocol_name); CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR); CXString clang_constructUSR_ObjCMethod(const char *name, unsigned isInstanceMethod, CXString classUSR); CXString clang_constructUSR_ObjCProperty(const char *property, CXString classUSR); CXString clang_getCursorSpelling(CXCursor); CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor, unsigned pieceIndex, unsigned options); CXString clang_getCursorDisplayName(CXCursor); CXCursor clang_getCursorReferenced(CXCursor); CXCursor clang_getCursorDefinition(CXCursor); unsigned clang_isCursorDefinition(CXCursor); CXCursor clang_getCanonicalCursor(CXCursor); int clang_Cursor_getObjCSelectorIndex(CXCursor); int clang_Cursor_isDynamicCall(CXCursor C); CXType clang_Cursor_getReceiverType(CXCursor C); typedef enum { CXObjCPropertyAttr_noattr = 0x00, CXObjCPropertyAttr_readonly = 0x01, CXObjCPropertyAttr_getter = 0x02, CXObjCPropertyAttr_assign = 0x04, CXObjCPropertyAttr_readwrite = 0x08, CXObjCPropertyAttr_retain = 0x10, CXObjCPropertyAttr_copy = 0x20, CXObjCPropertyAttr_nonatomic = 0x40, CXObjCPropertyAttr_setter = 0x80, CXObjCPropertyAttr_atomic = 0x100, CXObjCPropertyAttr_weak = 0x200, CXObjCPropertyAttr_strong = 0x400, CXObjCPropertyAttr_unsafe_unretained = 0x800 } CXObjCPropertyAttrKind; unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved); typedef enum { CXObjCDeclQualifier_None = 0x0, CXObjCDeclQualifier_In = 0x1, CXObjCDeclQualifier_Inout = 0x2, CXObjCDeclQualifier_Out = 0x4, CXObjCDeclQualifier_Bycopy = 0x8, CXObjCDeclQualifier_Byref = 0x10, CXObjCDeclQualifier_Oneway = 0x20 } CXObjCDeclQualifierKind; unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C); unsigned clang_Cursor_isObjCOptional(CXCursor C); unsigned clang_Cursor_isVariadic(CXCursor C); CXSourceRange clang_Cursor_getCommentRange(CXCursor C); CXString clang_Cursor_getRawCommentText(CXCursor C); CXString clang_Cursor_getBriefCommentText(CXCursor C); CXComment clang_Cursor_getParsedComment(CXCursor C); typedef void *CXModule; CXModule clang_Cursor_getModule(CXCursor C); CXFile clang_Module_getASTFile(CXModule Module); CXModule clang_Module_getParent(CXModule Module); CXString clang_Module_getName(CXModule Module); CXString clang_Module_getFullName(CXModule Module); unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit, CXModule Module); CXFile clang_Module_getTopLevelHeader(CXTranslationUnit, CXModule Module, unsigned Index); enum CXCommentKind { CXComment_Null = 0, CXComment_Text = 1, CXComment_InlineCommand = 2, CXComment_HTMLStartTag = 3, CXComment_HTMLEndTag = 4, CXComment_Paragraph = 5, CXComment_BlockCommand = 6, CXComment_ParamCommand = 7, CXComment_TParamCommand = 8, CXComment_VerbatimBlockCommand = 9, CXComment_VerbatimBlockLine = 10, CXComment_VerbatimLine = 11, CXComment_FullComment = 12 }; enum CXCommentInlineCommandRenderKind { CXCommentInlineCommandRenderKind_Normal, CXCommentInlineCommandRenderKind_Bold, CXCommentInlineCommandRenderKind_Monospaced, CXCommentInlineCommandRenderKind_Emphasized }; enum CXCommentParamPassDirection { CXCommentParamPassDirection_In, CXCommentParamPassDirection_Out, CXCommentParamPassDirection_InOut }; enum CXCommentKind clang_Comment_getKind(CXComment Comment); unsigned clang_Comment_getNumChildren(CXComment Comment); CXComment clang_Comment_getChild(CXComment Comment, unsigned ChildIdx); unsigned clang_Comment_isWhitespace(CXComment Comment); unsigned clang_InlineContentComment_hasTrailingNewline(CXComment Comment); CXString clang_TextComment_getText(CXComment Comment); CXString clang_InlineCommandComment_getCommandName(CXComment Comment); enum CXCommentInlineCommandRenderKind clang_InlineCommandComment_getRenderKind(CXComment Comment); unsigned clang_InlineCommandComment_getNumArgs(CXComment Comment); CXString clang_InlineCommandComment_getArgText(CXComment Comment, unsigned ArgIdx); CXString clang_HTMLTagComment_getTagName(CXComment Comment); unsigned clang_HTMLStartTagComment_isSelfClosing(CXComment Comment); unsigned clang_HTMLStartTag_getNumAttrs(CXComment Comment); CXString clang_HTMLStartTag_getAttrName(CXComment Comment, unsigned AttrIdx); CXString clang_HTMLStartTag_getAttrValue(CXComment Comment, unsigned AttrIdx); CXString clang_BlockCommandComment_getCommandName(CXComment Comment); unsigned clang_BlockCommandComment_getNumArgs(CXComment Comment); CXString clang_BlockCommandComment_getArgText(CXComment Comment, unsigned ArgIdx); CXComment clang_BlockCommandComment_getParagraph(CXComment Comment); CXString clang_ParamCommandComment_getParamName(CXComment Comment); unsigned clang_ParamCommandComment_isParamIndexValid(CXComment Comment); unsigned clang_ParamCommandComment_getParamIndex(CXComment Comment); unsigned clang_ParamCommandComment_isDirectionExplicit(CXComment Comment); enum CXCommentParamPassDirection clang_ParamCommandComment_getDirection( CXComment Comment); CXString clang_TParamCommandComment_getParamName(CXComment Comment); unsigned clang_TParamCommandComment_isParamPositionValid(CXComment Comment); unsigned clang_TParamCommandComment_getDepth(CXComment Comment); unsigned clang_TParamCommandComment_getIndex(CXComment Comment, unsigned Depth); CXString clang_VerbatimBlockLineComment_getText(CXComment Comment); CXString clang_VerbatimLineComment_getText(CXComment Comment); CXString clang_HTMLTagComment_getAsString(CXComment Comment); CXString clang_FullComment_getAsHTML(CXComment Comment); CXString clang_FullComment_getAsXML(CXComment Comment); unsigned clang_CXXMethod_isPureVirtual(CXCursor C); unsigned clang_CXXMethod_isStatic(CXCursor C); unsigned clang_CXXMethod_isVirtual(CXCursor C); enum CXCursorKind clang_getTemplateCursorKind(CXCursor C); CXCursor clang_getSpecializedCursorTemplate(CXCursor C); CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags, unsigned PieceIndex); enum CXNameRefFlags { CXNameRange_WantQualifier = 0x1, CXNameRange_WantTemplateArgs = 0x2, CXNameRange_WantSinglePiece = 0x4 }; typedef enum CXTokenKind { CXToken_Punctuation, CXToken_Keyword, CXToken_Identifier, CXToken_Literal, CXToken_Comment } CXTokenKind; typedef struct { unsigned int_data[4]; void *ptr_data; } CXToken; CXTokenKind clang_getTokenKind(CXToken); CXString clang_getTokenSpelling(CXTranslationUnit, CXToken); CXSourceLocation clang_getTokenLocation(CXTranslationUnit, CXToken); CXSourceRange clang_getTokenExtent(CXTranslationUnit, CXToken); void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, CXToken **Tokens, unsigned *NumTokens); void clang_annotateTokens(CXTranslationUnit TU, CXToken *Tokens, unsigned NumTokens, CXCursor *Cursors); void clang_disposeTokens(CXTranslationUnit TU, CXToken *Tokens, unsigned NumTokens); /* for debug/testing */ CXString clang_getCursorKindSpelling(enum CXCursorKind Kind); void clang_getDefinitionSpellingAndExtent(CXCursor, const char **startBuf, const char **endBuf, unsigned *startLine, unsigned *startColumn, unsigned *endLine, unsigned *endColumn); void clang_enableStackTraces(void); void clang_executeOnThread(void (*fn)(void*), void *user_data, unsigned stack_size); typedef void *CXCompletionString; typedef struct { enum CXCursorKind CursorKind; CXCompletionString CompletionString; } CXCompletionResult; enum CXCompletionChunkKind { CXCompletionChunk_Optional, CXCompletionChunk_TypedText, CXCompletionChunk_Text, CXCompletionChunk_Placeholder, CXCompletionChunk_Informative, CXCompletionChunk_CurrentParameter, CXCompletionChunk_LeftParen, CXCompletionChunk_RightParen, CXCompletionChunk_LeftBracket, CXCompletionChunk_RightBracket, CXCompletionChunk_LeftBrace, CXCompletionChunk_RightBrace, CXCompletionChunk_LeftAngle, CXCompletionChunk_RightAngle, CXCompletionChunk_Comma, CXCompletionChunk_ResultType, CXCompletionChunk_Colon, CXCompletionChunk_SemiColon, CXCompletionChunk_Equal, CXCompletionChunk_HorizontalSpace, CXCompletionChunk_VerticalSpace }; enum CXCompletionChunkKind clang_getCompletionChunkKind(CXCompletionString completion_string, unsigned chunk_number); CXString clang_getCompletionChunkText(CXCompletionString completion_string, unsigned chunk_number); CXCompletionString clang_getCompletionChunkCompletionString(CXCompletionString completion_string, unsigned chunk_number); unsigned clang_getNumCompletionChunks(CXCompletionString completion_string); unsigned clang_getCompletionPriority(CXCompletionString completion_string); enum CXAvailabilityKind clang_getCompletionAvailability(CXCompletionString completion_string); unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string); CXString clang_getCompletionAnnotation(CXCompletionString completion_string, unsigned annotation_number); CXString clang_getCompletionParent(CXCompletionString completion_string, enum CXCursorKind *kind); CXString clang_getCompletionBriefComment(CXCompletionString completion_string); CXCompletionString clang_getCursorCompletionString(CXCursor cursor); typedef struct { CXCompletionResult *Results; unsigned NumResults; } CXCodeCompleteResults; enum CXCodeComplete_Flags { CXCodeComplete_IncludeMacros = 0x01, CXCodeComplete_IncludeCodePatterns = 0x02, CXCodeComplete_IncludeBriefComments = 0x04 }; enum CXCompletionContext { CXCompletionContext_Unexposed = 0, CXCompletionContext_AnyType = 1 << 0, CXCompletionContext_AnyValue = 1 << 1, CXCompletionContext_ObjCObjectValue = 1 << 2, CXCompletionContext_ObjCSelectorValue = 1 << 3, CXCompletionContext_CXXClassTypeValue = 1 << 4, CXCompletionContext_DotMemberAccess = 1 << 5, CXCompletionContext_ArrowMemberAccess = 1 << 6, CXCompletionContext_ObjCPropertyAccess = 1 << 7, CXCompletionContext_EnumTag = 1 << 8, CXCompletionContext_UnionTag = 1 << 9, CXCompletionContext_StructTag = 1 << 10, CXCompletionContext_ClassTag = 1 << 11, CXCompletionContext_Namespace = 1 << 12, CXCompletionContext_NestedNameSpecifier = 1 << 13, CXCompletionContext_ObjCInterface = 1 << 14, CXCompletionContext_ObjCProtocol = 1 << 15, CXCompletionContext_ObjCCategory = 1 << 16, CXCompletionContext_ObjCInstanceMessage = 1 << 17, CXCompletionContext_ObjCClassMessage = 1 << 18, CXCompletionContext_ObjCSelectorName = 1 << 19, CXCompletionContext_MacroName = 1 << 20, CXCompletionContext_NaturalLanguage = 1 << 21, CXCompletionContext_Unknown = ((1 << 22) - 1) }; unsigned clang_defaultCodeCompleteOptions(void); CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU, const char *complete_filename, unsigned complete_line, unsigned complete_column, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, unsigned options); void clang_sortCodeCompletionResults(CXCompletionResult *Results, unsigned NumResults); void clang_disposeCodeCompleteResults(CXCodeCompleteResults *Results); unsigned clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *Results); CXDiagnostic clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *Results, unsigned Index); unsigned long long clang_codeCompleteGetContexts( CXCodeCompleteResults *Results); enum CXCursorKind clang_codeCompleteGetContainerKind( CXCodeCompleteResults *Results, unsigned *IsIncomplete); CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *Results); CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *Results); CXString clang_getClangVersion(void); void clang_toggleCrashRecovery(unsigned isEnabled); typedef void (*CXInclusionVisitor)(CXFile included_file, CXSourceLocation* inclusion_stack, unsigned include_len, CXClientData client_data); void clang_getInclusions(CXTranslationUnit tu, CXInclusionVisitor visitor, CXClientData client_data); typedef void *CXRemapping; CXRemapping clang_getRemappings(const char *path); CXRemapping clang_getRemappingsFromFileList(const char **filePaths, unsigned numFiles); unsigned clang_remap_getNumFiles(CXRemapping); void clang_remap_getFilenames(CXRemapping, unsigned index, CXString *original, CXString *transformed); void clang_remap_dispose(CXRemapping); enum CXVisitorResult { CXVisit_Break, CXVisit_Continue }; typedef struct { void *context; enum CXVisitorResult (*visit)(void *context, CXCursor, CXSourceRange); } CXCursorAndRangeVisitor; typedef enum { CXResult_Success = 0, CXResult_Invalid = 1, CXResult_VisitBreak = 2 } CXResult; CXResult clang_findReferencesInFile(CXCursor cursor, CXFile file, CXCursorAndRangeVisitor visitor); CXResult clang_findIncludesInFile(CXTranslationUnit TU, CXFile file, CXCursorAndRangeVisitor visitor); typedef void *CXIdxClientFile; typedef void *CXIdxClientEntity; typedef void *CXIdxClientContainer; typedef void *CXIdxClientASTFile; typedef struct { void *ptr_data[2]; unsigned int_data; } CXIdxLoc; typedef struct { CXIdxLoc hashLoc; const char *filename; CXFile file; int isImport; int isAngled; int isModuleImport; } CXIdxIncludedFileInfo; typedef struct { CXFile file; CXModule module; CXIdxLoc loc; int isImplicit; } CXIdxImportedASTFileInfo; typedef enum { CXIdxEntity_Unexposed = 0, CXIdxEntity_Typedef = 1, CXIdxEntity_Function = 2, CXIdxEntity_Variable = 3, CXIdxEntity_Field = 4, CXIdxEntity_EnumConstant = 5, CXIdxEntity_ObjCClass = 6, CXIdxEntity_ObjCProtocol = 7, CXIdxEntity_ObjCCategory = 8, CXIdxEntity_ObjCInstanceMethod = 9, CXIdxEntity_ObjCClassMethod = 10, CXIdxEntity_ObjCProperty = 11, CXIdxEntity_ObjCIvar = 12, CXIdxEntity_Enum = 13, CXIdxEntity_Struct = 14, CXIdxEntity_Union = 15, CXIdxEntity_CXXClass = 16, CXIdxEntity_CXXNamespace = 17, CXIdxEntity_CXXNamespaceAlias = 18, CXIdxEntity_CXXStaticVariable = 19, CXIdxEntity_CXXStaticMethod = 20, CXIdxEntity_CXXInstanceMethod = 21, CXIdxEntity_CXXConstructor = 22, CXIdxEntity_CXXDestructor = 23, CXIdxEntity_CXXConversionFunction = 24, CXIdxEntity_CXXTypeAlias = 25, CXIdxEntity_CXXInterface = 26 } CXIdxEntityKind; typedef enum { CXIdxEntityLang_None = 0, CXIdxEntityLang_C = 1, CXIdxEntityLang_ObjC = 2, CXIdxEntityLang_CXX = 3 } CXIdxEntityLanguage; typedef enum { CXIdxEntity_NonTemplate = 0, CXIdxEntity_Template = 1, CXIdxEntity_TemplatePartialSpecialization = 2, CXIdxEntity_TemplateSpecialization = 3 } CXIdxEntityCXXTemplateKind; typedef enum { CXIdxAttr_Unexposed = 0, CXIdxAttr_IBAction = 1, CXIdxAttr_IBOutlet = 2, CXIdxAttr_IBOutletCollection = 3 } CXIdxAttrKind; typedef struct { CXIdxAttrKind kind; CXCursor cursor; CXIdxLoc loc; } CXIdxAttrInfo; typedef struct { CXIdxEntityKind kind; CXIdxEntityCXXTemplateKind templateKind; CXIdxEntityLanguage lang; const char *name; const char *USR; CXCursor cursor; const CXIdxAttrInfo *const *attributes; unsigned numAttributes; } CXIdxEntityInfo; typedef struct { CXCursor cursor; } CXIdxContainerInfo; typedef struct { const CXIdxAttrInfo *attrInfo; const CXIdxEntityInfo *objcClass; CXCursor classCursor; CXIdxLoc classLoc; } CXIdxIBOutletCollectionAttrInfo; typedef enum { CXIdxDeclFlag_Skipped = 0x1 } CXIdxDeclInfoFlags; typedef struct { const CXIdxEntityInfo *entityInfo; CXCursor cursor; CXIdxLoc loc; const CXIdxContainerInfo *semanticContainer; const CXIdxContainerInfo *lexicalContainer; int isRedeclaration; int isDefinition; int isContainer; const CXIdxContainerInfo *declAsContainer; int isImplicit; const CXIdxAttrInfo *const *attributes; unsigned numAttributes; unsigned flags; } CXIdxDeclInfo; typedef enum { CXIdxObjCContainer_ForwardRef = 0, CXIdxObjCContainer_Interface = 1, CXIdxObjCContainer_Implementation = 2 } CXIdxObjCContainerKind; typedef struct { const CXIdxDeclInfo *declInfo; CXIdxObjCContainerKind kind; } CXIdxObjCContainerDeclInfo; typedef struct { const CXIdxEntityInfo *base; CXCursor cursor; CXIdxLoc loc; } CXIdxBaseClassInfo; typedef struct { const CXIdxEntityInfo *protocol; CXCursor cursor; CXIdxLoc loc; } CXIdxObjCProtocolRefInfo; typedef struct { const CXIdxObjCProtocolRefInfo *const *protocols; unsigned numProtocols; } CXIdxObjCProtocolRefListInfo; typedef struct { const CXIdxObjCContainerDeclInfo *containerInfo; const CXIdxBaseClassInfo *superInfo; const CXIdxObjCProtocolRefListInfo *protocols; } CXIdxObjCInterfaceDeclInfo; typedef struct { const CXIdxObjCContainerDeclInfo *containerInfo; const CXIdxEntityInfo *objcClass; CXCursor classCursor; CXIdxLoc classLoc; const CXIdxObjCProtocolRefListInfo *protocols; } CXIdxObjCCategoryDeclInfo; typedef struct { const CXIdxDeclInfo *declInfo; const CXIdxEntityInfo *getter; const CXIdxEntityInfo *setter; } CXIdxObjCPropertyDeclInfo; typedef struct { const CXIdxDeclInfo *declInfo; const CXIdxBaseClassInfo *const *bases; unsigned numBases; } CXIdxCXXClassDeclInfo; typedef enum { CXIdxEntityRef_Direct = 1, CXIdxEntityRef_Implicit = 2 } CXIdxEntityRefKind; typedef struct { CXIdxEntityRefKind kind; CXCursor cursor; CXIdxLoc loc; const CXIdxEntityInfo *referencedEntity; const CXIdxEntityInfo *parentEntity; const CXIdxContainerInfo *container; } CXIdxEntityRefInfo; typedef struct { int (*abortQuery)(CXClientData client_data, void *reserved); void (*diagnostic)(CXClientData client_data, CXDiagnosticSet, void *reserved); CXIdxClientFile (*enteredMainFile)(CXClientData client_data, CXFile mainFile, void *reserved); CXIdxClientFile (*ppIncludedFile)(CXClientData client_data, const CXIdxIncludedFileInfo *); CXIdxClientASTFile (*importedASTFile)(CXClientData client_data, const CXIdxImportedASTFileInfo *); CXIdxClientContainer (*startedTranslationUnit)(CXClientData client_data, void *reserved); void (*indexDeclaration)(CXClientData client_data, const CXIdxDeclInfo *); void (*indexEntityReference)(CXClientData client_data, const CXIdxEntityRefInfo *); } IndexerCallbacks; int clang_index_isEntityObjCContainerKind(CXIdxEntityKind); const CXIdxObjCContainerDeclInfo * clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *); const CXIdxObjCInterfaceDeclInfo * clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *); const CXIdxObjCCategoryDeclInfo * clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *); const CXIdxObjCProtocolRefListInfo * clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *); const CXIdxObjCPropertyDeclInfo * clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *); const CXIdxIBOutletCollectionAttrInfo * clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *); const CXIdxCXXClassDeclInfo * clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *); CXIdxClientContainer clang_index_getClientContainer(const CXIdxContainerInfo *); void clang_index_setClientContainer(const CXIdxContainerInfo *,CXIdxClientContainer); CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *); void clang_index_setClientEntity(const CXIdxEntityInfo *, CXIdxClientEntity); typedef void *CXIndexAction; CXIndexAction clang_IndexAction_create(CXIndex CIdx); void clang_IndexAction_dispose(CXIndexAction); typedef enum { CXIndexOpt_None = 0x0, CXIndexOpt_SuppressRedundantRefs = 0x1, CXIndexOpt_IndexFunctionLocalSymbols = 0x2, CXIndexOpt_IndexImplicitTemplateInstantiations = 0x4, CXIndexOpt_SuppressWarnings = 0x8, CXIndexOpt_SkipParsedBodiesInSession = 0x10 } CXIndexOptFlags; int clang_indexSourceFile(CXIndexAction, CXClientData client_data, IndexerCallbacks *index_callbacks, unsigned index_callbacks_size, unsigned index_options, const char *source_filename, const char * const *command_line_args, int num_command_line_args, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, CXTranslationUnit *out_TU, unsigned TU_options); int clang_indexTranslationUnit(CXIndexAction, CXClientData client_data, IndexerCallbacks *index_callbacks, unsigned index_callbacks_size, unsigned index_options, CXTranslationUnit); void clang_indexLoc_getFileLocation(CXIdxLoc loc, CXIdxClientFile *indexFile, CXFile *file, unsigned *line, unsigned *column, unsigned *offset); CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc loc); ]==========]
mit
shiprabehera/kong
spec/01-unit/01-db/02-cassandra_spec.lua
7
2407
local cassandra_db = require "kong.dao.db.cassandra" describe("cassandra_db", function() describe("extract_major()", function() it("extract major version digit", function() assert.equal("3", cassandra_db.extract_major("3.7")) assert.equal("3", cassandra_db.extract_major("3.7.12")) assert.equal("2", cassandra_db.extract_major("2.1.14")) assert.equal("2", cassandra_db.extract_major("2.10")) assert.equal("10", cassandra_db.extract_major("10.0")) end) end) describe("cluster_release_version()", function() it("extracts major release_version from available peers", function() local release_version = assert(cassandra_db.cluster_release_version { { host = "127.0.0.1", release_version = "3.7", }, { host = "127.0.0.2", release_version = "3.7", }, { host = "127.0.0.3", release_version = "3.1.2", } }) assert.equal(3, release_version) local release_version = assert(cassandra_db.cluster_release_version { { host = "127.0.0.1", release_version = "2.14", }, { host = "127.0.0.2", release_version = "2.11.14", }, { host = "127.0.0.3", release_version = "2.2.4", } }) assert.equal(2, release_version) end) it("errors with different major versions", function() local release_version, err = cassandra_db.cluster_release_version { { host = "127.0.0.1", release_version = "3.7", }, { host = "127.0.0.2", release_version = "3.7", }, { host = "127.0.0.3", release_version = "2.11.14", } } assert.is_nil(release_version) assert.equal("different major versions detected (only all of 2.x or 3.x supported): 127.0.0.1 (3.7) 127.0.0.2 (3.7) 127.0.0.3 (2.11.14)", err) end) it("errors if a peer is missing release_version", function() local release_version, err = cassandra_db.cluster_release_version { { host = "127.0.0.1", release_version = "3.7", }, { host = "127.0.0.2" } } assert.is_nil(release_version) assert.equal("no release_version for peer 127.0.0.2", err) end) end) end)
apache-2.0
Beagle/wesnoth
data/ai/micro_ais/cas/ca_swarm_move.lua
26
2504
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require "ai/lua/ai_helper.lua" local ca_swarm_move = {} function ca_swarm_move:evaluation(ai, cfg) local units = wesnoth.get_units { side = wesnoth.current.side } for _,unit in ipairs(units) do if (unit.moves > 0) then return cfg.ca_score end end return 0 end function ca_swarm_move:execution(ai, cfg) local enemy_distance = cfg.enemy_distance or 5 local vision_distance = cfg.vision_distance or 12 -- If no close enemies, swarm will move semi-randomly, staying close together, but away from enemies local all_units = wesnoth.get_units { side = wesnoth.current.side } local units, units_no_moves = {}, {} for _,unit in ipairs(all_units) do if (unit.moves > 0) then table.insert(units, unit) else table.insert(units_no_moves, unit) end end local enemies = wesnoth.get_units { { "filter_side", { { "enemy_of", {side = wesnoth.current.side } } } } } -- Pick one unit at random, swarm does not move systematically local unit = units[math.random(#units)] -- Find best place for that unit to move to local best_hex = AH.find_best_move(unit, function(x, y) local rating = 0 -- Only units within 'vision_distance' count for rejoining local close_units_no_moves = {} for _,unit_noMP in ipairs(units_no_moves) do if (H.distance_between(unit.x, unit.y, unit_noMP.x, unit_noMP.y) <= vision_distance) then table.insert(close_units_no_moves, unit_noMP) end end -- If all units on the side have moves left, simply go to a hex far away if (not close_units_no_moves[1]) then rating = rating + H.distance_between(x, y, unit.x, unit.y) else -- Otherwise, minimize distance from units that have already moved for _,close_unit in ipairs(close_units_no_moves) do rating = rating - H.distance_between(x, y, close_unit.x, close_unit.y) end end -- We also try to stay out of attack range of any enemy for _,enemy in ipairs(enemies) do local dist = H.distance_between(x, y, enemy.x, enemy.y) if (dist < enemy_distance) then rating = rating - (enemy_distance - dist) * 10. end end return rating end) AH.movefull_stopunit(ai, unit, best_hex) end return ca_swarm_move
gpl-2.0
SajayAntony/wrk
deps/luajit/src/jit/v.lua
88
5614
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1 loop] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20004, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..oex..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then out:write(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else out:write(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local info = traceinfo(tr) local link, ltype = info.link, info.linktype if ltype == "interpreter" then out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif link == tr or link == 0 then out:write(format("[TRACE %3s %s%s %s]\n", tr, startex, startloc, ltype)) elseif ltype == "root" then out:write(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) else out:write(format("[TRACE %3s %s%s -> %d %s]\n", tr, startex, startloc, link, ltype)) end else out:write(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. module(...) on = dumpon off = dumpoff start = dumpon -- For -j command line option.
apache-2.0
m13790115/ssss
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
sunyi00/wrk
deps/luajit/src/jit/dis_x86.lua
89
29330
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM) -- instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. -- * The public API may change when more architectures are added. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrm|movupdXrm|movsdXrm", "movupsXmr|movssXmr|movupdXmr|movsdXmr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrm||unpcklpdXrm", "unpckhpsXrm||unpckhpdXrm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm", "andpsXrm||andpdXrm","andnpsXrm||andnpdXrm", "orpsXrm||orpdXrm","xorpsXrm||xorpdXrm", "addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm", "cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm", "divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm", --6x "punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm", "pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm", "punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm", "||punpcklqdqXrm","||punpckhqdqXrm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu", "pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu", "pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|", "pinsrwPrWmu","pextrwDrPmu", "shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm", "paddqPrm","pmullwPrm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrm","psubuswPrm","pminubPrm","pandPrm", "paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm", --Ex "pavgbPrm","psrawPrm","psradPrm","pavgwPrm", "pmulhuwPrm","pmulhwPrm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrm","psubswPrm","pminswPrm","porPrm", "paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm", --Fx "|||lddquXrm","psllwPrm","pslldPrm","psllqPrm", "pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$", "psubbPrm","psubwPrm","psubdPrm","psubqPrm", "paddbPrm","paddwPrm","padddPrm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm", "pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm", "psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm", nil,nil,nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm", nil,nil,nil,nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm", nil,nil,nil,nil, --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm", "||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm", "||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm", --4x "||pmulddXrm","||phminposuwXrm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]=nil,nil,nil,nil,nil,nil,nil,nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu", "||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", nil,nil,nil,nil,nil,nil,nil,nil, --2x "||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil, --4x [0x40] = "||dppsXrmu", [0x41] = "||dppdXrmu", [0x42] = "||mpsadbwXrmu", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "") if t ~= "" then text = "rex."..t.." "..text end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop = ctx.code, ctx.pos, ctx.stop -- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXFG]") then sz = p regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = format("0x%08x", imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = true end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") end, } ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create_(code, addr, out) local ctx = {} ctx.code = code ctx.addr = (addr or 0) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64_(code, addr, out) local ctx = create_(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass_(code, addr, out) create_(code, addr, out):disass() end local function disass64_(code, addr, out) create64_(code, addr, out):disass() end -- Return register name for RID. local function regname_(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64_(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. module(...) create = create_ create64 = create64_ disass = disass_ disass64 = disass64_ regname = regname_ regname64 = regname64_
apache-2.0
liruqi/bigfoot
Interface/AddOns/DBM-Nighthold/ChronoAnomaly.lua
1
21033
local mod = DBM:NewMod(1725, "DBM-Nighthold", nil, 786) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 17522 $"):sub(12, -3)) mod:SetCreatureID(104415)--104731 (Depleted Time Particle). 104676 (Waning Time Particle). 104491 (Accelerated Time particle). 104492 (Slow Time Particle) mod:SetEncounterID(1865) mod:SetZone() --mod:SetUsedIcons(5, 4, 3, 2, 1)--sometimes it was 5 targets, sometimes it was whole raid. even post nerf. have to see mod:SetHotfixNoticeRev(15910) mod.respawnTime = 29 mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_CAST_START 211927 207228", "SPELL_CAST_SUCCESS 219815", "SPELL_AURA_APPLIED 206617 206607 212099", "SPELL_AURA_APPLIED_DOSE 206607 219823", "SPELL_AURA_REMOVED 206617", "UNIT_SPELLCAST_SUCCEEDED boss1 boss2 boss3 boss4 boss5", "UNIT_SPELLCAST_CHANNEL_STOP boss1 boss2 boss3 boss4 boss5", "UNIT_SPELLCAST_STOP boss1 boss2 boss3 boss4 boss5" ) --TODO, More data to complete sequences of timers on LFR/Heroic/Normal --(ability.id = 206618 or ability.id = 206610 or ability.id = 206614) and type = "cast" or ability.id = 211927 local warnNormal = mod:NewCountAnnounce(207012, 2) local warnFast = mod:NewCountAnnounce(207013, 2) local warnSlow = mod:NewCountAnnounce(207011, 2) local warnTimeBomb = mod:NewTargetAnnounce(206617, 3) local warnChronometricPart = mod:NewStackAnnounce(206607, 3, nil, "Tank") local warnPowerOverwhelmingStack = mod:NewStackAnnounce(219823, 2) local warnTemporalCharge = mod:NewTargetAnnounce(212099, 1) local specWarnTemporalOrbs = mod:NewSpecialWarningDodge(219815, nil, nil, nil, 2, 2) local specWarnPowerOverwhelming = mod:NewSpecialWarningSpell(211927, nil, nil, 2, 2, 2) local specWarnTimeBomb = mod:NewSpecialWarningMoveAway(206617, nil, nil, 2, 3, 2)--When close to expiring, not right away local yellTimeBomb = mod:NewFadesYell(206617) local specWarnWarp = mod:NewSpecialWarningInterrupt(207228, "HasInterrupt", nil, nil, 1, 2) local specWarnBigAdd = mod:NewSpecialWarningSwitch("ej13022", "-Healer", nil, nil, 1, 2)--Switch to waning time particle when section info known local timerTemporalOrbsCD = mod:NewNextCountTimer(30, 219815, nil, nil, nil, 2) local timerPowerOverwhelmingCD = mod:NewNextCountTimer(60, 211927, nil, nil, nil, 4, nil, DBM_CORE_INTERRUPT_ICON) local timerTimeBomb = mod:NewBuffFadesTimer(30, 206617, nil, nil, nil, 5) local timerTimeBombCD = mod:NewNextCountTimer(30, 206617, nil, nil, nil, 3) local timerBurstofTimeCD = mod:NewNextCountTimer(30, 206614, nil, nil, nil, 3) local timerTimeReleaseCD = mod:NewNextCountTimer(30, 206610, nil, "Healer", nil, 5, nil, DBM_CORE_HEALER_ICON) local timerChronoPartCD = mod:NewCDTimer(5, 206607, nil, "Tank", nil, 5, nil, DBM_CORE_TANK_ICON) local timerBigAddCD = mod:NewNextCountTimer(30, 206700, nil, nil, nil, 1)--Switch to waning time particle when section info known local timerNextPhase = mod:NewPhaseTimer(74)--Used anywhere phase change is NOT immediately after power overwhelming local countdownBigAdd = mod:NewCountdown(30, 206700)--Switch to waning time particle when section info known local countdownTimeBomb = mod:NewCountdownFades("AltTwo30", 206617) mod:AddRangeFrameOption(10, 206617) mod:AddInfoFrameOption(206610) mod:AddDropdownOption("InfoFrameBehavior", {"TimeRelease", "TimeBomb"}, "TimeRelease", "misc") mod.vb.normCount = 0 mod.vb.fastCount = 0 mod.vb.slowCount = 0 mod.vb.currentPhase = 2 mod.vb.interruptCount = 0 mod.vb.timeBombDebuffCount = 0 local timeBombDebuff = DBM:GetSpellInfo(206617) local timeRelease = DBM:GetSpellInfo(206610) local function updateTimeBomb(self) local _, _, _, _, _, _, expires = UnitDebuff("player", timeBombDebuff) if expires then specWarnTimeBomb:Cancel() specWarnTimeBomb:CancelVoice() timerTimeBomb:Stop() countdownTimeBomb:Cancel() yellTimeBomb:Cancel() local debuffTime = expires - GetTime() specWarnTimeBomb:Schedule(debuffTime - 5) -- Show "move away" warning 5secs before explode specWarnTimeBomb:ScheduleVoice(debuffTime - 5, "runout") timerTimeBomb:Start(debuffTime) countdownTimeBomb:Start(debuffTime) yellTimeBomb:Schedule(debuffTime-1, 1) yellTimeBomb:Schedule(debuffTime-2, 2) yellTimeBomb:Schedule(debuffTime-3, 3) end end function mod:OnCombatStart(delay) self.vb.currentPhase = 2 self.vb.interruptCount = 0 self.vb.normCount = 0 self.vb.fastCount = 0 self.vb.slowCount = 0 self.vb.timeBombDebuffCount = 0 if self.Options.InfoFrame and self.Options.InfoFrameBehavior == "TimeRelease" then DBM.InfoFrame:SetHeader(timeRelease) DBM.InfoFrame:Show(10, "playerabsorb", timeRelease) end end function mod:OnCombatEnd() if self.Options.RangeFrame then DBM.RangeCheck:Hide() end if self.Options.InfoFrame then DBM.InfoFrame:Hide() end end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 211927 then timerChronoPartCD:Stop()--Will be used immediately when this ends. specWarnPowerOverwhelming:Show() specWarnPowerOverwhelming:Play("aesoon") elseif spellId == 207228 and self:CheckInterruptFilter(args.sourceGUID, false, true) then specWarnWarp:Show(args.sourceName) specWarnWarp:Play("kickcast") end end function mod:SPELL_CAST_SUCCESS(args) local spellId = args.spellId if spellId == 219815 then specWarnTemporalOrbs:Show() specWarnTemporalOrbs:Play("watchstep") end end function mod:SPELL_AURA_APPLIED(args) local spellId = args.spellId if spellId == 206617 then self.vb.timeBombDebuffCount = self.vb.timeBombDebuffCount + 1 warnTimeBomb:CombinedShow(0.5, args.destName) if args:IsPlayer() then updateTimeBomb(self) if self.Options.RangeFrame then DBM.RangeCheck:Show(10) end end if self.Options.InfoFrame and not DBM.InfoFrame:IsShown() and self.Options.InfoFrameBehavior == "TimeBomb" then DBM.InfoFrame:SetHeader(args.spellName) DBM.InfoFrame:Show(10, "playerdebuffremaining", args.spellName) end elseif spellId == 206607 then local amount = args.amount or 1 warnChronometricPart:Show(args.destName, amount) timerChronoPartCD:Start()--Move timer to success if this can be avoided elseif spellId == 219823 then local amount = args.amount or 1 warnPowerOverwhelmingStack:Show(args.destName, amount) elseif spellId == 212099 and args:IsDestTypePlayer() then warnTemporalCharge:Show(args.destName) end end mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED function mod:SPELL_AURA_REMOVED(args) local spellId = args.spellId if spellId == 206617 then self.vb.timeBombDebuffCount = self.vb.timeBombDebuffCount - 1 if args:IsPlayer() then specWarnTimeBomb:Cancel() specWarnTimeBomb:CancelVoice() timerTimeBomb:Stop() countdownTimeBomb:Cancel() yellTimeBomb:Cancel() if self.Options.RangeFrame then DBM.RangeCheck:Hide() end end if self.Options.InfoFrame and self.vb.timeBombDebuffCount == 0 and self.Options.InfoFrameBehavior == "TimeBomb" then DBM.InfoFrame:Hide() end end end local function delayedBurst(self, time, count) timerBurstofTimeCD:Start(time, count) end local function delayedTimeRelease(self, time, count) timerTimeReleaseCD:Start(time, count) end local function delayedTimeBomb(self, time, count) timerTimeBombCD:Start(time, count) end local function delayedOrbs(self, time, count) timerTemporalOrbsCD:Start(time, count) end function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, spellGUID) local spellId = tonumber(select(5, strsplit("-", spellGUID)), 10) if spellId == 207012 then--Speed: Normal self.vb.currentPhase = 2 self.vb.interruptCount = 0 self.vb.normCount = self.vb.normCount + 1 warnNormal:Show(self.vb.normCount) if self.vb.normCount == 1 then if self:IsMythic() then--Updated Jan 25 timerTimeBombCD:Start(5, 1) timerTimeReleaseCD:Start(10, 1) timerNextPhase:Start(12) elseif self:IsHeroic() then--UPDATED Jan 18 timerTimeReleaseCD:Start(5, 1) self:Schedule(5, delayedTimeRelease, self, 13, 2)--18 timerBigAddCD:Start(23, 1) countdownBigAdd:Start(23) timerTimeBombCD:Start(28, 1) self:Schedule(28, delayedTimeBomb, self, 5, 2)--33 timerTemporalOrbsCD:Start(38, 1) self:Schedule(30, delayedTimeRelease, self, 13, 3)--43 timerPowerOverwhelmingCD:Start(53, 1) elseif self:IsNormal() then--Updated Jan 17 timerTimeReleaseCD:Start(5, 1) self:Schedule(5, delayedTimeRelease, self, 15, 2)--20 timerBigAddCD:Start(28, 1) countdownBigAdd:Start(28) timerTimeBombCD:Start(35, 1) timerTemporalOrbsCD:Start(48, 1) timerPowerOverwhelmingCD:Start(84, 1) else--LFR end elseif self.vb.normCount == 2 then if self:IsMythic() then--Updated Jan 25 timerTimeReleaseCD:Start(2, 1) timerTemporalOrbsCD:Start(7, 1) timerTimeBombCD:Start(12, 1) timerPowerOverwhelmingCD:Start(17, 1) elseif self:IsHeroic() then--Updated May 26 2017 timerTimeBombCD:Start(5, 1) timerTemporalOrbsCD:Start(10, 1) self:Schedule(5, delayedTimeBomb, self, 10, 2)--15 timerBigAddCD:Start(20, 1) countdownBigAdd:Start(20) self:Schedule(15, delayedTimeBomb, self, 10, 3)--25 timerTimeReleaseCD:Start(30, 1) self:Schedule(10, delayedOrbs, self, 25, 2)--35 self:Schedule(30, delayedTimeRelease, self, 20, 2)--50 self:Schedule(50, delayedTimeRelease, self, 7, 3)--57 self:Schedule(35, delayedOrbs, self, 30, 3)--65 timerPowerOverwhelmingCD:Start(72, 1) --Triggers special extention phase after interrupt elseif self:IsNormal() then DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end elseif self.vb.normCount == 3 then if self:IsMythic() then--Updated Jan 25 timerTemporalOrbsCD:Start(2, 1) timerTimeBombCD:Start(7, 1) timerNextPhase:Start(12) elseif self:IsHeroic() then--Probably changed. DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end elseif self.vb.normCount == 4 then if self:IsMythic() then--Updated Jan 25 timerTimeBombCD:Start(2, 1) timerNextPhase:Start(5) elseif self:IsHeroic() then--Probably changed. DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end else DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") end updateTimeBomb(self) self:Schedule(2, updateTimeBomb, self) self:Schedule(5, updateTimeBomb, self) elseif spellId == 207011 then--Speed: Slow self.vb.currentPhase = 1 self.vb.interruptCount = 0 self.vb.slowCount = self.vb.slowCount + 1 warnSlow:Show(self.vb.slowCount) if self.vb.slowCount == 1 then if self:IsMythic() then--Updated Jan 25 timerTemporalOrbsCD:Start(8, 1) timerTimeReleaseCD:Start(13, 1) timerTimeBombCD:Start(16, 1) self:Schedule(13, delayedTimeRelease, self, 10, 2)--23 timerPowerOverwhelmingCD:Start(28, 1) elseif self:IsHeroic() then--Updated Jan 18 timerTimeReleaseCD:Start(10, 1) timerTimeBombCD:Start(15, 1) timerTemporalOrbsCD:Start(20, 1) self:Schedule(10, delayedTimeBomb, self, 15, 2)--25 self:Schedule(5, delayedTimeRelease, self, 25, 2)--30 self:Schedule(25, delayedTimeBomb, self, 10, 3)--35 self:Schedule(20, delayedOrbs, self, 18, 2)--38 self:Schedule(25, delayedTimeBomb, self, 15, 3)--40 timerBigAddCD:Start(43, 1) countdownBigAdd:Start(43) self:Schedule(38, delayedOrbs, self, 7, 3)--45 timerPowerOverwhelmingCD:Start(55, 1) elseif self:IsNormal() then--Updated Jan 17 timerTimeReleaseCD:Start(5, 1) timerTimeBombCD:Start(20, 1) self:Schedule(5, delayedTimeRelease, self, 23, 2)--28 timerTemporalOrbsCD:Start(30, 1) timerBigAddCD:Start(38, 1) countdownBigAdd:Start(38) timerPowerOverwhelmingCD:Start(90, 1) else--LFR end elseif self.vb.slowCount == 2 then if self:IsMythic() then--Updated Jan 25 timerTimeBombCD:Start(2, 1) timerTimeReleaseCD:Start(7, 1) timerBigAddCD:Start(9, 1) countdownBigAdd:Start(9) timerTemporalOrbsCD:Start(14, 1) timerPowerOverwhelmingCD:Start(19, 1) elseif self:IsHeroic() then--Updated May 26, 2017 timerTimeReleaseCD:Start(5, 1) timerTemporalOrbsCD:Start(15, 1) timerTimeBombCD:Start(20, 1) self:Schedule(20, delayedTimeBomb, self, 5, 2)--25 self:Schedule(25, delayedTimeBomb, self, 5, 2)--30 timerPowerOverwhelmingCD:Start(35, 1) elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end elseif self.vb.slowCount == 3 then if self:IsMythic() then timerTemporalOrbsCD:Start(5, 1) timerTimeBombCD:Start(7, 1) timerPowerOverwhelmingCD:Start(9, 1) elseif self:IsHeroic() then--Probably changed. DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end elseif self.vb.slowCount == 4 then if self:IsMythic() then--Updated Jan 25 timerTimeReleaseCD:Start(5, 1) timerTemporalOrbsCD:Start(15, 1) timerTimeBombCD:Start(20, 1) self:Schedule(15, delayedOrbs, self, 10, 2)--25 timerPowerOverwhelmingCD:Start(30, 1) elseif self:IsHeroic() then--Probably changed. DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end else--Slow 5 if self:IsMythic() then--Updated Jan 25 timerTimeReleaseCD:Start(2, 1) timerTimeBombCD:Start(3, 1) timerPowerOverwhelmingCD:Start(8, 1) elseif self:IsHeroic() then--Probably changed. DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end end updateTimeBomb(self) self:Schedule(2, updateTimeBomb, self) self:Schedule(5, updateTimeBomb, self) elseif spellId == 207013 then--Speed: Fast self.vb.currentPhase = 3 self.vb.interruptCount = 0 self.vb.fastCount = self.vb.fastCount + 1 warnFast:Show(self.vb.fastCount) if self.vb.fastCount == 1 then if self:IsMythic() then--Updated Jan 25 timerTimeReleaseCD:Start(5, 1) timerBigAddCD:Start(7, 1) countdownBigAdd:Start(7) timerTemporalOrbsCD:Start(12, 1) timerPowerOverwhelmingCD:Start(22, 1) elseif self:IsHeroic() then--Updated May 26, 2017 timerTimeReleaseCD:Start(5, 1) self:Schedule(5, delayedTimeRelease, self, 7, 2)--12 timerTimeBombCD:Start(17, 1) self:Schedule(12, delayedTimeRelease, self, 13, 3)--25 self:Schedule(25, delayedTimeRelease, self, 5, 4)--30 self:Schedule(30, delayedTimeRelease, self, 5, 5)--35 timerBigAddCD:Start(38, 1) countdownBigAdd:Start(38) self:Schedule(35, delayedTimeRelease, self, 8, 6)--43 timerPowerOverwhelmingCD:Start(50, 1) elseif self:IsNormal() then--Normal confirmed timerTimeReleaseCD:Start(10, 1) timerTemporalOrbsCD:Start(15, 1) DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end elseif self.vb.fastCount == 2 then if self:IsMythic() then--Updated Feb 15 timerTimeReleaseCD:Start(5, 1) self:Schedule(5, delayedTimeRelease, self, 5, 2)--10 self:Schedule(10, delayedTimeRelease, self, 5, 3)--15 self:Schedule(15, delayedTimeRelease, self, 5, 4)--20 timerBigAddCD:Start(23, 1) countdownBigAdd:Start(23) timerTemporalOrbsCD:Start(25, 1) timerPowerOverwhelmingCD:Start(30, 1) elseif self:IsHeroic() then--Updated Dec 2 timerTemporalOrbsCD:Start(10, 1) self:Schedule(10, delayedOrbs, self, 15, 2)--25 timerTimeBombCD:Start(30, 1) timerTimeReleaseCD:Start(40, 1) timerPowerOverwhelmingCD:Start(45, 1) elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end elseif self.vb.fastCount == 3 then if self:IsMythic() then--Updated Feb 15 timerTimeReleaseCD:Start(5, 1) self:Schedule(5, delayedTimeRelease, self, 5, 2)--10 self:Schedule(10, delayedTimeRelease, self, 5, 3)--15 self:Schedule(15, delayedTimeRelease, self, 5, 4)--20 timerTemporalOrbsCD:Start(23, 1) timerBigAddCD:Start(25, 1) countdownBigAdd:Start(25) timerPowerOverwhelmingCD:Start(30, 1) elseif self:IsHeroic() then--Updated Dec 2 --Goes into Full Power here? --DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else--LFR end elseif self.vb.fastCount == 4 then if self:IsMythic() then--Updated Jan 25 timerTimeReleaseCD:Start(5, 1) timerNextPhase:Start(8) elseif self:IsHeroic() then--Probably changed. DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") elseif self:IsNormal() then--Normal confirmed DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") else DBM:AddMsg("There is no timer data going this far into the fight. Please submit transcriptor log to improve this mod") end else--LFR end updateTimeBomb(self) self:Schedule(2, updateTimeBomb, self) self:Schedule(5, updateTimeBomb, self) elseif spellId == 206700 then--Summon Slow Add (Big Adds) specWarnBigAdd:Show() specWarnBigAdd:Play("bigmobsoon") elseif spellId == 207972 then--Full Power, he's just gonna run in circles aoeing the raid and stop using abilities timerBigAddCD:Stop() countdownBigAdd:Cancel() timerTemporalOrbsCD:Stop() timerPowerOverwhelmingCD:Stop() timerTimeReleaseCD:Stop() timerTimeBombCD:Stop() timerBurstofTimeCD:Stop() timerNextPhase:Stop() self:Unschedule(delayedTimeRelease) self:Unschedule(delayedTimeBomb) self:Unschedule(delayedBurst) self:Unschedule(delayedOrbs) end end function mod:UNIT_SPELLCAST_CHANNEL_STOP(uId, _, _, spellGUID) local spellId = tonumber(select(5, strsplit("-", spellGUID)), 10) if spellId == 211927 then--Power Overwhelming self.vb.interruptCount = self.vb.interruptCount + 1 if self.vb.currentPhase == 1 then--slow if self.vb.normCount == 2 then if self:IsMythic() then--Updated Jan 25 timerTimeReleaseCD:Start(5, 1) timerNextPhase:Start(8) elseif self:IsNormal() then --timerBurstofTimeCD:Start(5, 2) --self:Schedule(5, delayedBurst, self, 5, 3)--10 --timerTimeReleaseCD:Start(18, 2) --timerTimeBombCD:Start(25, 1) --timerNextPhase:Start(30) end end elseif self.vb.currentPhase == 2 then--normal if self.vb.normCount == 2 then if self:IsMythic() then--Updated Jan 25 timerTimeBombCD:Start(3, 2) timerTemporalOrbsCD:Start(6, 2) timerNextPhase:Start(9) elseif self:IsHeroic() then--Updated May 26 2017 timerTimeReleaseCD:Start(5, 1) timerNextPhase:Start(10) elseif self:IsNormal() then --timerTimeReleaseCD:Start(5, 3) --timerNextPhase:Start(10) else--LFR --timerTimeReleaseCD:Start(10, 3) --timerNextPhase:Start(15) end end end end end mod.UNIT_SPELLCAST_STOP = mod.UNIT_SPELLCAST_CHANNEL_STOP
mit
bjornbytes/RxLua
tests/elementAt.lua
2
1696
describe('elementAt', function() it('errors when its parent errors', function() expect(Rx.Observable:throw():elementAt(0)).to.produce.error() end) it('chains subscriptions', function() local subscription = Rx.Subscription.create() local observable = Rx.Observable.create(function() return subscription end) expect(observable:subscribe()).to.equal(subscription) expect(observable:elementAt(1):subscribe()).to.equal(subscription) end) it('unsubscribes the subscription if the element is produced', function() local subject = Rx.Subject.create() local subscription = subject:elementAt(2):subscribe() subscription.unsubscribe = spy() subject:onNext('a') expect(#subscription.unsubscribe).to.equal(0) subject:onNext('b') expect(#subscription.unsubscribe).to.equal(1) end) it('errors if no index is specified', function() expect(function () Rx.Observable.of(1):elementAt() end).to.fail() end) it('produces no values if the specified index is less than one', function() expect(Rx.Observable.of(1):elementAt(0)).to.produce.nothing() expect(Rx.Observable.of(1):elementAt(-1)).to.produce.nothing() end) it('produces no values if the specified index is greater than the number of elements produced by the source', function() expect(Rx.Observable.of(1):elementAt(2)).to.produce.nothing() end) it('produces all values produced by the source at the specified index', function() local observable = Rx.Observable.create(function(observer) observer:onNext(1, 2, 3) observer:onNext(4, 5, 6) observer:onCompleted() end) expect(observable:elementAt(2)).to.produce({{4, 5, 6}}) end) end)
mit
liruqi/bigfoot
Interface/AddOns/BigFoot/AceLibs/Ace3/AceAddon-3.0/AceAddon-3.0.lua
17
26462
--- **AceAddon-3.0** provides a template for creating addon objects. -- It'll provide you with a set of callback functions that allow you to simplify the loading -- process of your addon.\\ -- Callbacks provided are:\\ -- * **OnInitialize**, which is called directly after the addon is fully loaded. -- * **OnEnable** which gets called during the PLAYER_LOGIN event, when most of the data provided by the game is already present. -- * **OnDisable**, which is only called when your addon is manually being disabled. -- @usage -- -- A small (but complete) addon, that doesn't do anything, -- -- but shows usage of the callbacks. -- local MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- function MyAddon:OnInitialize() -- -- do init tasks here, like loading the Saved Variables, -- -- or setting up slash commands. -- end -- -- function MyAddon:OnEnable() -- -- Do more initialization here, that really enables the use of your addon. -- -- Register Events, Hook functions, Create Frames, Get information from -- -- the game that wasn't available in OnInitialize -- end -- -- function MyAddon:OnDisable() -- -- Unhook, Unregister Events, Hide frames that you created. -- -- You would probably only use an OnDisable if you want to -- -- build a "standby" mode, or be able to toggle modules on/off. -- end -- @class file -- @name AceAddon-3.0.lua -- @release $Id: AceAddon-3.0.lua 1084 2013-04-27 20:14:11Z nevcairiel $ local MAJOR, MINOR = "AceAddon-3.0", 12 local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceAddon then return end -- No Upgrade needed. AceAddon.frame = AceAddon.frame or CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame AceAddon.addons = AceAddon.addons or {} -- addons in general AceAddon.statuses = AceAddon.statuses or {} -- statuses of addon. AceAddon.initializequeue = AceAddon.initializequeue or {} -- addons that are new and not initialized AceAddon.enablequeue = AceAddon.enablequeue or {} -- addons that are initialized and waiting to be enabled AceAddon.embeds = AceAddon.embeds or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon -- Lua APIs local tinsert, tconcat, tremove = table.insert, table.concat, table.remove local fmt, tostring = string.format, tostring local select, pairs, next, type, unpack = select, pairs, next, type, unpack local loadstring, assert, error = loadstring, assert, error local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: LibStub, IsLoggedIn, geterrorhandler --[[ xpcall safecall implementation ]] local xpcall = xpcall local function errorhandler(err) return geterrorhandler()(err) end local function CreateDispatcher(argCount) local code = [[ local xpcall, eh = ... local method, ARGS local function call() return method(ARGS) end local function dispatch(func, ...) method = func if not method then return end ARGS = ... return xpcall(call, eh) end return dispatch ]] local ARGS = {} for i = 1, argCount do ARGS[i] = "arg"..i end code = code:gsub("ARGS", tconcat(ARGS, ", ")) return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler) end local Dispatchers = setmetatable({}, {__index=function(self, argCount) local dispatcher = CreateDispatcher(argCount) rawset(self, argCount, dispatcher) return dispatcher end}) Dispatchers[0] = function(func) return xpcall(func, errorhandler) end local function safecall(func, ...) -- we check to see if the func is passed is actually a function here and don't error when it isn't -- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not -- present execution should continue without hinderance if type(func) == "function" then return Dispatchers[select('#', ...)](func, ...) end end -- local functions that will be implemented further down local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule, GetName, SetDefaultModuleState, SetDefaultModuleLibraries, SetEnabledState, SetDefaultModulePrototype -- used in the addon metatable local function addontostring( self ) return self.name end -- Check if the addon is queued for initialization local function queuedForInitialization(addon) for i = 1, #AceAddon.initializequeue do if AceAddon.initializequeue[i] == addon then return true end end return false end --- Create a new AceAddon-3.0 addon. -- Any libraries you specified will be embeded, and the addon will be scheduled for -- its OnInitialize and OnEnable callbacks. -- The final addon object, with all libraries embeded, will be returned. -- @paramsig [object ,]name[, lib, ...] -- @param object Table to use as a base for the addon (optional) -- @param name Name of the addon object to create -- @param lib List of libraries to embed into the addon -- @usage -- -- Create a simple addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0") -- -- -- Create a Addon object based on the table of a frame -- local MyFrame = CreateFrame("Frame") -- MyAddon = LibStub("AceAddon-3.0"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0") function AceAddon:NewAddon(objectorname, ...) local object,name local i=1 if type(objectorname)=="table" then object=objectorname name=... i=2 else name=objectorname end if type(name)~="string" then error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end if self.addons[name] then error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists."):format(name), 2) end object = object or {} object.name = name local addonmeta = {} local oldmeta = getmetatable(object) if oldmeta then for k, v in pairs(oldmeta) do addonmeta[k] = v end end addonmeta.__tostring = addontostring setmetatable( object, addonmeta ) self.addons[name] = object object.modules = {} object.orderedModules = {} object.defaultModuleLibraries = {} Embed( object ) -- embed NewModule, GetModule methods self:EmbedLibraries(object, select(i,...)) -- add to queue of addons to be initialized upon ADDON_LOADED tinsert(self.initializequeue, object) return object end --- Get the addon object by its name from the internal AceAddon registry. -- Throws an error if the addon object cannot be found (except if silent is set). -- @param name unique name of the addon object -- @param silent if true, the addon is optional, silently return nil if its not found -- @usage -- -- Get the Addon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") function AceAddon:GetAddon(name, silent) if not silent and not self.addons[name] then error(("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'."):format(tostring(name)), 2) end return self.addons[name] end -- - Embed a list of libraries into the specified addon. -- This function will try to embed all of the listed libraries into the addon -- and error if a single one fails. -- -- **Note:** This function is for internal use by :NewAddon/:NewModule -- @paramsig addon, [lib, ...] -- @param addon addon object to embed the libs in -- @param lib List of libraries to embed into the addon function AceAddon:EmbedLibraries(addon, ...) for i=1,select("#", ... ) do local libname = select(i, ...) self:EmbedLibrary(addon, libname, false, 4) end end -- - Embed a library into the addon object. -- This function will check if the specified library is registered with LibStub -- and if it has a :Embed function to call. It'll error if any of those conditions -- fails. -- -- **Note:** This function is for internal use by :EmbedLibraries -- @paramsig addon, libname[, silent[, offset]] -- @param addon addon object to embed the library in -- @param libname name of the library to embed -- @param silent marks an embed to fail silently if the library doesn't exist (optional) -- @param offset will push the error messages back to said offset, defaults to 2 (optional) function AceAddon:EmbedLibrary(addon, libname, silent, offset) local lib = LibStub:GetLibrary(libname, true) if not lib and not silent then error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q."):format(tostring(libname)), offset or 2) elseif lib and type(lib.Embed) == "function" then lib:Embed(addon) tinsert(self.embeds[addon], libname) return true elseif lib then error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable"):format(libname), offset or 2) end end --- Return the specified module from an addon object. -- Throws an error if the addon object cannot be found (except if silent is set) -- @name //addon//:GetModule -- @paramsig name[, silent] -- @param name unique name of the module -- @param silent if true, the module is optional, silently return nil if its not found (optional) -- @usage -- -- Get the Addon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- -- Get the Module -- MyModule = MyAddon:GetModule("MyModule") function GetModule(self, name, silent) if not self.modules[name] and not silent then error(("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'."):format(tostring(name)), 2) end return self.modules[name] end local function IsModuleTrue(self) return true end --- Create a new module for the addon. -- The new module can have its own embeded libraries and/or use a module prototype to be mixed into the module.\\ -- A module has the same functionality as a real addon, it can have modules of its own, and has the same API as -- an addon object. -- @name //addon//:NewModule -- @paramsig name[, prototype|lib[, lib, ...]] -- @param name unique name of the module -- @param prototype object to derive this module from, methods and values from this table will be mixed into the module (optional) -- @param lib List of libraries to embed into the addon -- @usage -- -- Create a module with some embeded libraries -- MyModule = MyAddon:NewModule("MyModule", "AceEvent-3.0", "AceHook-3.0") -- -- -- Create a module with a prototype -- local prototype = { OnEnable = function(self) print("OnEnable called!") end } -- MyModule = MyAddon:NewModule("MyModule", prototype, "AceEvent-3.0", "AceHook-3.0") function NewModule(self, name, prototype, ...) if type(name) ~= "string" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'."):format(type(prototype)), 2) end if self.modules[name] then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists."):format(name), 2) end -- modules are basically addons. We treat them as such. They will be added to the initializequeue properly as well. -- NewModule can only be called after the parent addon is present thus the modules will be initialized after their parent is. local module = AceAddon:NewAddon(fmt("%s_%s", self.name or tostring(self), name)) module.IsModule = IsModuleTrue module:SetEnabledState(self.defaultModuleState) module.moduleName = name if type(prototype) == "string" then AceAddon:EmbedLibraries(module, prototype, ...) else AceAddon:EmbedLibraries(module, ...) end AceAddon:EmbedLibraries(module, unpack(self.defaultModuleLibraries)) if not prototype or type(prototype) == "string" then prototype = self.defaultModulePrototype or nil end if type(prototype) == "table" then local mt = getmetatable(module) mt.__index = prototype setmetatable(module, mt) -- More of a Base class type feel. end safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy. self.modules[name] = module tinsert(self.orderedModules, module) return module end --- Returns the real name of the addon or module, without any prefix. -- @name //addon//:GetName -- @paramsig -- @usage -- print(MyAddon:GetName()) -- -- prints "MyAddon" function GetName(self) return self.moduleName or self.name end --- Enables the Addon, if possible, return true or false depending on success. -- This internally calls AceAddon:EnableAddon(), thus dispatching a OnEnable callback -- and enabling all modules of the addon (unless explicitly disabled).\\ -- :Enable() also sets the internal `enableState` variable to true -- @name //addon//:Enable -- @paramsig -- @usage -- -- Enable MyModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Enable() function Enable(self) self:SetEnabledState(true) -- nevcairiel 2013-04-27: don't enable an addon/module if its queued for init still -- it'll be enabled after the init process if not queuedForInitialization(self) then return AceAddon:EnableAddon(self) end end --- Disables the Addon, if possible, return true or false depending on success. -- This internally calls AceAddon:DisableAddon(), thus dispatching a OnDisable callback -- and disabling all modules of the addon.\\ -- :Disable() also sets the internal `enableState` variable to false -- @name //addon//:Disable -- @paramsig -- @usage -- -- Disable MyAddon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:Disable() function Disable(self) self:SetEnabledState(false) return AceAddon:DisableAddon(self) end --- Enables the Module, if possible, return true or false depending on success. -- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object. -- @name //addon//:EnableModule -- @paramsig name -- @usage -- -- Enable MyModule using :GetModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Enable() -- -- -- Enable MyModule using the short-hand -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:EnableModule("MyModule") function EnableModule(self, name) local module = self:GetModule( name ) return module:Enable() end --- Disables the Module, if possible, return true or false depending on success. -- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object. -- @name //addon//:DisableModule -- @paramsig name -- @usage -- -- Disable MyModule using :GetModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Disable() -- -- -- Disable MyModule using the short-hand -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:DisableModule("MyModule") function DisableModule(self, name) local module = self:GetModule( name ) return module:Disable() end --- Set the default libraries to be mixed into all modules created by this object. -- Note that you can only change the default module libraries before any module is created. -- @name //addon//:SetDefaultModuleLibraries -- @paramsig lib[, lib, ...] -- @param lib List of libraries to embed into the addon -- @usage -- -- Create the addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- Configure default libraries for modules (all modules need AceEvent-3.0) -- MyAddon:SetDefaultModuleLibraries("AceEvent-3.0") -- -- Create a module -- MyModule = MyAddon:NewModule("MyModule") function SetDefaultModuleLibraries(self, ...) if next(self.modules) then error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2) end self.defaultModuleLibraries = {...} end --- Set the default state in which new modules are being created. -- Note that you can only change the default state before any module is created. -- @name //addon//:SetDefaultModuleState -- @paramsig state -- @param state Default state for new modules, true for enabled, false for disabled -- @usage -- -- Create the addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- Set the default state to "disabled" -- MyAddon:SetDefaultModuleState(false) -- -- Create a module and explicilty enable it -- MyModule = MyAddon:NewModule("MyModule") -- MyModule:Enable() function SetDefaultModuleState(self, state) if next(self.modules) then error("Usage: SetDefaultModuleState(state): cannot change the module defaults after a module has been registered.", 2) end self.defaultModuleState = state end --- Set the default prototype to use for new modules on creation. -- Note that you can only change the default prototype before any module is created. -- @name //addon//:SetDefaultModulePrototype -- @paramsig prototype -- @param prototype Default prototype for the new modules (table) -- @usage -- -- Define a prototype -- local prototype = { OnEnable = function(self) print("OnEnable called!") end } -- -- Set the default prototype -- MyAddon:SetDefaultModulePrototype(prototype) -- -- Create a module and explicitly Enable it -- MyModule = MyAddon:NewModule("MyModule") -- MyModule:Enable() -- -- should print "OnEnable called!" now -- @see NewModule function SetDefaultModulePrototype(self, prototype) if next(self.modules) then error("Usage: SetDefaultModulePrototype(prototype): cannot change the module defaults after a module has been registered.", 2) end if type(prototype) ~= "table" then error(("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'."):format(type(prototype)), 2) end self.defaultModulePrototype = prototype end --- Set the state of an addon or module -- This should only be called before any enabling actually happend, e.g. in/before OnInitialize. -- @name //addon//:SetEnabledState -- @paramsig state -- @param state the state of an addon or module (enabled=true, disabled=false) function SetEnabledState(self, state) self.enabledState = state end --- Return an iterator of all modules associated to the addon. -- @name //addon//:IterateModules -- @paramsig -- @usage -- -- Enable all modules -- for name, module in MyAddon:IterateModules() do -- module:Enable() -- end local function IterateModules(self) return pairs(self.modules) end -- Returns an iterator of all embeds in the addon -- @name //addon//:IterateEmbeds -- @paramsig local function IterateEmbeds(self) return pairs(AceAddon.embeds[self]) end --- Query the enabledState of an addon. -- @name //addon//:IsEnabled -- @paramsig -- @usage -- if MyAddon:IsEnabled() then -- MyAddon:Disable() -- end local function IsEnabled(self) return self.enabledState end local mixins = { NewModule = NewModule, GetModule = GetModule, Enable = Enable, Disable = Disable, EnableModule = EnableModule, DisableModule = DisableModule, IsEnabled = IsEnabled, SetDefaultModuleLibraries = SetDefaultModuleLibraries, SetDefaultModuleState = SetDefaultModuleState, SetDefaultModulePrototype = SetDefaultModulePrototype, SetEnabledState = SetEnabledState, IterateModules = IterateModules, IterateEmbeds = IterateEmbeds, GetName = GetName, } local function IsModule(self) return false end local pmixins = { defaultModuleState = true, enabledState = true, IsModule = IsModule, } -- Embed( target ) -- target (object) - target object to embed aceaddon in -- -- this is a local function specifically since it's meant to be only called internally function Embed(target, skipPMixins) for k, v in pairs(mixins) do target[k] = v end if not skipPMixins then for k, v in pairs(pmixins) do target[k] = target[k] or v end end end -- - Initialize the addon after creation. -- This function is only used internally during the ADDON_LOADED event -- It will call the **OnInitialize** function on the addon object (if present), -- and the **OnEmbedInitialize** function on all embeded libraries. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- @param addon addon object to intialize function AceAddon:InitializeAddon(addon) safecall(addon.OnInitialize, addon) local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedInitialize, lib, addon) end end -- we don't call InitializeAddon on modules specifically, this is handled -- from the event handler and only done _once_ end -- - Enable the addon after creation. -- Note: This function is only used internally during the PLAYER_LOGIN event, or during ADDON_LOADED, -- if IsLoggedIn() already returns true at that point, e.g. for LoD Addons. -- It will call the **OnEnable** function on the addon object (if present), -- and the **OnEmbedEnable** function on all embeded libraries.\\ -- This function does not toggle the enable state of the addon itself, and will return early if the addon is disabled. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- Use :Enable on the addon itself instead. -- @param addon addon object to enable function AceAddon:EnableAddon(addon) if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end if self.statuses[addon.name] or not addon.enabledState then return false end -- set the statuses first, before calling the OnEnable. this allows for Disabling of the addon in OnEnable. self.statuses[addon.name] = true safecall(addon.OnEnable, addon) -- make sure we're still enabled before continueing if self.statuses[addon.name] then local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedEnable, lib, addon) end end -- enable possible modules. local modules = addon.orderedModules for i = 1, #modules do self:EnableAddon(modules[i]) end end return self.statuses[addon.name] -- return true if we're disabled end -- - Disable the addon -- Note: This function is only used internally. -- It will call the **OnDisable** function on the addon object (if present), -- and the **OnEmbedDisable** function on all embeded libraries.\\ -- This function does not toggle the enable state of the addon itself, and will return early if the addon is still enabled. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- Use :Disable on the addon itself instead. -- @param addon addon object to enable function AceAddon:DisableAddon(addon) if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end if not self.statuses[addon.name] then return false end -- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable. self.statuses[addon.name] = false safecall( addon.OnDisable, addon ) -- make sure we're still disabling... if not self.statuses[addon.name] then local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedDisable, lib, addon) end end -- disable possible modules. local modules = addon.orderedModules for i = 1, #modules do self:DisableAddon(modules[i]) end end return not self.statuses[addon.name] -- return true if we're disabled end --- Get an iterator over all registered addons. -- @usage -- -- Print a list of all installed AceAddon's -- for name, addon in AceAddon:IterateAddons() do -- print("Addon: " .. name) -- end function AceAddon:IterateAddons() return pairs(self.addons) end --- Get an iterator over the internal status registry. -- @usage -- -- Print a list of all enabled addons -- for name, status in AceAddon:IterateAddonStatus() do -- if status then -- print("EnabledAddon: " .. name) -- end -- end function AceAddon:IterateAddonStatus() return pairs(self.statuses) end -- Following Iterators are deprecated, and their addon specific versions should be used -- e.g. addon:IterateEmbeds() instead of :IterateEmbedsOnAddon(addon) function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end -- Event Handling local function onEvent(this, event, arg1) -- 2011-08-17 nevcairiel - ignore the load event of Blizzard_DebugTools, so a potential startup error isn't swallowed up if (event == "ADDON_LOADED" and arg1 ~= "Blizzard_DebugTools") or event == "PLAYER_LOGIN" then -- if a addon loads another addon, recursion could happen here, so we need to validate the table on every iteration while(#AceAddon.initializequeue > 0) do local addon = tremove(AceAddon.initializequeue, 1) -- this might be an issue with recursion - TODO: validate if event == "ADDON_LOADED" then addon.baseName = arg1 end AceAddon:InitializeAddon(addon) tinsert(AceAddon.enablequeue, addon) end if IsLoggedIn() then while(#AceAddon.enablequeue > 0) do local addon = tremove(AceAddon.enablequeue, 1) AceAddon:EnableAddon(addon) end end end end AceAddon.frame:RegisterEvent("ADDON_LOADED") AceAddon.frame:RegisterEvent("PLAYER_LOGIN") AceAddon.frame:SetScript("OnEvent", onEvent) -- upgrade embeded for name, addon in pairs(AceAddon.addons) do Embed(addon, true) end -- 2010-10-27 nevcairiel - add new "orderedModules" table if oldminor and oldminor < 10 then for name, addon in pairs(AceAddon.addons) do addon.orderedModules = {} for module_name, module in pairs(addon.modules) do tinsert(addon.orderedModules, module) end end end
mit
liruqi/bigfoot
Interface/AddOns/DBM-WorldEvents/Holidays/HeadlessHorseman.lua
1
3216
local mod = DBM:NewMod("d285", "DBM-WorldEvents", 1) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 17257 $"):sub(12, -3)) mod:SetCreatureID(23682, 23775) --mod:SetModelID(22351)--Model doesn't work/render for some reason. mod:SetZone() mod:SetReCombatTime(10) mod:RegisterCombat("combat") --mod:RegisterEvents( -- "CHAT_MSG_SAY" --) mod:RegisterEventsInCombat( "SPELL_AURA_APPLIED 42380 42514", "UNIT_SPELLCAST_SUCCEEDED target focus", "CHAT_MSG_MONSTER_SAY", "UNIT_DIED" ) local warnConflag = mod:NewTargetAnnounce(42380, 3) local warnSquashSoul = mod:NewTargetAnnounce(42514, 2, nil, false, 2) local warnPhase = mod:NewAnnounce("WarnPhase", 2, "Interface\\Icons\\Spell_Nature_WispSplode") local warnHorsemanSoldiers = mod:NewAnnounce("warnHorsemanSoldiers", 2, 97133) local warnHorsemanHead = mod:NewAnnounce("warnHorsemanHead", 3) --local timerCombatStart = mod:NewCombatTimer(17)--rollplay for first pull local timerConflag = mod:NewTargetTimer(4, 42380, nil, "Healer", nil, 3) local timerSquashSoul = mod:NewTargetTimer(15, 42514, nil, false, 2, 3) function mod:SPELL_AURA_APPLIED(args) local spellId = args.spellId if spellId == 42380 then -- Conflagration warnConflag:Show(args.destName) timerConflag:Start(args.destName) elseif spellId == 42514 then -- Squash Soul warnSquashSoul:Show(args.destName) timerSquashSoul:Start(args.destName) end end function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId) -- "<48.6> Headless Horseman:Possible Target<Omegal>:target:Headless Horseman Climax - Command, Head Repositions::0:42410", -- [35] if spellId == 42410 then self:SendSync("HeadRepositions") -- "<23.0> Headless Horseman:Possible Target<nil>:target:Headless Horseman Climax, Body Stage 1::0:42547", -- [1] elseif spellId == 42547 then self:SendSync("BodyStage1") -- "<49.0> Headless Horseman:Possible Target<Omegal>:target:Headless Horseman Climax, Body Stage 2::0:42548", -- [7] elseif spellId == 42548 then self:SendSync("BodyStage2") -- "<70.6> Headless Horseman:Possible Target<Omegal>:target:Headless Horseman Climax, Body Stage 3::0:42549", -- [13] elseif spellId == 42549 then self:SendSync("BodyStage3") end end --Use syncing since these unit events require "target" or "focus" to detect. --At least someone in group should be targeting this stuff and sync it to those that aren't (like a healer) function mod:OnSync(event, arg) if event == "HeadRepositions" then warnHorsemanHead:Show() elseif event == "BodyStage1" then warnPhase:Show(1) elseif event == "BodyStage2" then warnPhase:Show(2) elseif event == "BodyStage3" then warnPhase:Show(3) end end function mod:CHAT_MSG_MONSTER_SAY(msg) if msg == L.HorsemanSoldiers and self:AntiSpam(5, 1) then -- Warning for adds spawning. No CLEU or UNIT event for it. warnHorsemanSoldiers:Show() end end --[[ function mod:CHAT_MSG_SAY(msg) if msg == L.HorsemanSummon and self:AntiSpam(5) then -- Summoned timerCombatStart:Start() end end--]] function mod:UNIT_DIED(args) if self:GetCIDFromGUID(args.destGUID) == 23775 then DBM:EndCombat(self) end end
mit
shiprabehera/kong
spec/03-plugins/25-response-rate-limiting/03-api_spec.lua
4
1589
local helpers = require "spec.helpers" local cjson = require "cjson" describe("Plugin: response-rate-limiting (API)", function() local admin_client teardown(function() if admin_client then admin_client:close() end helpers.stop_kong() end) describe("POST", function() setup(function() assert(helpers.dao.apis:insert { name = "test", hosts = { "test1.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.start_kong()) admin_client = helpers.admin_client() end) it("errors on empty config", function() local res = assert(admin_client:send { method = "POST", path = "/apis/test/plugins/", body = { name = "response-ratelimiting" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(400, res) local json = cjson.decode(body) assert.same({ config = "You need to set at least one limit name" }, json) end) it("accepts proper config", function() local res = assert(admin_client:send { method = "POST", path = "/apis/test/plugins/", body = { name = "response-ratelimiting", config = { limits = { video = {second = 10} } } }, headers = { ["Content-Type"] = "application/json" } }) local body = cjson.decode(assert.res_status(201, res)) assert.equal(10, body.config.limits.video.second) end) end) end)
apache-2.0
dromozoa/dromozoa-commons
dromozoa/commons/base64.lua
3
4685
-- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-commons. -- -- dromozoa-commons is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>. local sequence_writer = require "dromozoa.commons.sequence_writer" local translate_range = require "dromozoa.commons.translate_range" local encoder = { [62] = "+"; [63] = "/"; [64] = "="; [65] = "=="; } local decoder = { [("+"):byte()] = 62; [("/"):byte()] = 63; } local n = ("A"):byte() for i = 0, 25 do local byte = i + n local char = string.char(byte) encoder[i] = char decoder[byte] = i end local n = ("a"):byte() - 26 for i = 26, 51 do local byte = i + n local char = string.char(byte) encoder[i] = char decoder[byte] = i end local n = ("0"):byte() - 52 for i = 52, 61 do local byte = i + n local char = string.char(byte) encoder[i] = char decoder[byte] = i end local encoder_url = setmetatable({ [62] = "-"; [63] = "_"; [64] = ""; [65] = ""; }, { __index = encoder }) local function encode(encoder, out, s, min, max) for i = min + 2, max, 3 do local p = i - 2 local a, b, c = s:byte(p, i) local a = a * 65536 + b * 256 + c local d = a % 64 local a = (a - d) / 64 local c = a % 64 local a = (a - c) / 64 local b = a % 64 local a = (a - b) / 64 out:write(encoder[a], encoder[b], encoder[c], encoder[d]) end local i = max + 1 local p = i - (i - min) % 3 if p < i then local a, b = s:byte(p, max) if b then local a = a * 1024 + b * 4 local c = a % 64 local a = (a - c) / 64 local b = a % 64 local a = (a - b) / 64 out:write(encoder[a], encoder[b], encoder[c], encoder[64]) else local a = a * 16 local b = a % 64 local a = (a - b) / 64 out:write(encoder[a], encoder[b], encoder[65]) end end return out end local function decode(out, s, min, max) local n = max - min + 1 if n == 0 then return out elseif n % 4 ~= 0 then return nil, "length not divisible by 4" end for i = min + 3, max - 4, 4 do local p = i - 3 if s:find("^[0-9A-Za-z%+%/][0-9A-Za-z%+%/][0-9A-Za-z%+%/][0-9A-Za-z%+%/]", p) == nil then return nil, "decode error at position " .. p end local a, b, c, d = s:byte(p, i) local a = decoder[a] * 262144 + decoder[b] * 4096 + decoder[c] * 64 + decoder[d] local c = a % 256 local a = (a - c) / 256 local b = a % 256 local a = (a - b) / 256 out:write(string.char(a, b, c)) end local p = max - 3 if s:find("^[0-9A-Za-z%+%/][0-9A-Za-z%+%/][0-9A-Za-z%+%/%=][0-9A-Za-z%+%/%=]", p) == nil then return nil, "decode error at position " .. p end local a, b, c, d = s:byte(p, max) local a = decoder[a] local b = decoder[b] local c = decoder[c] local d = decoder[d] if d == nil then if c == nil then if b % 16 ~= 0 then return nil, "decode error at position " .. p + 1 end local a = a * 4 + b / 16 out:write(string.char(a)) else if c % 4 ~= 0 then return nil, "decode error at position " .. p + 2 end local a = a * 1024 + b * 16 + c / 4 local b = a % 256 local a = (a - b) / 256 out:write(string.char(a, b)) end elseif c == nil then return nil, "decode error at position " .. p + 3 else local a = a * 262144 + b * 4096 + c * 64 + d local c = a % 256 local a = (a - c) / 256 local b = a % 256 local a = (a - b) / 256 out:write(string.char(a, b, c)) end return out end local class = {} function class.encode(s, i, j) local s = tostring(s) return encode(encoder, sequence_writer(), s, translate_range(#s, i, j)):concat() end function class.encode_url(s, i, j) local s = tostring(s) return encode(encoder_url, sequence_writer(), s, translate_range(#s, i, j)):concat() end function class.decode(s, i, j) local s = tostring(s) local result, message = decode(sequence_writer(), s, translate_range(#s, i, j)) if result == nil then return nil, message else return result:concat() end end return class
gpl-3.0
ingran/balzac
custom_feeds/teltonika_luci/protocols/ppp/luasrc/model/cbi/admin_network/proto_ppp.lua
7
3622
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local device, username, password local ipv6, 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*S*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", Flag, "ipv6", translate("Enable IPv6 negotiation on the PPP link")) ipv6.default = ipv6.disabled end 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"
gpl-2.0
liruqi/bigfoot
Interface/AddOns/BigFoot/AceLibs/Ace3/AceGUI-3.0/widgets/AceGUIWidget-DropDown-Items.lua
1
11116
--[[ $Id: AceGUIWidget-DropDown-Items.lua 1167 2017-08-29 22:08:48Z funkydude $ ]]-- local AceGUI = LibStub("AceGUI-3.0") -- Lua APIs local select, assert = select, assert -- WoW APIs local PlaySound = PlaySound local CreateFrame = CreateFrame local function fixlevels(parent,...) local i = 1 local child = select(i, ...) while child do child:SetFrameLevel(parent:GetFrameLevel()+1) fixlevels(child, child:GetChildren()) i = i + 1 child = select(i, ...) end end local function fixstrata(strata, parent, ...) local i = 1 local child = select(i, ...) parent:SetFrameStrata(strata) while child do fixstrata(strata, child, child:GetChildren()) i = i + 1 child = select(i, ...) end end -- ItemBase is the base "class" for all dropdown items. -- Each item has to use ItemBase.Create(widgetType) to -- create an initial 'self' value. -- ItemBase will add common functions and ui event handlers. -- Be sure to keep basic usage when you override functions. local ItemBase = { -- NOTE: The ItemBase version is added to each item's version number -- to ensure proper updates on ItemBase changes. -- Use at least 1000er steps. version = 1000, counter = 0, } function ItemBase.Frame_OnEnter(this) local self = this.obj if self.useHighlight then self.highlight:Show() end self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end end function ItemBase.Frame_OnLeave(this) local self = this.obj self.highlight:Hide() self:Fire("OnLeave") if self.specialOnLeave then self.specialOnLeave(self) end end -- exported, AceGUI callback function ItemBase.OnAcquire(self) self.frame:SetToplevel(true) self.frame:SetFrameStrata("FULLSCREEN_DIALOG") end -- exported, AceGUI callback function ItemBase.OnRelease(self) self:SetDisabled(false) self.pullout = nil self.frame:SetParent(nil) self.frame:ClearAllPoints() self.frame:Hide() end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetPullout(self, pullout) self.pullout = pullout self.frame:SetParent(nil) self.frame:SetParent(pullout.itemFrame) self.parent = pullout.itemFrame fixlevels(pullout.itemFrame, pullout.itemFrame:GetChildren()) end -- exported function ItemBase.SetText(self, text) self.text:SetText(text or "") end -- exported function ItemBase.GetText(self) return self.text:GetText() end -- exported function ItemBase.SetPoint(self, ...) self.frame:SetPoint(...) end -- exported function ItemBase.Show(self) self.frame:Show() end -- exported function ItemBase.Hide(self) self.frame:Hide() end -- exported function ItemBase.SetDisabled(self, disabled) self.disabled = disabled if disabled then self.useHighlight = false self.text:SetTextColor(.5, .5, .5) else self.useHighlight = true self.text:SetTextColor(1, 1, 1) end end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetOnLeave(self, func) self.specialOnLeave = func end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetOnEnter(self, func) self.specialOnEnter = func end function ItemBase.Create(type) -- NOTE: Most of the following code is copied from AceGUI-3.0/Dropdown widget local count = AceGUI:GetNextWidgetNum(type) local frame = CreateFrame("Button", "AceGUI30DropDownItem"..count) local self = {} self.frame = frame frame.obj = self self.type = type self.useHighlight = true frame:SetHeight(17) frame:SetFrameStrata("FULLSCREEN_DIALOG") local text = frame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall") text:SetTextColor(1,1,1) text:SetJustifyH("LEFT") text:SetPoint("TOPLEFT",frame,"TOPLEFT",18,0) text:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-8,0) self.text = text local highlight = frame:CreateTexture(nil, "OVERLAY") highlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight") highlight:SetBlendMode("ADD") highlight:SetHeight(14) highlight:ClearAllPoints() highlight:SetPoint("RIGHT",frame,"RIGHT",-3,0) highlight:SetPoint("LEFT",frame,"LEFT",5,0) highlight:Hide() self.highlight = highlight local check = frame:CreateTexture("OVERLAY") check:SetWidth(16) check:SetHeight(16) check:SetPoint("LEFT",frame,"LEFT",3,-1) check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check") check:Hide() self.check = check local sub = frame:CreateTexture("OVERLAY") sub:SetWidth(16) sub:SetHeight(16) sub:SetPoint("RIGHT",frame,"RIGHT",-3,-1) sub:SetTexture("Interface\\ChatFrame\\ChatFrameExpandArrow") sub:Hide() self.sub = sub frame:SetScript("OnEnter", ItemBase.Frame_OnEnter) frame:SetScript("OnLeave", ItemBase.Frame_OnLeave) self.OnAcquire = ItemBase.OnAcquire self.OnRelease = ItemBase.OnRelease self.SetPullout = ItemBase.SetPullout self.GetText = ItemBase.GetText self.SetText = ItemBase.SetText self.SetDisabled = ItemBase.SetDisabled self.SetPoint = ItemBase.SetPoint self.Show = ItemBase.Show self.Hide = ItemBase.Hide self.SetOnLeave = ItemBase.SetOnLeave self.SetOnEnter = ItemBase.SetOnEnter return self end -- Register a dummy LibStub library to retrieve the ItemBase, so other addons can use it. local IBLib = LibStub:NewLibrary("AceGUI-3.0-DropDown-ItemBase", ItemBase.version) if IBLib then IBLib.GetItemBase = function() return ItemBase end end --[[ Template for items: -- Item: -- do local widgetType = "Dropdown-Item-" local widgetVersion = 1 local function Constructor() local self = ItemBase.Create(widgetType) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end --]] -- Item: Header -- A single text entry. -- Special: Different text color and no highlight do local widgetType = "Dropdown-Item-Header" local widgetVersion = 1 local function OnEnter(this) local self = this.obj self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end end local function OnLeave(this) local self = this.obj self:Fire("OnLeave") if self.specialOnLeave then self.specialOnLeave(self) end end -- exported, override local function SetDisabled(self, disabled) ItemBase.SetDisabled(self, disabled) if not disabled then self.text:SetTextColor(1, 1, 0) end end local function Constructor() local self = ItemBase.Create(widgetType) self.SetDisabled = SetDisabled self.frame:SetScript("OnEnter", OnEnter) self.frame:SetScript("OnLeave", OnLeave) self.text:SetTextColor(1, 1, 0) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Execute -- A simple button do local widgetType = "Dropdown-Item-Execute" local widgetVersion = 1 local function Frame_OnClick(this, button) local self = this.obj if self.disabled then return end self:Fire("OnClick") if self.pullout then self.pullout:Close() end end local function Constructor() local self = ItemBase.Create(widgetType) self.frame:SetScript("OnClick", Frame_OnClick) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Toggle -- Some sort of checkbox for dropdown menus. -- Does not close the pullout on click. do local widgetType = "Dropdown-Item-Toggle" local widgetVersion = 4 local function UpdateToggle(self) if self.value then self.check:Show() else self.check:Hide() end end local function OnRelease(self) ItemBase.OnRelease(self) self:SetValue(nil) end local function Frame_OnClick(this, button) local self = this.obj if self.disabled then return end self.value = not self.value if self.value then PlaySound(856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON else PlaySound(857) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_OFF end UpdateToggle(self) self:Fire("OnValueChanged", self.value) end -- exported local function SetValue(self, value) self.value = value UpdateToggle(self) end -- exported local function GetValue(self) return self.value end local function Constructor() local self = ItemBase.Create(widgetType) self.frame:SetScript("OnClick", Frame_OnClick) self.SetValue = SetValue self.GetValue = GetValue self.OnRelease = OnRelease AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Menu -- Shows a submenu on mouse over -- Does not close the pullout on click do local widgetType = "Dropdown-Item-Menu" local widgetVersion = 2 local function OnEnter(this) local self = this.obj self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end self.highlight:Show() if not self.disabled and self.submenu then self.submenu:Open("TOPLEFT", self.frame, "TOPRIGHT", self.pullout:GetRightBorderWidth(), 0, self.frame:GetFrameLevel() + 100) end end local function OnHide(this) local self = this.obj if self.submenu then self.submenu:Close() end end -- exported local function SetMenu(self, menu) assert(menu.type == "Dropdown-Pullout") self.submenu = menu end -- exported local function CloseMenu(self) self.submenu:Close() end local function Constructor() local self = ItemBase.Create(widgetType) self.sub:Show() self.frame:SetScript("OnEnter", OnEnter) self.frame:SetScript("OnHide", OnHide) self.SetMenu = SetMenu self.CloseMenu = CloseMenu AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Separator -- A single line to separate items do local widgetType = "Dropdown-Item-Separator" local widgetVersion = 2 -- exported, override local function SetDisabled(self, disabled) ItemBase.SetDisabled(self, disabled) self.useHighlight = false end local function Constructor() local self = ItemBase.Create(widgetType) self.SetDisabled = SetDisabled local line = self.frame:CreateTexture(nil, "OVERLAY") line:SetHeight(1) line:SetColorTexture(.5, .5, .5) line:SetPoint("LEFT", self.frame, "LEFT", 10, 0) line:SetPoint("RIGHT", self.frame, "RIGHT", -10, 0) self.text:Hide() self.useHighlight = false AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end
mit
lp/puredis
pdtests/redis_zset_suite.lua
1
2332
local suite = Suite("redis zset suite") suite.setup(function() _.outlet({"command","flushdb"}) _.outlet({"command","ZADD","MYZSET1",1,"M1"}) _.outlet({"command","ZADD","MYZSET1",2,"M2"}) _.outlet({"command","ZADD","MYZSET1",3,"M3"}) _.outlet({"command","ZADD","MYZSET1",4,"M4"}) _.outlet({"command","ZADD","MYZSET1",5,"M5"}) _.outlet({"command","ZADD","MYZSET2",3,"M3"}) _.outlet({"command","ZADD","MYZSET2",4,"M4"}) _.outlet({"command","ZADD","MYZSET2",5,"M5"}) _.outlet({"command","ZADD","MYZSET2",6,"M6"}) _.outlet({"command","ZADD","MYZSET2",7,"M7"}) end) suite.teardown(function() _.outlet({"command","flushdb"}) end) suite.case("ZADD" ).test({"command","ZADD","MYZSET1",6,"M6"} ).should:equal(1) suite.case("ZREM" ).test({"command","ZREM","MYZSET1","M2"} ).should:equal(1) suite.case("ZREMRANGEBYRANK" ).test({"command","ZREMRANGEBYRANK","MYZSET1",0,3} ).should:equal(4) suite.case("ZREMRANGEBYSCORE" ).test({"command","ZREMRANGEBYSCORE","MYZSET2",0,4} ).should:equal(2) suite.case("ZCARD" ).test({"command","ZCARD","MYZSET2"} ).should:equal(5) suite.case("ZCOUNT" ).test({"command","ZCOUNT","MYZSET2",5,"+inf"} ).should:equal(3) suite.case("ZSCORE" ).test({"command","ZSCORE","MYZSET2","M5"} ).should:equal("5") suite.case("ZRANK" ).test({"command","ZRANK","MYZSET1","M3"} ).should:equal(2) suite.case("ZREVRANK" ).test({"command","ZREVRANK","MYZSET1","M2"} ).should:equal(3) suite.case("ZINCRBY" ).test({"command","ZINCRBY","MYZSET2",2.5,"M7"} ).should:equal("9.5") suite.case("ZRANGE" ).test({"command","ZRANGE","MYZSET1",3,-1,"WITHSCORES"} ).should:resemble({"M4","4","M5","5"}) suite.case("ZRANGEBYSCORE" ).test({"command","ZRANGEBYSCORE","MYZSET1",2,4,"WITHSCORES"} ).should:equal({"M2","2","M3","3","M4","4"}) suite.case("ZREVRANGE" ).test({"command","ZREVRANGE","MYZSET1",3,-1,"WITHSCORES"} ).should:equal({"M2","2","M1","1"}) suite.case("ZREVRANGEBYSCORE" ).test({"command","ZREVRANGEBYSCORE","MYZSET1",4,2,"WITHSCORES"} ).should:equal({"M4","4","M3","3","M2","2"}) suite.case("ZINTERSTORE" ).test({"command","ZINTERSTORE","MYZSET3",2,"MYZSET1","MYZSET2"} ).should:equal(3) suite.case("ZUNIONSTORE" ).test({"command","ZUNIONSTORE","MYZSET3",2,"MYZSET1","MYZSET2"} ).should:equal(7)
mit
handsomecheung/miniKanren.lua
test.lua
1
4477
local MK = require("mk") local run = MK.run local run_all = MK.run_all local eq = MK.eq local not_eq = MK.not_eq local all = MK.all local alli = MK.alli local condi = MK.condi local cond = MK.cond local fresh_vars = MK.fresh_vars local succeed = MK.succeed local fail = MK.fail local list = MK.list local car = MK.car local cdr = MK.cdr local equal = MK.equal local NUM = require("num") local poso = NUM.poso local gt1o = NUM.gt1o local plus_1o = NUM.plus_1o local pluso = NUM.pluso local minuso = NUM.minuso local odd_multo = NUM.odd_multo local multo = NUM.multo local lto = NUM.lto local leo = NUM.leo local divo = NUM.divo local counto = NUM.counto local E = require("extend") local mergeo = E.mergeo local nullo = E.nullo local conso = E.conso r, a, b, c, d, e, f, g, a1, q, x = fresh_vars(11) assert(equal(run(false, a, (all(eq(a, b), not_eq(b, 2), not_eq(b, 3)))), { "_.0 not eq: 3,2" })) assert(equal(run(false, a, (all(eq(a, b), eq(b, c), not_eq(b, 2), not_eq(b, 3), not_eq(c, 4)))), { "_.0 not eq: 4,3,2" })) assert(equal(run(false, a, (all(eq(a, b), not_eq(b, 2), not_eq(b, 3), not_eq(1, 1)))), {})) -- assert(equal(run(false, a, (all(eq(b, 3), not_eq(a, b)))), { "_.0 not eq: 3" })) assert(equal(run(20, a, cond( all(eq(0, 1), eq(a, 1)), all(eq(0, 1), eq(a, 2)) )), {})) assert(equal(run(1, x, eq(x, 5)), {5})) assert(equal(run(1, list(a, b, x), eq(x, 5)), {list("_.1", "_.0", 5)})) assert(equal(run_all(x, all(eq(x, 5))), {5})) assert(equal(run_all(x, all(eq(x, 5), eq(6, 6))), {5})) assert(equal(run_all(x, all(eq(x, 5), eq(x, 6))), {})) assert(equal(run_all(x, cond(eq(x, 5), eq(x, 6))), {5, 6})) assert(equal(run(1, x, cond(eq(x, 5), eq(x, 6))), {5})) assert(equal(run(2, x, cond(eq(x, 5), eq(x, 6))), {5, 6})) assert(equal(run(10, x, cond(eq(x, 5), eq(x, 6))), {5, 6})) assert(equal(run(1, x, cond(eq(x, 5), eq(x, 6), all(eq(5, 5), eq(x, 7)))), {5})) assert(equal(run(2, x, cond(eq(x, 5), eq(x, 6), all(eq(5, 5), eq(x, 7)))), {5, 6})) assert(equal(run(3, x, cond(eq(x, 5), eq(x, 6), all(eq(5, 5), eq(x, 7)))), {5, 6, 7})) assert(equal(run_all(x, cond(eq(x, 5), eq(6, 6), eq(7, 7))), {5, "_.0", "_.0"})) assert(equal(run(1, x, cond(eq(x, 5), eq(6, 6), eq(7, 7))), {5})) assert(equal(run(2, x, cond(eq(x, 5), eq(6, 6), eq(7, 7))), {5, "_.0"})) assert(equal(run(3, x, cond(eq(x, 5), eq(6, 6), eq(7, 7))), {5, "_.0", "_.0"})) assert(equal(run(100, x, cond(eq(x, 5), eq(6, 6), eq(7, 7))), {5, "_.0", "_.0"})) assert(equal(run_all(list(a, b, c), cond(eq(a, 5), eq(b, 6), eq(c, 7))), {list(5, "_.1", "_.0"), list("_.1", 6, "_.0"), list("_.1", "_.0", 7)})) assert(equal(run_all(x, cond(eq(x, 5), eq(x, 6), cond(eq(x, 7), eq(x, 8)))), {5, 6, 7, 8})) assert(equal(run(1, x, cond(eq(x, 5), eq(x, 6), cond(eq(x, 7), eq(x, 8)))), {5})) assert(equal(run(2, x, cond(eq(x, 5), eq(x, 6), cond(eq(x, 7), eq(x, 8)))), {5, 6})) assert(equal(run(3, x, cond(eq(x, 5), eq(x, 6), cond(eq(x, 7), eq(x, 8)))), {5, 6, 7})) assert(equal(run(4, x, cond(eq(x, 5), eq(x, 6), cond(eq(x, 7), eq(x, 8)))), {5, 6, 7, 8})) assert(equal(run_all(x, cond(eq(x, 5), eq(x, 6), all(eq(x, 7), eq(x, 8)))), {5, 6})) assert(equal(run_all({x, 5}, cond(eq(x, 5), eq(x, 6), all(eq(x, 7), eq(x, 8)))), {{5, 5}, {6, 5}})) assert(equal(run_all(x, cond(eq({x, 1}, {2, 1}), eq({x, x}, {3, 3}))), {2, 3})) assert(equal(run(3, x, cond( eq(x, 2), eq(x, 3), function(s) return eq(x, 4)(s) end )), {2, 3, 4})) assert(equal(run(false, {a, b, c}, all(eq(a, 2), eq(a, b), not_eq(b, 3))), {{2, 2, "_.0"}})) assert(equal(run(false, {a, b, c}, all(eq(c, 2), eq(a, b), not_eq(b, 3))), { { "_.0 not eq: 3", "_.0 not eq: 3", 2 } })) assert(equal(run(false, {a, b}, all(eq(a, b), not_eq(a, 3))), { { "_.0 not eq: 3", "_.0 not eq: 3" } })) assert(equal(run(1, a, mergeo({1, {2, {3}}}, {4, {5, {6, {}}}}, a)), { list(1, 2, 3, 4, 5, 6) })) assert(equal(run(1, a, mergeo({1}, {2}, a)), { {1, {2}} })) assert(equal(run(1, a, mergeo({}, {1}, a)), { {1} })) assert(equal(run(1, a, mergeo({1}, {}, a)), { {1, {}} })) assert(equal( run(false, a, all( eq(a, b), eq(b, c), not_eq(a, 1), not_eq(b, 2), not_eq(c, 3))) , { "_.0 not eq: 3,2,1" }))
mit
alijoooon/Psycho
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
johannes-mueller/ardour
scripts/stop_at_marker.lua
1
1299
ardour { ["type"] = "session", name = "Stop at Marker", license = "MIT", author = "Ardour Lua Task Force", description = [[An example session script which stops the transport on every location marker when rolling forward.]] } function factory () return function (n_samples) if (not Session:transport_rolling ()) then -- not rolling, nothing to do. return end local pos = Session:transport_sample () -- current playhead position local loc = Session:locations () -- all marker locations -- find first marker after the current playhead position, ignore loop + punch ranges -- (this only works when rolling forward, to extend this example see -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:Locations ) local m = loc:first_mark_after (pos, false) if (m == -1) then -- no marker was found return end -- since ardour may split the process cycle for events, -- n_samples may be smaller. local blk = Session:get_block_size () -- transport stop can only happen on a process-cycle boundary. -- This callback happens from within the process callback, -- so we need to queue it ahead of time. if (pos + n_samples + blk >= m and pos + n_samples < m) then Session:request_transport_speed (0.0, true) end end end
gpl-2.0
Telewild/telewild
plugins/ingroup.lua
527
44020
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] 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.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators 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 get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators 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_namemod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" 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_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" 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 local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators 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_membermod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators 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 set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message 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 help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(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(v.id, result.id) 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 user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_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 savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() 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 if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
TeleDALAD/sg
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
valy012/safroid5
plugins/SUDO.lua
36
1917
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "شما دسترسی ندارید" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, 'آپ تایم') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "آپ تایم", patterns = {"^آپ تایم", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
Yonaba/Algorithm-Implementations
Bellman_Ford_Search/Lua/Yonaba/bellmanford.lua
26
3025
-- Bellman Ford single source shortest path search algorithm implementation -- See : https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm -- Notes : this is a generic implementation of Bellman Ford search algorithm. -- It is devised to be used on waypoint graphs. -- The BellmanFord class expects a handler to be initialized. Roughly said, the handler -- is an interface between your graph and the search algorithm. -- The passed-in handler should implement those functions. -- handler.getNode(...) -> returns a Node (instance of node.lua) -- handler.getAllNodes() -> returns an array list of all nodes in the graph -- handler.getAllEdges() -> returns an array list of all edges in the graph -- See utils/graph.lua for reference -- The generic Node class provided (see utils/node.lua) should also be implemented -- through the handler. Basically, it should describe how nodes are labelled -- and tested for equality for a custom search space. -- The following functions should be implemented: -- function Node:initialize(...) -> creates a Node with custom attributes -- function Node:toString() -> returns a unique string representation of -- the node, for debug purposes -- Dependencies local class = require 'utils.class' -- Clears nodes data between consecutive path requests. local function resetForNextSearch(bellmanford) local nodes = bellmanford.handler.getAllNodes() for _, node in pairs(nodes) do node.parent = nil node.distance = math.huge end end -- Builds and returns the path to the goal node local function backtrace(node) local path = {} repeat table.insert(path, 1, node) node = node.parent until not node return path end -- Initializes Bellman Ford search with a custom handler local BellmanFord = class() function BellmanFord:initialize(handler) self.handler = handler end -- Processes the graph for shortest paths -- source : the starting node from which the search will spread. -- target : the goal node -- When done, the shortest path from one node to another can easily -- backtraced by indexing the parent field of a node. -- Return : if target supplied, returns the shortest path from source -- to target. function BellmanFord:process(source, target) resetForNextSearch(self) source.distance = 0 local nodes = self.handler.getAllNodes() local edges = self.handler.getAllEdges() -- Relaxing all edges |V| - 1 times for i = 1, #nodes - 1 do for i, edge in ipairs(edges) do local u, v, w = edge.from, edge.to, edge.weight local tempDistance = u.distance + w if tempDistance < v.distance then v.distance, v.parent = tempDistance, u end end end -- Checking for negative cycles for i, edge in ipairs(edges) do local u, v, w = edge.from, edge.to, edge.weight local tempDistance = u.distance + w assert(tempDistance >= v.distance, 'Negative cycle found!') end if target then return backtrace(target) end end return BellmanFord
mit
ingran/balzac
custom_feeds/teltonika_luci/modules/admin-mini/luasrc/controller/mini/system.lua
1
6723
--[[ 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: system.lua 7362 2011-08-12 13:16:27Z jow $ ]]-- module("luci.controller.mini.system", package.seeall) function index() entry({"mini", "system"}, alias("mini", "system", "index"), _("System"), 40).index = true entry({"mini", "system", "index"}, cbi("mini/system", {autoapply=true}), _("General"), 1) entry({"mini", "system", "passwd"}, form("mini/passwd"), _("Admin Password"), 10) entry({"mini", "system", "backup"}, call("action_backup"), _("Backup / Restore"), 80) entry({"mini", "system", "upgrade"}, call("action_upgrade"), _("Flash Firmware"), 90) entry({"mini", "system", "reboot"}, call("action_reboot"), _("Reboot"), 100) end function action_backup() local reset_avail = os.execute([[grep '"rootfs_data"' /proc/mtd >/dev/null 2>&1]]) == 0 local restore_cmd = "gunzip | tar -xC/ >/dev/null 2>&1" local backup_cmd = "tar -c %s | gzip 2>/dev/null" local restore_fpi luci.http.setfilehandler( function(meta, chunk, eof) if not restore_fpi then restore_fpi = io.popen(restore_cmd, "w") end if chunk then restore_fpi:write(chunk) end if eof then restore_fpi:close() end end ) local upload = luci.http.formvalue("archive") local backup = luci.http.formvalue("backup") local reset = reset_avail and luci.http.formvalue("reset") if upload and #upload > 0 then luci.template.render("mini/applyreboot") luci.sys.reboot() elseif backup then local reader = ltn12_popen(backup_cmd:format(_keep_pattern())) luci.http.header(translate('Content-Disposition'), 'attachment; filename="backup-%s-%s.tar.gz"' % { luci.sys.hostname(), os.date("%Y-%m-%d")}) luci.http.prepare_content("application/x-targz") luci.ltn12.pump.all(reader, luci.http.write) elseif reset then luci.template.render("mini/applyreboot") luci.util.exec("mtd -r erase rootfs_data") else luci.template.render("mini/backup", {reset_avail = reset_avail}) end end function action_reboot() local reboot = luci.http.formvalue("reboot") luci.template.render("mini/reboot", {reboot=reboot}) if reboot then luci.sys.reboot() end end function action_upgrade() require("luci.model.uci") local tmpfile = "/tmp/firmware.img" local function image_supported() -- XXX: yay... return ( 0 == os.execute( ". /etc/functions.sh; " .. "include /lib/upgrade; " .. "platform_check_image %q >/dev/null" % tmpfile ) ) end local function image_checksum() return (luci.sys.exec("md5sum %q" % tmpfile):match("^([^%s]+)")) end local function storage_size() local size = 0 if nixio.fs.access("/proc/mtd") then for l in io.lines("/proc/mtd") do local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"') if n == "linux" then size = tonumber(s, 16) break end end elseif nixio.fs.access("/proc/partitions") then for l in io.lines("/proc/partitions") do local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)') if b and n and not n:match('[0-9]') then size = tonumber(b) * 1024 break end end end return size end -- Install upload handler local file luci.http.setfilehandler( function(meta, chunk, eof) if not nixio.fs.access(tmpfile) and not file and chunk and #chunk > 0 then file = io.open(tmpfile, "w") end if file and chunk then file:write(chunk) end if file and eof then file:close() end end ) -- Determine state local keep_avail = true local step = tonumber(luci.http.formvalue("step") or 1) local has_image = nixio.fs.access(tmpfile) local has_support = image_supported() local has_platform = nixio.fs.access("/lib/upgrade/platform.sh") local has_upload = luci.http.formvalue("image") -- This does the actual flashing which is invoked inside an iframe -- so don't produce meaningful errors here because the the -- previous pages should arrange the stuff as required. if step == 4 then if has_platform and has_image and has_support then -- Mimetype text/plain luci.http.prepare_content("text/plain") luci.http.write("Starting luci-flash...\n") -- Now invoke sysupgrade local keepcfg = keep_avail and luci.http.formvalue("keepcfg") == "1" local flash = ltn12_popen("/sbin/luci-flash %s %q" %{ keepcfg and "-k %q" % _keep_pattern() or "", tmpfile }) luci.ltn12.pump.all(flash, luci.http.write) -- Make sure the device is rebooted luci.sys.reboot() end -- -- This is step 1-3, which does the user interaction and -- image upload. -- -- Step 1: file upload, error on unsupported image format elseif not has_image or not has_support or step == 1 then -- If there is an image but user has requested step 1 -- or type is not supported, then remove it. if has_image then nixio.fs.unlink(tmpfile) end luci.template.render("mini/upgrade", { step=1, bad_image=(has_image and not has_support or false), keepavail=keep_avail, supported=has_platform } ) -- Step 2: present uploaded file, show checksum, confirmation elseif step == 2 then luci.template.render("mini/upgrade", { step=2, checksum=image_checksum(), filesize=nixio.fs.stat(tmpfile).size, flashsize=storage_size(), keepconfig=(keep_avail and luci.http.formvalue("keepcfg") == "1") } ) -- Step 3: load iframe which calls the actual flash procedure elseif step == 3 then luci.template.render("mini/upgrade", { step=3, keepconfig=(keep_avail and luci.http.formvalue("keepcfg") == "1") } ) end end function _keep_pattern() local kpattern = "" local files = luci.model.uci.cursor():get_all("luci", "flash_keep") if files then kpattern = "" for k, v in pairs(files) do if k:sub(1,1) ~= "." and nixio.fs.glob(v)() then kpattern = kpattern .. " " .. v end end end return kpattern end function ltn12_popen(command) local fdi, fdo = nixio.pipe() local pid = nixio.fork() if pid > 0 then fdo:close() local close return function() local buffer = fdi:read(2048) local wpid, stat = nixio.waitpid(pid, "nohang") if not close and wpid and stat == "exited" then close = true end if buffer and #buffer > 0 then return buffer elseif close then fdi:close() return nil end end elseif pid == 0 then nixio.dup(fdo, nixio.stdout) fdi:close() fdo:close() nixio.exec("/bin/sh", "-c", command) end end
gpl-2.0
dromozoa/dromozoa-commons
dromozoa/commons/hash_table.lua
2
2781
-- Copyright (C) 2015,2017 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-commons. -- -- dromozoa-commons is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>. local hash_table_impl = require "dromozoa.commons.hash_table_impl" local private_impl = function () end local class = {} function class.new(hasher) return { [private_impl] = hash_table_impl(hasher); } end function class:get(key) if key == nil then return nil end local t = type(key) if t == "number" or t == "string" or t == "boolean" then return rawget(self, key) else local impl = self[private_impl] return impl:get(key) end end function class:each() return coroutine.wrap(function () for k, v in next, self do if k == private_impl then for k, v in v:each() do coroutine.yield(k, v) end else coroutine.yield(k, v) end end end) end function class:insert(key, value, overwrite) if key == nil then error "table index is nil" end if value == nil then value = true end local t = type(key) if t == "number" or t == "string" or t == "boolean" then local v = rawget(self, key) if v == nil or overwrite then rawset(self, key, value) end return v else local impl = self[private_impl] return impl:insert(key, value, overwrite) end end function class:remove(key) if key == nil then error "table index is nil" end local t = type(key) if t == "number" or t == "string" or t == "boolean" then local v = rawget(self, key) rawset(self, key, nil) return v else local impl = self[private_impl] return impl:remove(key) end end function class:set(key, value) if value == nil then return class.remove(self, key) else return class.insert(self, key, value, true) end end class.metatable = { __newindex = class.set; __pairs = class.each; } function class.metatable:__index(key) local v = class.get(self, key) if v == nil then return class[key] else return v end end return setmetatable(class, { __call = function (_, hasher) return setmetatable(class.new(hasher), class.metatable) end; })
gpl-3.0
liruqi/bigfoot
Interface/AddOns/Decursive/Dcr_lists.lua
1
16625
--[[ This file is part of Decursive. Decursive (v 2.7.5.7) add-on for World of Warcraft UI Copyright (C) 2006-2014 John Wellesz (archarodim AT teaser.fr) ( http://www.2072productions.com/to/decursive.php ) Starting from 2009-10-31 and until said otherwise by its author, Decursive is no longer free software, all rights are reserved to its author (John Wellesz). The only official and allowed distribution means are www.2072productions.com, www.wowace.com and curse.com. To distribute Decursive through other means a special authorization is required. Decursive is inspired from the original "Decursive v1.9.4" by Patrick Bohnet (Quu). The original "Decursive 1.9.4" is in public domain ( www.quutar.com ) Decursive is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. --]] ------------------------------------------------------------------------------- local addonName, T = ...; -- big ugly scary fatal error message display function {{{ if not T._FatalError then -- the beautiful error popup : {{{ - StaticPopupDialogs["DECURSIVE_ERROR_FRAME"] = { text = "|cFFFF0000Decursive Error:|r\n%s", button1 = "OK", OnAccept = function() return false; end, timeout = 0, whileDead = 1, hideOnEscape = 1, showAlert = 1, preferredIndex = 3, }; -- }}} T._FatalError = function (TheError) StaticPopup_Show ("DECURSIVE_ERROR_FRAME", TheError); end end -- }}} if not T._LoadedFiles or not T._LoadedFiles["Decursive.xml"] or not T._LoadedFiles["Decursive.lua"] then if not DecursiveInstallCorrupted then T._FatalError("Decursive installation is corrupted! (Decursive.xml or Decursive.lua not loaded)"); end; DecursiveInstallCorrupted = true; return; end T._LoadedFiles["Dcr_lists.lua"] = false; local D = T.Dcr; local L = D.L; local LC = D.LC; local DC = T._C; local _; local _G = _G; local pairs = _G.pairs; local ipairs = _G.ipairs; local type = _G.type; local string = _G.string; local UnitGUID = _G.UnitGUID; local table = _G.table; local str_format = _G.string.format; local t_insert = _G.table.insert; local UnitClass = _G.UnitClass; local UnitExists = _G.UnitExists; local UnitIsPlayer = _G.UnitIsPlayer; local GetRaidRosterInfo = _G.GetRaidRosterInfo; local IsShiftKeyDown = _G.IsShiftKeyDown; local IsControlKeyDown = _G.IsControlKeyDown; -- Dcr_ListFrameTemplate specific internal functions {{{ function D.ListFrameTemplate_OnLoad(frame) frame.ScrollFrame = _G[frame:GetName().."ScrollFrame"]; frame.ScrollBar = _G[frame.ScrollFrame:GetName().."ScrollBar"]; frame.ScrollFrame.offset = 0; end function D:ListFrameScrollFrameTemplate_OnMouseWheel(frame, value) local scrollBar = _G[frame:GetName().."ScrollBar"]; local min, max = scrollBar:GetMinMaxValues(); if ( value > 0 ) then if (IsShiftKeyDown() ) then scrollBar:SetValue(min); else scrollBar:SetValue(scrollBar:GetValue() - scrollBar:GetValueStep()); end else if (IsShiftKeyDown() ) then scrollBar:SetValue(max); else scrollBar:SetValue(scrollBar:GetValue() + scrollBar:GetValueStep()); end end end -- }}} -- Dcr_ListFrameTemplate specific handlers {{{ function D.PrioSkipListFrame_OnUpdate(frame) --{{{ if not D.DcrFullyInitialized then return; end if (frame.UpdateYourself) then frame.UpdateYourself = false; local baseName = frame:GetName(); local size; if (frame.Priority) then size = #D.profile.PriorityList; else size = #D.profile.SkipList; end -- D:Debug("PrioSkipListFrame_OnUpdate executed", size, this.ScrollFrame.offset); local i; for i = 1, 10 do local id = ""..i; if (i < 10) then id = "0"..i; end local btn = _G[baseName.."Index"..id]; btn:SetID( i + frame.ScrollFrame.offset); D:PrioSkipListEntry_Update(btn); if (i <= size) then btn:Show(); else btn:Hide(); end end frame.ScrollUpdateFunc(_G[baseName.."ScrollFrame"], true); end end --}}} function D.PrioSkipListEntryTemplate_OnClick(listFrame, entryBFrame, button) --{{{ local list; local UnitNum; if listFrame.Priority then list = D.profile.PriorityList; UnitNum = #D.profile.PriorityList; else list = D.profile.SkipList; UnitNum = #D.profile.SkipList; end local id = entryBFrame:GetID(); if (id) then if (IsControlKeyDown()) then if (listFrame.Priority) then D:RemoveIDFromPriorityList(id); else D:RemoveIDFromSkipList(id); end elseif (UnitNum > 1) then local previousUnit_ID, previousUnit, nextUnit_ID, nextUnit, currentUnit; previousUnit_ID = id - 1; nextUnit_ID = id + 1; previousUnit = list[previousUnit_ID]; nextUnit = list[nextUnit_ID ]; currentUnit = list[id]; if (button=="RightButton" and IsShiftKeyDown()) then -- move at the bottom table.remove(list, id); table.insert(list, UnitNum, currentUnit); elseif (button=="LeftButton" and IsShiftKeyDown()) then -- move at the top table.remove(list, id); table.insert(list, 1, currentUnit); elseif (button=="LeftButton" and id ~= 1) then -- unit gets higher D:Debug("upping %s of id %d", list[id], id); list[previousUnit_ID] = list[id]; list[id] = previousUnit; elseif (button=="RightButton" and id ~= UnitNum) then -- unit gets lower D:Debug("downing %s of id %d", list[id], id); list[nextUnit_ID] = list[id]; list[id] = nextUnit; elseif (button=="MiddleButton") then end listFrame.UpdateYourself = true; end D.Status.PrioChanged = true; D:GroupChanged ("PrioSkipListEntryTemplate_OnClick"); else D:Debug("No ID"); end end --}}} function D:PrioSkipListEntry_Update(Entry) --{{{ local id = Entry:GetID(); if (id) then --D:Debug("PrioSkipListEntry_Update executed"); local name, classname, GUIDorNum; if (Entry:GetParent().Priority) then GUIDorNum = D.profile.PriorityList[id]; classname = D.profile.PriorityListClass[GUIDorNum]; name = D.profile.PrioGUIDtoNAME[GUIDorNum]; else GUIDorNum = D.profile.SkipList[id]; classname = D.profile.SkipListClass[GUIDorNum]; name = D.profile.SkipGUIDtoNAME[GUIDorNum]; end if (GUIDorNum) then if (type(GUIDorNum) == "number") then if (GUIDorNum > 10) then name = str_format("[ %s ]", DC.ClassNumToLName[GUIDorNum]); elseif GUIDorNum > 0 then name = str_format("[ %s %s ]", L["STR_GROUP"], GUIDorNum); else name = str_format("[ %s ]", _G[({"HEALER", "TANK", "DAMAGER"})[-GUIDorNum]] or GUIDorNum); end end Entry:SetText(id.." - "..D:ColorText(name, classname and "FF"..DC.HexClassColor[classname] or (GUIDorNum > 0 and "FFCACAF0" or "FFBAF0DA") )); else Entry:SetText("Error - NO name!"); end else Entry:SetText("Error - No ID!"); end end --}}} function D.PrioSkipList_ScrollFrame_Update (ScrollFrame) -- {{{ if not D.DcrFullyInitialized then return; end local maxentry; local UpdateListOnceDone = true; local DirectCall = false; D:Debug("ScrollFrame is a %s", type(ScrollFrame)); if (not ScrollFrame) then --ScrollFrame = this; -- Called from the scrollbar frame handler else --UpdateListOnceDone = false; -- The function was called from the list update function DirectCall = true; end if (not ScrollFrame.UpdateYourself) then ScrollFrame.UpdateYourself = true; return; end if (ScrollFrame:GetParent().Priority) then maxentry = #D.profile.PriorityList; else maxentry = #D.profile.SkipList; end FauxScrollFrame_Update(ScrollFrame,maxentry,10,16); if (UpdateListOnceDone) then ScrollFrame.UpdateYourself = false; -- prevent this function to re-execute unecessarily ScrollFrame:GetParent().UpdateYourself = true; end D:Debug("PrioSkipList_ScrollFrame_Update executed for %s", ScrollFrame:GetName()); end -- }}} -- }}} -- list specific management functions {{{ ------------------------------------------------------------------------------- function D:AddTargetToPriorityList() --{{{ D:Debug( "Adding the target to the priority list"); return D:AddElementToPriorityList("target", true); end --}}} local function AddElementToList(element, checkIfExist, list, listGUIDtoName, listClass) -- {{{ if not D.DcrFullyInitialized then return false; end if #list > 99 then return false; end if not checkIfExist or UnitExists(element) then if type(element) == "number" or UnitIsPlayer(element) then D:Debug("adding %s", element); local GUIDorNum; if type(element) == "number" then GUIDorNum = element; else GUIDorNum = UnitGUID(element); if not GUIDorNum then return false; end end if listGUIDtoName[GUIDorNum] then return false; end table.insert(list, GUIDorNum); if type(element) == "string" then _, listClass[GUIDorNum] = UnitClass(element); listGUIDtoName[GUIDorNum] = D:UnitName(element); elseif element > 10 then listClass[element] = DC.ClassNumToUName[element]; listGUIDtoName[GUIDorNum] = str_format("[ %s ]", DC.ClassNumToLName[GUIDorNum]); else listGUIDtoName[GUIDorNum] = str_format("[ %s %s ]", L["STR_GROUP"], GUIDorNum); end return true; else D:Debug("Unit is not a player:", element, checkIfExist, UnitExists(element)); if not element then error("D:AddElementToList: bad argument #1 'element' must be!",2); end end else D:Debug("Unit does not exist"); end return false; end -- }}} function D:AddElementToPriorityList(element, check) --{{{ if AddElementToList(element, check, D.profile.PriorityList, D.profile.PrioGUIDtoNAME, D.profile.PriorityListClass) then DecursivePriorityListFrame.UpdateYourself = true; D.Status.PrioChanged = true; D:GroupChanged("AddElementToPriorityList"); D:Debug("Unit %s added to the prio list", element); return true; else return false; end end --}}} function D:RemoveIDFromPriorityList(id) --{{{ D.profile.PriorityListClass[ D.profile.PriorityList[id] ] = nil; -- remove it from the table D.profile.PrioGUIDtoNAME[ D.profile.PriorityList[id]] = nil; table.remove( D.profile.PriorityList, id ); D.Status.PrioChanged = true; D:GroupChanged ("RemoveIDFromPriorityList"); DecursivePriorityListFrame.UpdateYourself = true; end --}}} function D:ClearPriorityList() --{{{ D.profile.PriorityList = {}; D.profile.PriorityListClass = {}; D.profile.PrioGUIDtoNAME = {}; D.Status.PrioChanged = true; D:GroupChanged ("ClearPriorityList"); DecursivePriorityListFrame.UpdateYourself = true; end --}}} function D:AddTargetToSkipList() --{{{ D:Debug( "Adding the target to the Skip list"); return D:AddElementToSkipList("target"); end --}}} function D:AddElementToSkipList(element, check) --{{{ if AddElementToList(element, check, D.profile.SkipList, D.profile.SkipGUIDtoNAME, D.profile.SkipListClass) then DecursiveSkipListFrame.UpdateYourself = true; D.Status.PrioChanged = true; D:GroupChanged ("AddElementToSkipList"); D:Debug("Unit %s added to the skip list", element); return true; else return false; end end --}}} function D:RemoveIDFromSkipList(id) --{{{ D.profile.SkipListClass[ D.profile.SkipList[id] ] = nil; -- remove it from the table D.profile.SkipGUIDtoNAME[ D.profile.SkipList[id]] = nil; table.remove( D.profile.SkipList, id ); D.Status.PrioChanged = true; D:GroupChanged ("RemoveIDFromSkipList"); DecursiveSkipListFrame.UpdateYourself = true; end --}}} function D:ClearSkipList() --{{{ local i; D.profile.SkipList = {}; D.profile.SkipListClass = {}; D.profile.SkipGUIDtoNAME = {}; D.Status.PrioChanged = true; D.Groups_datas_are_invalid = true; D:GroupChanged ("ClearSkipList"); DecursiveSkipListFrame.UpdateYourself = true; end --}}} function D:IsInPriorList (GUID) --{{{ return self.Status.InternalPrioList[GUID] or false; end --}}} function D:IsInSkipList (GUID) --{{{ return self.Status.InternalSkipList[GUID] or false; end --}}} -- }}} function D:PopulateButtonPress(frame) --{{{ local PopulateFrame = frame:GetParent(); local UppedClass = ""; if (IsShiftKeyDown() and frame.ClassType) then -- UnitClass returns uppercased class... UppedClass = string.upper(frame.ClassType); D:Debug("Populate called for %s", frame.ClassType); -- for the class type stuff... we do party local _, pclass = UnitClass("player"); if (pclass == UppedClass) then PopulateFrame:addFunction("player"); end _, pclass = UnitClass("party1"); if (pclass == UppedClass) then PopulateFrame:addFunction("party1"); end _, pclass = UnitClass("party2"); if (pclass == UppedClass) then PopulateFrame:addFunction("party2"); end _, pclass = UnitClass("party3"); if (pclass == UppedClass) then PopulateFrame:addFunction("party3"); end _, pclass = UnitClass("party4"); if (pclass == UppedClass) then PopulateFrame:addFunction("party4"); end end local i, pgroup, pclass; if (IsShiftKeyDown() and frame.ClassType) then D:Debug("Finding raid units with a macthing class"); for index, unit in ipairs(D.Status.Unit_Array) do _, pclass = UnitClass(unit); if (pclass == UppedClass) then D:Debug("found %s", pclass); PopulateFrame:addFunction(unit); end end elseif (frame.ClassType) then PopulateFrame:addFunction(DC.ClassUNameToNum[string.upper(frame.ClassType)]); end local max = DC.GetNumRaidMembers(); if (IsShiftKeyDown() and frame.GroupNumber and max > 0) then D:Debug("Finding raid units with a matching group number"); for i = 1, max do _, _, pgroup, _, _, pclass = GetRaidRosterInfo(i); if (pgroup == frame.GroupNumber) then D:Debug("found %s in group %d", pclass, max); PopulateFrame:addFunction("raid"..i); end end elseif (not IsShiftKeyDown() and frame.GroupNumber) then PopulateFrame:addFunction(frame.GroupNumber); end end --}}} T._LoadedFiles["Dcr_lists.lua"] = "2.7.5.7";
mit
BeaconNet/sPhone
src/apis/bigfont.lua
3
17220
--# BigFont API - Write bigger letters. v1.1 --# Made By Wojbie --# http://pastebin.com/3LfWxRWh local rawFont = { { "\32\32\32\137\156\148\158\159\148\135\135\144\159\139\32\136\157\32\159\139\32\32\143\32\32\143\32\32\32\32\32\32\32\32\147\148\150\131\148\32\32\32\151\140\148\151\140\147", "\32\32\32\149\132\149\136\156\149\144\32\133\139\159\129\143\159\133\143\159\133\138\32\133\138\32\133\32\32\32\32\32\32\150\150\129\137\156\129\32\32\32\133\131\129\133\131\132", "\32\32\32\130\131\32\130\131\32\32\129\32\32\32\32\130\131\32\130\131\32\32\32\32\143\143\143\32\32\32\32\32\32\130\129\32\130\135\32\32\32\32\131\32\32\131\32\131", "\139\144\32\32\143\148\135\130\144\149\32\149\150\151\149\158\140\129\32\32\32\135\130\144\135\130\144\32\149\32\32\139\32\159\148\32\32\32\32\159\32\144\32\148\32\147\131\132", "\159\135\129\131\143\149\143\138\144\138\32\133\130\149\149\137\155\149\159\143\144\147\130\132\32\149\32\147\130\132\131\159\129\139\151\129\148\32\32\139\131\135\133\32\144\130\151\32", "\32\32\32\32\32\32\130\135\32\130\32\129\32\129\129\131\131\32\130\131\129\140\141\132\32\129\32\32\129\32\32\32\32\32\32\32\131\131\129\32\32\32\32\32\32\32\32\32", "\32\32\32\32\149\32\159\154\133\133\133\144\152\141\132\133\151\129\136\153\32\32\154\32\159\134\129\130\137\144\159\32\144\32\148\32\32\32\32\32\32\32\32\32\32\32\151\129", "\32\32\32\32\133\32\32\32\32\145\145\132\141\140\132\151\129\144\150\146\129\32\32\32\138\144\32\32\159\133\136\131\132\131\151\129\32\144\32\131\131\129\32\144\32\151\129\32", "\32\32\32\32\129\32\32\32\32\130\130\32\32\129\32\129\32\129\130\129\129\32\32\32\32\130\129\130\129\32\32\32\32\32\32\32\32\133\32\32\32\32\32\129\32\129\32\32", "\150\156\148\136\149\32\134\131\148\134\131\148\159\134\149\136\140\129\152\131\32\135\131\149\150\131\148\150\131\148\32\148\32\32\148\32\32\152\129\143\143\144\130\155\32\134\131\148", "\157\129\149\32\149\32\152\131\144\144\131\148\141\140\149\144\32\149\151\131\148\32\150\32\150\131\148\130\156\133\32\144\32\32\144\32\130\155\32\143\143\144\32\152\129\32\134\32", "\130\131\32\131\131\129\131\131\129\130\131\32\32\32\129\130\131\32\130\131\32\32\129\32\130\131\32\130\129\32\32\129\32\32\133\32\32\32\129\32\32\32\130\32\32\32\129\32", "\150\140\150\137\140\148\136\140\132\150\131\132\151\131\148\136\147\129\136\147\129\150\156\145\138\143\149\130\151\32\32\32\149\138\152\129\149\32\32\157\152\149\157\144\149\150\131\148", "\149\143\142\149\32\149\149\32\149\149\32\144\149\32\149\149\32\32\149\32\32\149\32\149\149\32\149\32\149\32\144\32\149\149\130\148\149\32\32\149\32\149\149\130\149\149\32\149", "\130\131\129\129\32\129\131\131\32\130\131\32\131\131\32\131\131\129\129\32\32\130\131\32\129\32\129\130\131\32\130\131\32\129\32\129\131\131\129\129\32\129\129\32\129\130\131\32", "\136\140\132\150\131\148\136\140\132\153\140\129\131\151\129\149\32\149\149\32\149\149\32\149\137\152\129\137\152\129\131\156\133\149\131\32\150\32\32\130\148\32\152\137\144\32\32\32", "\149\32\32\149\159\133\149\32\149\144\32\149\32\149\32\149\32\149\150\151\129\138\155\149\150\130\148\32\149\32\152\129\32\149\32\32\32\150\32\32\149\32\32\32\32\32\32\32", "\129\32\32\130\129\129\129\32\129\130\131\32\32\129\32\130\131\32\32\129\32\129\32\129\129\32\129\32\129\32\131\131\129\130\131\32\32\32\129\130\131\32\32\32\32\140\140\132", "\32\154\32\159\143\32\149\143\32\159\143\32\159\144\149\159\143\32\159\137\145\159\143\144\149\143\32\32\145\32\32\32\145\149\32\144\32\149\32\143\159\32\143\143\32\159\143\32", "\32\32\32\152\140\149\151\32\149\149\32\145\149\130\149\157\140\133\32\149\32\154\143\149\151\32\149\32\149\32\144\32\149\149\153\32\32\149\32\149\133\149\149\32\149\149\32\149", "\32\32\32\130\131\129\131\131\32\130\131\32\130\131\129\130\131\129\32\129\32\140\140\129\129\32\129\32\129\32\137\140\129\130\32\129\32\130\32\129\32\129\129\32\129\130\131\32", "\144\143\32\159\144\144\144\143\32\159\143\144\159\138\32\144\32\144\144\32\144\144\32\144\144\32\144\144\32\144\143\143\144\32\150\129\32\149\32\130\150\32\134\137\134\134\131\148", "\136\143\133\154\141\149\151\32\129\137\140\144\32\149\32\149\32\149\154\159\133\149\148\149\157\153\32\154\143\149\159\134\32\130\148\32\32\149\32\32\151\129\32\32\32\32\134\32", "\133\32\32\32\32\133\129\32\32\131\131\32\32\130\32\130\131\129\32\129\32\130\131\129\129\32\129\140\140\129\131\131\129\32\130\129\32\129\32\130\129\32\32\32\32\32\129\32", "\32\32\32\32\149\32\32\149\32\32\32\32\32\32\32\32\149\32\32\149\32\32\32\32\32\32\32\32\149\32\32\149\32\32\32\32\32\32\32\32\149\32\32\149\32\32\32\32", "\32\32\32\32\32\32\32\32\32\32\32\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\32\32\32\32\32\32\32\32\32\32\32", "\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32", "\32\32\32\32\149\32\32\149\32\32\32\32\32\32\32\32\149\32\32\149\32\32\32\32\32\32\32\32\149\32\32\149\32\32\32\32\32\32\32\32\149\32\32\149\32\32\32\32", "\32\32\32\32\32\32\32\32\32\32\32\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\32\32\32\32\32\32\32\32\32\32\32", "\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32\32\149\32", "\32\32\32\32\145\32\159\139\32\151\131\132\155\143\132\134\135\145\32\149\32\158\140\129\130\130\32\152\147\155\157\134\32\32\144\144\32\32\32\32\32\32\152\131\155\131\131\129", "\32\32\32\32\149\32\149\32\145\148\131\32\149\32\149\140\157\132\32\148\32\137\155\149\32\32\32\149\154\149\137\142\32\153\153\32\131\131\149\131\131\129\149\135\145\32\32\32", "\32\32\32\32\129\32\130\135\32\131\131\129\134\131\132\32\129\32\32\129\32\131\131\32\32\32\32\130\131\129\32\32\32\32\129\129\32\32\32\32\32\32\130\131\129\32\32\32", "\150\150\32\32\148\32\134\32\32\132\32\32\134\32\32\144\32\144\150\151\149\32\32\32\32\32\32\145\32\32\152\140\144\144\144\32\133\151\129\133\151\129\132\151\129\32\145\32", "\130\129\32\131\151\129\141\32\32\142\32\32\32\32\32\149\32\149\130\149\149\32\143\32\32\32\32\142\132\32\154\143\133\157\153\132\151\150\148\151\158\132\151\150\148\144\130\148", "\32\32\32\140\140\132\32\32\32\32\32\32\32\32\32\151\131\32\32\129\129\32\32\32\32\134\32\32\32\32\32\32\32\129\129\32\129\32\129\129\130\129\129\32\129\130\131\32", "\156\143\32\159\141\129\153\140\132\153\137\32\157\141\32\159\142\32\150\151\129\150\131\132\140\143\144\143\141\145\137\140\148\141\141\144\157\142\32\159\140\32\151\134\32\157\141\32", "\157\140\149\157\140\149\157\140\149\157\140\149\157\140\149\157\140\149\151\151\32\154\143\132\157\140\32\157\140\32\157\140\32\157\140\32\32\149\32\32\149\32\32\149\32\32\149\32", "\129\32\129\129\32\129\129\32\129\129\32\129\129\32\129\129\32\129\129\131\129\32\134\32\131\131\129\131\131\129\131\131\129\131\131\129\130\131\32\130\131\32\130\131\32\130\131\32", "\151\131\148\152\137\145\155\140\144\152\142\145\153\140\132\153\137\32\154\142\144\155\159\132\150\156\148\147\32\144\144\130\145\136\137\32\146\130\144\144\130\145\130\136\32\151\140\132", "\151\32\149\151\155\149\149\32\149\149\32\149\149\32\149\149\32\149\149\32\149\152\137\144\157\129\149\149\32\149\149\32\149\149\32\149\149\32\149\130\150\32\32\157\129\149\32\149", "\131\131\32\129\32\129\130\131\32\130\131\32\130\131\32\130\131\32\130\131\32\32\32\32\130\131\32\130\131\32\130\131\32\130\131\32\130\131\32\32\129\32\130\131\32\133\131\32", "\156\143\32\159\141\129\153\140\132\153\137\32\157\141\32\159\142\32\159\159\144\152\140\144\156\143\32\159\141\129\153\140\132\157\141\32\130\145\32\32\147\32\136\153\32\130\146\32", "\152\140\149\152\140\149\152\140\149\152\140\149\152\140\149\152\140\149\149\157\134\154\143\132\157\140\133\157\140\133\157\140\133\157\140\133\32\149\32\32\149\32\32\149\32\32\149\32", "\130\131\129\130\131\129\130\131\129\130\131\129\130\131\129\130\131\129\130\130\131\32\134\32\130\131\129\130\131\129\130\131\129\130\131\129\32\129\32\32\129\32\32\129\32\32\129\32", "\159\134\144\137\137\32\156\143\32\159\141\129\153\140\132\153\137\32\157\141\32\32\132\32\159\143\32\147\32\144\144\130\145\136\137\32\146\130\144\144\130\145\130\138\32\146\130\144", "\149\32\149\149\32\149\149\32\149\149\32\149\149\32\149\149\32\149\149\32\149\131\147\129\138\134\149\149\32\149\149\32\149\149\32\149\149\32\149\154\143\149\32\157\129\154\143\149", "\130\131\32\129\32\129\130\131\32\130\131\32\130\131\32\130\131\32\130\131\32\32\32\32\130\131\32\130\131\129\130\131\129\130\131\129\130\131\129\140\140\129\130\131\32\140\140\129", }, { [[000110000110110000110010101000000010000000100101]], [[000000110110000000000010101000000010000000100101]], [[000000000000000000000000000000000000000000000000]], [[100010110100000010000110110000010100000100000110]], [[000000110000000010110110000110000000000000110000]], [[000000000000000000000000000000000000000000000000]], [[000000110110000010000000100000100000000000000010]], [[000000000110110100010000000010000000000000000100]], [[000000000000000000000000000000000000000000000000]], [[010000000000100110000000000000000000000110010000]], [[000000000000000000000000000010000000010110000000]], [[000000000000000000000000000000000000000000000000]], [[011110110000000100100010110000000100000000000000]], [[000000000000000000000000000000000000000000000000]], [[000000000000000000000000000000000000000000000000]], [[110000110110000000000000000000010100100010000000]], [[000010000000000000110110000000000100010010000000]], [[000000000000000000000000000000000000000000000000]], [[010110010110100110110110010000000100000110110110]], [[000000000000000000000110000000000110000000000000]], [[000000000000000000000000000000000000000000000000]], [[010100010110110000000000000000110000000010000000]], [[110110000000000000110000110110100000000010000000]], [[000000000000000000000000000000000000000000000000]], [[000100011111000100011111000100011111000100011111]], [[000000000000100100100100011011011011111111111111]], [[000000000000000000000000000000000000000000000000]], [[000100011111000100011111000100011111000100011111]], [[000000000000100100100100011011011011111111111111]], [[100100100100100100100100100100100100100100100100]], [[000000110100110110000010000011110000000000011000]], [[000000000100000000000010000011000110000000001000]], [[000000000000000000000000000000000000000000000000]], [[010000100100000000000000000100000000010010110000]], [[000000000000000000000000000000110110110110110000]], [[000000000000000000000000000000000000000000000000]], [[110110110110110110000000110110110110110110110110]], [[000000000000000000000110000000000000000000000000]], [[000000000000000000000000000000000000000000000000]], [[000000000000110110000110010000000000000000010010]], [[000010000000000000000000000000000000000000000000]], [[000000000000000000000000000000000000000000000000]], [[110110110110110110110000110110110110000000000000]], [[000000000000000000000110000000000000000000000000]], [[000000000000000000000000000000000000000000000000]], [[110110110110110110110000110000000000000000010000]], [[000000000000000000000000100000000000000110000110]], [[000000000000000000000000000000000000000000000000]], } } --Cut for 3x3 chars per a character. (1 character is 6x9 pixels) local fonts = {} do local firstFont = {} local char = 0 local height = #rawFont[1] local lenght = #rawFont[1][1] for i=1,height,3 do for j=1,lenght,3 do local thisChar = string.char(char) local temp = {} temp[1] = rawFont[1][i]:sub(j,j+2) temp[2] = rawFont[1][i+1]:sub(j,j+2) temp[3] = rawFont[1][i+2]:sub(j,j+2) local temp2 = {} temp2[1] = rawFont[2][i]:sub(j,j+2) temp2[2] = rawFont[2][i+1]:sub(j,j+2) temp2[3] = rawFont[2][i+2]:sub(j,j+2) firstFont[thisChar] = {temp,temp2} char = char + 1 end end fonts[1] = firstFont local inverter = {["0"]="1",["1"]="0"} --:gsub("[01]",inverter) for f=2,3 do --automagicly make bigger fonts using firstFont and fonts[f-1]. local nextFont = {} local lastFont = fonts[f-1] for char=0,255 do local thisChar = string.char(char) local temp = {} local temp2 = {} local templateChar = lastFont[thisChar][1] local templateBack = lastFont[thisChar][2] for i=1,#templateChar do local line1,line2,line3,back1,back2,back3={},{},{},{},{},{} for j=1,#templateChar[1] do local currentChar = firstFont[templateChar[i]:sub(j,j)][1] table.insert(line1,currentChar[1]) table.insert(line2,currentChar[2]) table.insert(line3,currentChar[3]) local currentBack = firstFont[templateChar[i]:sub(j,j)][2] if templateBack[i]:sub(j,j) =="1" then table.insert(back1,(currentBack[1]:gsub("[01]",inverter))) table.insert(back2,(currentBack[2]:gsub("[01]",inverter))) table.insert(back3,(currentBack[3]:gsub("[01]",inverter))) else table.insert(back1,currentBack[1]) table.insert(back2,currentBack[2]) table.insert(back3,currentBack[3]) end end table.insert(temp,table.concat(line1)) table.insert(temp,table.concat(line2)) table.insert(temp,table.concat(line3)) table.insert(temp2,table.concat(back1)) table.insert(temp2,table.concat(back2)) table.insert(temp2,table.concat(back3)) end nextFont[thisChar] = {temp,temp2} end fonts[f] = nextFont end end --Make a big font of big font local tHex = { [ colors.white ] = "0", [ colors.orange ] = "1", [ colors.magenta ] = "2", [ colors.lightBlue ] = "3", [ colors.yellow ] = "4", [ colors.lime ] = "5", [ colors.pink ] = "6", [ colors.gray ] = "7", [ colors.lightGray ] = "8", [ colors.cyan ] = "9", [ colors.purple ] = "a", [ colors.blue ] = "b", [ colors.brown ] = "c", [ colors.green ] = "d", [ colors.red ] = "e", [ colors.black ] = "f", } local function stamp(tTerminal,tData,nX,nY) local oX,oY = tTerminal.getSize() local cX,cY = #tData[1][1],#tData[1] nX = nX or math.floor((oX-cX)/2)+1 nY = nY or math.floor((oY-cY)/2)+1 for i=1,cY do if i > 1 and nY+i-1 > oY then term.scroll(1) nY = nY-1 end tTerminal.setCursorPos(nX,nY+i-1) tTerminal.blit(tData[1][i],tData[2][i],tData[3][i]) end end local function makeText(nSize,sString,nFC,nBC,bBlit) if not type(sString) == "string" then error("Not a String") end local cFC = type(nFC)=="string" and nFC:sub(1,1) or tHex[nFC] or error("Wrong Front Color") local cBC = type(nBC)=="string" and nBC:sub(1,1) or tHex[nBC] or error("Wrong Back Color") local font = fonts[nSize] or error("Wrong font size selected") local input = {} for i in sString:gmatch('.') do table.insert(input,i) end local tText = {} local height = #font[input[1]][1] for nLine=1,height do local outLine={} for i=1,#input do outLine[i] = (font[input[i]] and font[input[i]][1][nLine] or "") end tText[nLine] = table.concat(outLine) end local tFront = {} local tBack = {} local tFrontSub = {["0"]=cFC,["1"]=cBC} local tBackSub = {["0"]=cBC,["1"]=cFC} for nLine=1,height do local front={} local back={} for i=1,#input do local template = (font[input[i]] and font[input[i]][2][nLine] or "") front[i] = template:gsub("[01]",bBlit and {["0"]=nFC:sub(i,i),["1"]=nBC:sub(i,i)} or tFrontSub) back[i] = template:gsub("[01]",bBlit and {["0"]=nBC:sub(i,i),["1"]=nFC:sub(i,i)} or tBackSub) end tFront[nLine] = table.concat(front) tBack[nLine] = table.concat(back) end return {tText,tFront,tBack} end function bigWrite(sString) stamp(term,makeText(1,sString,term.getTextColor(),term.getBackgroundColor()),term.getCursorPos()) local x,y = term.getCursorPos() term.setCursorPos(x,y-2) end function bigBlit(sString,sFront,sBack) stamp(term,makeText(1,sString,sFront,sBack,true),term.getCursorPos()) local x,y = term.getCursorPos() term.setCursorPos(x,y-2) end function bigPrint(sString) stamp(term,makeText(1,sString,term.getTextColor(),term.getBackgroundColor()),term.getCursorPos()) print() end function hugeWrite(sString) stamp(term,makeText(2,sString,term.getTextColor(),term.getBackgroundColor()),term.getCursorPos()) local x,y = term.getCursorPos() term.setCursorPos(x,y-8) end function hugeBlit(sString,sFront,sBack) stamp(term,makeText(2,sString,sFront,sBack,true),term.getCursorPos()) local x,y = term.getCursorPos() term.setCursorPos(x,y-8) end function hugePrint(sString) stamp(term,makeText(2,sString,term.getTextColor(),term.getBackgroundColor()),term.getCursorPos()) print() end function writeOn(tTerminal,nSize,sString,nX,nY) stamp(tTerminal,makeText(nSize,sString,tTerminal.getTextColor(),tTerminal.getBackgroundColor()),nX,nY) end function blitOn(tTerminal,nSize,sString,sFront,sBack,nX,nY) stamp(tTerminal,makeText(nSize,sString,sFront,sBack,true),nX,nY) end function makeBlittleText(nSize,sString,nFC,nBC) local out = makeText(nSize,sString,nFC,nBC) out.height=#out[1] out.width=#out[1][1] return out end
mit
masoudre11/RaHabot
plugins/slap.lua
11
4313
local doc = [[ /slap [target] Give someone a good slap (or worse) through reply or specification of a target. ]] local triggers = { '^/slap[@'..bot.username..']*' } local slaps = { '$victim was shot by $victor.', '$victim was pricked to death.', '$victim walked into a cactus while trying to escape $victor.', '$victim drowned.', '$victim drowned whilst trying to escape $victor.', '$victim blew up.', '$victim was blown up by $victor.', '$victim hit the ground too hard.', '$victim fell from a high place.', '$victim fell off a ladder.', '$victim fell into a patch of cacti.', '$victim was doomed to fall by $victor.', '$victim was blown from a high place by $victor.', '$victim was squashed by a falling anvil.', '$victim went up in flames.', '$victim burned to death.', '$victim was burnt to a crisp whilst fighting $victor.', '$victim walked into a fire whilst fighting $victor.', '$victim tried to swim in lava.', '$victim tried to swim in lava while trying to escape $victor.', '$victim was struck by lightning.', '$victim was slain by $victor.', '$victim got finished off by $victor.', '$victim was killed by magic.', '$victim was killed by $victor using magic.', '$victim starved to death.', '$victim suffocated in a wall.', '$victim fell out of the world.', '$victim was knocked into the void by $victor.', '$victim withered away.', '$victim was pummeled by $victor.', '$victim was fragged by $victor.', '$victim was desynchronized.', '$victim was wasted.', '$victim was busted.', '$victim\'s bones are scraped clean by the desolate wind.', '$victim has died of dysentery.', '$victim fainted.', '$victim is out of usable Pokemon! $victim whited out!', '$victim is out of usable Pokemon! $victim blacked out!', '$victim whited out!', '$victim blacked out!', '$victim says goodbye to this cruel world.', '$victim got rekt.', '$victim was sawn in half by $victor.', '$victim died. I blame $victor.', '$victim was axe-murdered by $victor.', '$victim\'s melon was split by $victor.', '$victim was slice and diced by $victor.', '$victim was split from crotch to sternum by $victor.', '$victim\'s death put another notch in $victor\'s axe.', '$victim died impossibly!', '$victim died from $victor\'s mysterious tropical disease.', '$victim escaped infection by dying.', '$victim played hot-potato with a grenade.', '$victim was knifed by $victor.', '$victim fell on his sword.', '$victim ate a grenade.', '$victim practiced being $victor\'s clay pigeon.', '$victim is what\'s for dinner!', '$victim was terminated by $victor.', '$victim was shot before being thrown out of a plane.', '$victim was not invincible.', '$victim has encountered an error.', '$victim died and reincarnated as a goat.', '$victor threw $victim off a building.', '$victim is sleeping with the fishes.', '$victim got a premature burial.', '$victor replaced all of $victim\'s music with Nickelback.', '$victor spammed $victim\'s email.', '$victor made $victim a knuckle sandwich.', '$victor slapped $victim with pure nothing.', '$victor hit $victim with a small, interstellar spaceship.', '$victim was quickscoped by $victor.', '$victor put $victim in check-mate.', '$victor RSA-encrypted $victim and deleted the private key.', '$victor put $victim in the friendzone.', '$victor slaps $victim with a DMCA takedown request!', '$victim became a corpse blanket for $victor.', 'Death is when the monsters get you. Death comes for $victim.', 'Cowards die many times before their death. $victim never tasted death but once.' } local action = function(msg) local nicks = load_data('nicknames.json') local victim = msg.text:input() if msg.reply_to_message then if nicks[tostring(msg.reply_to_message.from.id)] then victim = nicks[tostring(msg.reply_to_message.from.id)] else victim = msg.reply_to_message.from.first_name end end local victor = msg.from.first_name if nicks[msg.from.id_str] then victor = nicks[msg.from.id_str] end if not victim then victim = victor victor = bot.first_name end local message = slaps[math.random(#slaps)] message = message:gsub('$victim', victim) message = message:gsub('$victor', victor) sendMessage(msg.chat.id, message) end return { action = action, triggers = triggers, doc = doc }
gpl-2.0
pouya-joker/Telecat
plugins/ingroup.lua
7
50617
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group Join link : "..settings.antijoin.."\nLock group Fosh : "..settings.antifosh.."\nLock group English : "..settings.lock_egnlish.."\nLock group Tag : "..settings.antitag.."\nLock group leave : "..settings.lock_leave.."\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators 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 get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators 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_namemod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" 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_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" 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 local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators 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_membermod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local group_join_lock = data[tostring(target)]['settings']['antijoin'] if group_join_lock == 'yes' then return 'Join by link is already locked' else data[tostring(target)]['settings']['antijoin'] = 'yes' save_data(_config.moderation.data, data) return 'Join by link has been locked' end end local function unlock_group_join(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_join_lock = data[tostring(target)]['settings']['antijoin'] if group_join_lock == 'no' then return 'Join by link is already unlocked' else data[tostring(target)]['settings']['antijoin'] = 'no' save_data(_config.moderation.data, data) return 'Join by link has been unlocked' end end local group_link_lock = data[tostring(target)]['settings']['antilink'] if group_link_lock == 'yes' then return 'Link is already locked' else data[tostring(target)]['settings']['antilink'] = 'yes' save_data(_config.moderation.data, data) return 'Link has been locked' end end local function unlock_group_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['antilink'] if group_link_lock == 'no' then return 'Link is already unlocked' else data[tostring(target)]['settings']['antilink'] = 'no' save_data(_config.moderation.data, data) return 'Link has been unlocked' end end local function lock_group_fosh(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_fosh_lock = data[tostring(target)]['settings']['antifosh'] if group_fosh_lock == 'yes' then return 'fosh is already locked' else data[tostring(target)]['settings']['antifosh'] = 'yes' save_data(_config.moderation.data, data) return 'fosh has been locked' end end local function unlock_group_fosh(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_fosh_lock = data[tostring(target)]['settings']['antifosh'] if group_fosh_lock == 'no' then return 'fosh is already unlocked' else data[tostring(target)]['settings']['antifosh'] = 'no' save_data(_config.moderation.data, data) return 'fosh has been unlocked' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['antitag'] if group_tag_lock == 'yes' then return 'tag is already locked' else data[tostring(target)]['settings']['antitag'] = 'yes' save_data(_config.moderation.data, data) return 'tag has been locked' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['antitag'] if group_tag_lock == 'no' then return 'tag is already unlocked' else data[tostring(target)]['settings']['antitag'] = 'no' save_data(_config.moderation.data, data) return 'tag has been unlocked' end end local function lock_group_english(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_english_lock = data[tostring(target)]['settings']['lock_english'] if group_english_lock == 'yes' then return 'English is already locked' else data[tostring(target)]['settings']['lock_english'] = 'yes' save_data(_config.moderation.data, data) return 'English has been locked' end end local function unlock_group_english(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_english_lock = data[tostring(target)]['settings']['lock_english'] if group_english_lock == 'no' then return 'english is already unlocked' else data[tostring(target)]['settings']['lock_english'] = 'no' save_data(_config.moderation.data, data) return 'English has been unlocked' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators 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 set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message 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 help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(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(v.id, result.id) 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 user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_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 savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'link' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link ") return lock_group_link(msg, data, target) end if matches[2] == 'fosh' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fosh ") return lock_group_fosh(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ") return lock_group_tag(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked English ") return lock_group_english(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end if matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Joining by link ") return lock_group_join(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'link' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link ") return unlock_group_link(msg, data, target) end if matches[2] == 'fosh' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fosh ") return unlock_group_fosh(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag ") return unlock_group_tag(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english ") return unlock_group_english(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end if matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Joining by link ") return unlock_group_join(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'linkpv' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, "Group link:\n"..group_link) end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() 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 if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](linkpv)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Unknown8765/SpeedBot
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
ingran/balzac
custom_feeds/teltonika_luci/applications/luci-ahcp/luasrc/model/cbi/ahcp.lua
1
3875
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: init.lua 5764 2010-03-08 19:05:34Z jow $ ]]-- m = Map("ahcpd", translate("AHCP Server"), translate("AHCP is an autoconfiguration protocol for IPv6 and dual-stack IPv6/IPv4 networks designed to be used in place of router discovery and DHCP on networks where it is difficult or impossible to configure a server within every link-layer broadcast domain, for example mobile ad-hoc networks.")) m:section(SimpleSection).template = "ahcp_status" s = m:section(TypedSection, "ahcpd") s:tab("general", translate("General Setup")) s:tab("advanced", translate("Advanced Settings")) s.addremove = false s.anonymous = true mode = s:taboption("general", ListValue, "mode", translate("Operation mode")) mode:value("server", translate("Server")) mode:value("forwarder", translate("Forwarder")) net = s:taboption("general", Value, "interface", translate("Served interfaces")) net.template = "cbi/network_netlist" net.widget = "checkbox" net.nocreate = true function net.cfgvalue(self, section) return m.uci:get("ahcpd", section, "interface") end pfx = s:taboption("general", DynamicList, "prefix", translate("Announced prefixes"), translate("Specifies the announced IPv4 and IPv6 network prefixes in CIDR notation")) pfx.optional = true pfx.datatype = "ipaddr" pfx:depends("mode", "server") nss = s:taboption("general", DynamicList, "name_server", translate("Announced DNS servers"), translate("Specifies the announced IPv4 and IPv6 name servers")) nss.optional = true nss.datatype = "ipaddr" nss:depends("mode", "server") ntp = s:taboption("general", DynamicList, "ntp_server", translate("Announced NTP servers"), translate("Specifies the announced IPv4 and IPv6 NTP servers")) ntp.optional = true ntp.datatype = "ipaddr" ntp:depends("mode", "server") mca = s:taboption("general", Value, "multicast_address", translate("Multicast address")) mca.optional = true mca.placeholder = "ff02::cca6:c0f9:e182:5359" mca.datatype = "ip6addr" port = s:taboption("general", Value, "port", translate("Port")) port.optional = true port.placeholder = 5359 port.datatype = "port" fam = s:taboption("general", ListValue, "_family", translate("Protocol family")) fam:value("", translate("IPv4 and IPv6")) fam:value("ipv4", translate("IPv4 only")) fam:value("ipv6", translate("IPv6 only")) function fam.cfgvalue(self, section) local v4 = m.uci:get_bool("ahcpd", section, "ipv4_only") local v6 = m.uci:get_bool("ahcpd", section, "ipv6_only") if v4 then return "ipv4" elseif v6 then return "ipv6" end return "" end function fam.write(self, section, value) if value == "ipv4" then m.uci:set("ahcpd", section, "ipv4_only", "true") m.uci:delete("ahcpd", section, "ipv6_only") elseif value == "ipv6" then m.uci:set("ahcpd", section, "ipv6_only", "true") m.uci:delete("ahcpd", section, "ipv4_only") end end function fam.remove(self, section) m.uci:delete("ahcpd", section, "ipv4_only") m.uci:delete("ahcpd", section, "ipv6_only") end ltime = s:taboption("general", Value, "lease_time", translate("Lease validity time")) ltime.optional = true ltime.placeholder = 3666 ltime.datatype = "uinteger" ld = s:taboption("advanced", Value, "lease_dir", translate("Lease directory")) ld.datatype = "directory" ld.placeholder = "/var/lib/leases" id = s:taboption("advanced", Value, "id_file", translate("Unique ID file")) --id.datatype = "file" id.placeholder = "/var/lib/ahcpd-unique-id" log = s:taboption("advanced", Value, "log_file", translate("Log file")) --log.datatype = "file" log.placeholder = "/var/log/ahcpd.log" return m
gpl-2.0
ingran/balzac
custom_feeds/teltonika_luci/applications/luci-input-output-tlt/luasrc/tools/input-output.lua
1
6089
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: firewall.lua 8314 2012-02-19 20:22:17Z jow $ ]]-- module("luci.tools.input-output", package.seeall) local ut = require "luci.util" local ip = require "luci.ip" local nx = require "nixio" local translate, translatef = luci.i18n.translate, luci.i18n.translatef local function tr(...) return tostring(translate(...)) end function fmt_neg(x) if type(x) == "string" then local v, neg = x:gsub("^ *! *", "") if neg > 0 then return v, "%s " % tr("not") else return x, "" end end return x, "" end function fmt_mac(x) if x and #x > 0 then local m, n local l = { tr("MAC"), " " } for m in ut.imatch(x) do m, n = fmt_neg(m) l[#l+1] = "<var>%s%s</var>" %{ n, m } l[#l+1] = ", " end if #l > 1 then l[#l] = nil if #l > 3 then l[1] = tr("MACs") end return table.concat(l, "") end end end function fmt_port(x, d) if x and #x > 0 then local p, n local l = { tr("port"), " " } for p in ut.imatch(x) do p, n = fmt_neg(p) local a, b = p:match("(%d+)%D+(%d+)") if a and b then l[1] = tr("ports") l[#l+1] = "<var>%s%d-%d</var>" %{ n, a, b } else l[#l+1] = "<var>%s%d</var>" %{ n, p } end l[#l+1] = ", " end if #l > 1 then l[#l] = nil if #l > 3 then l[1] = tr("ports") end return table.concat(l, "") end end return d and "<var>%s</var>" % d end function fmt_ip(x, d) if x and #x > 0 then local l = { tr("IP"), " " } local v, a, n for v in ut.imatch(x) do v, n = fmt_neg(v) a, m = v:match("(%S+)/(%d+%.%S+)") a = a or v a = a:match(":") and ip.IPv6(a, m) or ip.IPv4(a, m) if a and (a:is6() and a:prefix() < 128 or a:prefix() < 32) then l[1] = tr("IP range") l[#l+1] = "<var title='%s - %s'>%s%s</var>" %{ a:minhost():string(), a:maxhost():string(), n, a:string() } else l[#l+1] = "<var>%s%s</var>" %{ n, a and a:string() or v } end l[#l+1] = ", " end if #l > 1 then l[#l] = nil if #l > 3 then l[1] = tr("IPs") end return table.concat(l, "") end end return d and "<var>%s</var>" % d end function fmt_zone(x, d) if x == "*" then return "<var>%s</var>" % tr("any zone") elseif x and #x > 0 then return "<var>%s</var>" % x elseif d then return "<var>%s</var>" % d end end function fmt_icmp_type(x) if x and #x > 0 then local t, v, n local l = { tr("type"), " " } for v in ut.imatch(x) do v, n = fmt_neg(v) l[#l+1] = "<var>%s%s</var>" %{ n, v } l[#l+1] = ", " end if #l > 1 then l[#l] = nil if #l > 3 then l[1] = tr("types") end return table.concat(l, "") end end end function fmt_proto(x, icmp_types) if x and #x > 0 then local v, n local l = { } local t = fmt_icmp_type(icmp_types) for v in ut.imatch(x) do v, n = fmt_neg(v) if v == "tcpudp" then l[#l+1] = "TCP" l[#l+1] = "UDP" l[#l+1] = ", " elseif v ~= "all" then local p = nx.getproto(v) if p then -- ICMP if (p.proto == 1 or p.proto == 58) and t then l[#l+1] = translatef( "%s%s with %s", n, p.aliases[1] or p.name, t ) else l[#l+1] = "%s%s" %{ n, p.aliases[1] or p.name } end l[#l+1] = ", " end end end if #l > 0 then l[#l] = nil return table.concat(l, "") end end end function fmt_limit(limit, burst) burst = tonumber(burst) if limit and #limit > 0 then local l, u = limit:match("(%d+)/(%w+)") l = tonumber(l or limit) u = u or "second" if l then if u:match("^s") then u = tr("second") elseif u:match("^m") then u = tr("minute") elseif u:match("^h") then u = tr("hour") elseif u:match("^d") then u = tr("day") end if burst and burst > 0 then return translatef("<var>%d</var> pkts. per <var>%s</var>, \ burst <var>%d</var> pkts.", l, u, burst) else return translatef("<var>%d</var> pkts. per <var>%s</var>", l, u) end end end end function fmt_target(x, dest) if dest and #dest > 0 then if x == "ACCEPT" then return tr("Accept forward") elseif x == "REJECT" then return tr("Refuse forward") elseif x == "NOTRACK" then return tr("Do not track forward") else --if x == "DROP" then return tr("Discard forward") end else if x == "ACCEPT" then return tr("Accept input") elseif x == "REJECT" then return tr("Refuse input") elseif x == "NOTRACK" then return tr("Do not track input") else --if x == "DROP" then return tr("Discard input") end end end function opt_enabled(s, t, ...) if t == luci.cbi.Button then local o = s:option(t, "__enabled") function o.render(self, section) if self.map:get(section, "enabled") == "1" then self.title = tr("Rule is enabled") self.inputtitle = tr("Disable") self.inputstyle = "reset" else self.title = tr("Rule is disabled") self.inputtitle = tr("Enable") self.inputstyle = "apply" end t.render(self, section) end function o.write(self, section, value) if self.map:get(section, "enabled") == "1" then self.map:set(section, "enabled", "0") else self.map:set(section, "enabled", "1") end end return o else local o = s:option(t, "enabled", ...) o.rmempty = false o.default = o.enabled return o end end function opt_name(s, t, ...) local o = s:option(t, "name", ...) function o.cfgvalue(self, section) return self.map:get(section, "name") or self.map:get(section, "_name") or "-" end function o.write(self, section, value) if value ~= "-" then self.map:set(section, "name", value) self.map:del(section, "_name") else self:remove(section) end end function o.remove(self, section) self.map:del(section, "name") self.map:del(section, "_name") end return o end
gpl-2.0
AngelBaltar/RenegadeKlingon
Utils/Advanced-Tiled-Loader/external/crc32lua.lua
13
3282
--[[ dmlib.crc32 CRC-32 checksum implemented entirely in Lua. This is similar to [1-2]. References [1] http://www.axlradius.com/freestuff/CRC32.java [2] http://www.gamedev.net/reference/articles/article1941.asp [3] http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/CRC32.html [4] http://www.dsource.org/projects/tango/docs/current/tango.io.digest.Crc32.html [5] http://pydoc.org/1.5.2/zlib.html#-crc32 [6] http://www.python.org/doc/2.5.2/lib/module-binascii.html (c) 2008 David Manura. Licensed under the same terms as Lua (MIT). --]] local M = {} local type = type local require = require local setmetatable = setmetatable local _G = _G local bxor = require ( TILED_LOADER_PATH .. "external.numberlua" ) . bxor --[[NATIVE_BITOPS local bxor = bit.bxor local rshift = bit.rshift local bnot = bit.bnot --]] -- CRC-32-IEEE 802.3 (V.42) local POLY = 0xEDB88320 local function memoize(f) local mt = {} local t = setmetatable({}, mt) function mt:__index(k) local v = f(k); t[k] = v return v end return t end local function get(i) local crc = i for j=1,8 do local b = crc % 2 crc = (crc - b) / 2 if b == 1 then crc = bxor(crc, POLY) end end return crc end local crc_table = memoize(get) local function crc32_byte(byte, crc) crc = 0xffffffff - (crc or 0) local v1 = (crc - crc % 256) / 256 local v2 = crc_table[bxor(crc % 256, byte)] return 0xffffffff - bxor(v1, v2) end --[[NATIVE_BITOPS local function crc32_byte(byte, crc) crc = bnot(crc or 0) local v1 = rshift(crc, 8) local v2 = crc_table[bxor(crc % 256, byte)] return bnot(bxor(v1, v2)) end --]] M.crc32_byte = crc32_byte local function crc32_string(s, crc) crc = crc or 0 for i=1,#s do crc = crc32_byte(s:byte(i), crc) end return crc end M.crc32_string = crc32_string local function crc32(s, crc) if type(s) == 'string' then return crc32_string(s, crc) else return crc32_byte(s, crc) end end M.crc32 = crc32 --DEBUG: --local s = "test123" --local crc = 0xffffffff --for i=1,#s do -- local byte = s:sub(i,i):byte() -- crc = crc32(crc, byte) --end --crc = 0xffffffff - crc --print(string.format("%08X", crc)) return M --[[ LICENSE Copyright (C) 2008, David Manura. 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. (end license) --]]
gpl-3.0
MocoNinja/LinuxConfs
Archlabs/.config/awesome/vicious/widgets/gmail.lua
1
2031
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Adrian C. <anrxc@sysphere.org> --------------------------------------------------- -- {{{ Grab environment local type = type local tonumber = tonumber local io = { popen = io.popen } local setmetatable = setmetatable local helpers = require("vicious.helpers") local string = { match = string.match } -- }}} -- Gmail: provides count of new and subject of last e-mail on Gmail -- vicious.widgets.gmail local gmail = {} -- {{{ Variable definitions local rss = { inbox = "https://mail.google.com/mail/feed/atom", unread = "https://mail.google.com/mail/feed/atom/unread", --labelname = "https://mail.google.com/mail/feed/atom/labelname", } -- Default is just Inbox local feed = rss.inbox local mail = { ["{count}"] = 0, ["{subject}"] = "N/A" } -- }}} -- {{{ Gmail widget type local function worker(format, warg) -- Get info from the Gmail atom feed local f = io.popen("curl --connect-timeout 1 -m 3 -fsn " .. feed) -- Could be huge don't read it all at once, info we are after is at the top local xml = f:read(2000) if xml ~= nil then return mail end mail["{count}"] = -- Count comes before messages and matches at least 0 tonumber(string.match(xml, "<fullcount>([%d]+)</fullcount>")) or mail["{count}"] -- Find subject tag local title = string.match(xml, "<entry>.-<title>(.-)</title>") if title ~= nil then -- Check if we should scroll, or maybe truncate if warg then if type(warg) == "table" then title = helpers.scroll(title, warg[1], warg[2]) else title = helpers.truncate(title, warg) end end -- Spam sanitize the subject and store mail["{subject}"] = helpers.escape(title) end f:close() return mail end -- }}} return setmetatable(gmail, { __call = function(_, ...) return worker(...) end })
gpl-3.0
liruqi/bigfoot
Interface/AddOns/AngryKeystones/Persist.lua
1
10930
if GetBuildInfo() ~= "7.2.0" then return end local ADDON, Addon = ... local Mod = Addon:NewModule('Persist') local challengeMapID local function LoadPersist() local function IsInCompletedInstance() return select(10, C_Scenario.GetInfo()) == LE_SCENARIO_TYPE_CHALLENGE_MODE and C_ChallengeMode.GetCompletionInfo() ~= 0 and select(3, C_Scenario.GetInfo()) == 0 and challengeMapID end ScenarioTimer_OnUpdate_Old = ScenarioTimer_OnUpdate function ScenarioTimer_OnUpdate(self, elapsed) if self.block.timerID ~= -1 then self.timeSinceBase = self.timeSinceBase + elapsed; end self.updateFunc(self.block, floor(self.baseTime + self.timeSinceBase)); end ScenarioTimerFrame:SetScript("OnUpdate", ScenarioTimer_OnUpdate) ScenarioTimer_Start_Old = ScenarioTimer_Start function ScenarioTimer_Start(block, updateFunc) if block.timerID == -1 then local mapID, level, timeElapsed, onTime, keystoneUpgradeLevels = C_ChallengeMode.GetCompletionInfo() ScenarioTimerFrame.baseTime = floor(timeElapsed/1000); else local _, elapsedTime = GetWorldElapsedTime(block.timerID); ScenarioTimerFrame.baseTime = elapsedTime; challengeMapID = C_ChallengeMode.GetActiveChallengeMapID() end ScenarioTimerFrame.timeSinceBase = 0; ScenarioTimerFrame.block = block; ScenarioTimerFrame.updateFunc = updateFunc; ScenarioTimerFrame:Show(); end ScenarioTimer_Stop_Old = ScenarioTimer_Stop function ScenarioTimer_Stop(...) if IsInCompletedInstance() then local mapID, level, timeElapsed, onTime, keystoneUpgradeLevels = C_ChallengeMode.GetCompletionInfo() local name, _, timeLimit = C_ChallengeMode.GetMapInfo(challengeMapID) Scenario_ChallengeMode_ShowBlock(-1, floor(timeElapsed/1000), timeLimit) else ScenarioTimer_Stop_Old(...) end end SCENARIO_CONTENT_TRACKER_MODULE_StaticReanchor_Old = SCENARIO_CONTENT_TRACKER_MODULE.StaticReanchor function SCENARIO_CONTENT_TRACKER_MODULE:StaticReanchor() local inCompletedInstance = IsInCompletedInstance() local scenarioName, currentStage, numStages, flags, _, _, completed, xp, money = C_Scenario.GetInfo(); local rewardsFrame = ObjectiveTrackerScenarioRewardsFrame; if ( numStages == 0 and not inCompletedInstance ) then ScenarioBlocksFrame_Hide(); return; end if ( ScenarioBlocksFrame:IsShown() ) then ObjectiveTracker_AddBlock(SCENARIO_TRACKER_MODULE.BlocksFrame); end end SCENARIO_CONTENT_TRACKER_MODULE_Update_Old = SCENARIO_CONTENT_TRACKER_MODULE.Update function SCENARIO_CONTENT_TRACKER_MODULE:Update() local inCompletedInstance = IsInCompletedInstance() local scenarioName, currentStage, numStages, flags, _, _, _, xp, money, scenarioType = C_Scenario.GetInfo(); local rewardsFrame = ObjectiveTrackerScenarioRewardsFrame; if ( numStages == 0 and not inCompletedInstance ) then ScenarioBlocksFrame_Hide(); return; end local BlocksFrame = SCENARIO_TRACKER_MODULE.BlocksFrame; local objectiveBlock = SCENARIO_TRACKER_MODULE:GetBlock(); local stageBlock = ScenarioStageBlock; -- if sliding, ignore updates unless the stage changed if ( BlocksFrame.slidingAction ) then if ( BlocksFrame.currentStage == currentStage ) then ObjectiveTracker_AddBlock(BlocksFrame); BlocksFrame:Show(); return; else ObjectiveTracker_EndSlideBlock(BlocksFrame); end end BlocksFrame.maxHeight = SCENARIO_CONTENT_TRACKER_MODULE.BlocksFrame.maxHeight; BlocksFrame.currentBlock = nil; BlocksFrame.contentsHeight = 0; SCENARIO_TRACKER_MODULE.contentsHeight = 0; local stageName, stageDescription, numCriteria, _, _, _, numSpells, spellInfo, weightedProgress = C_Scenario.GetStepInfo(); local inChallengeMode = (scenarioType == LE_SCENARIO_TYPE_CHALLENGE_MODE); local inProvingGrounds = (scenarioType == LE_SCENARIO_TYPE_PROVING_GROUNDS); local dungeonDisplay = (scenarioType == LE_SCENARIO_TYPE_USE_DUNGEON_DISPLAY); local scenariocompleted = currentStage > numStages; if ( scenariocompleted ) then ObjectiveTracker_AddBlock(stageBlock); ScenarioBlocksFrame_SetupStageBlock(scenariocompleted); stageBlock:Show(); elseif ( inChallengeMode or inCompletedInstance ) then if ( ScenarioChallengeModeBlock.timerID or inCompletedInstance ) then ObjectiveTracker_AddBlock(ScenarioChallengeModeBlock); end stageBlock:Hide(); elseif ( ScenarioProvingGroundsBlock.timerID ) then ObjectiveTracker_AddBlock(ScenarioProvingGroundsBlock); stageBlock:Hide(); else -- add the stage block ObjectiveTracker_AddBlock(stageBlock); stageBlock:Show(); -- update if stage changed if ( BlocksFrame.currentStage ~= currentStage or BlocksFrame.scenarioName ~= scenarioName ) then SCENARIO_TRACKER_MODULE:FreeUnusedLines(objectiveBlock); if ( bit.band(flags, SCENARIO_FLAG_SUPRESS_STAGE_TEXT) == SCENARIO_FLAG_SUPRESS_STAGE_TEXT ) then stageBlock.Stage:SetText(stageName); stageBlock.Stage:SetSize( 172, 36 ); stageBlock.Stage:SetPoint("TOPLEFT", 15, -18); stageBlock.FinalBG:Hide(); stageBlock.Name:SetText(""); else if ( currentStage == numStages ) then stageBlock.Stage:SetText(SCENARIO_STAGE_FINAL); stageBlock.FinalBG:Show(); else stageBlock.Stage:SetFormattedText(SCENARIO_STAGE, currentStage); stageBlock.FinalBG:Hide(); end stageBlock.Stage:SetSize( 172, 18 ); stageBlock.Name:SetText(stageName); if ( stageBlock.Name:GetStringWidth() > stageBlock.Name:GetWrappedWidth() ) then stageBlock.Stage:SetPoint("TOPLEFT", 15, -10); else stageBlock.Stage:SetPoint("TOPLEFT", 15, -18); end end if (not stageBlock.appliedAlready) then -- Ugly hack to get around :IsTruncated failing if used during load C_Timer.After(1, function() stageBlock.Stage:ApplyFontObjects(); end); stageBlock.appliedAlready = true; end ScenarioStage_CustomizeBlock(stageBlock, scenarioType); end end BlocksFrame.scenarioName = scenarioName; BlocksFrame.currentStage = currentStage; if ( not ScenarioProvingGroundsBlock.timerID and not scenariocompleted ) then if (weightedProgress) then self:UpdateWeightedProgressCriteria(stageDescription, stageBlock, objectiveBlock, BlocksFrame); else self:UpdateCriteria(numCriteria, objectiveBlock); self:AddSpells(objectiveBlock, spellInfo); -- add the objective block objectiveBlock:SetHeight(objectiveBlock.height); if ( ObjectiveTracker_AddBlock(objectiveBlock) ) then if ( not BlocksFrame.slidingAction ) then objectiveBlock:Show(); end else objectiveBlock:Hide(); stageBlock:Hide(); end end end ScenarioSpellButtons_UpdateCooldowns(); -- add the scenario block if ( BlocksFrame.currentBlock ) then BlocksFrame.height = BlocksFrame.contentsHeight + 1; BlocksFrame:SetHeight(BlocksFrame.contentsHeight + 1); ObjectiveTracker_AddBlock(BlocksFrame); BlocksFrame:Show(); if ( OBJECTIVE_TRACKER_UPDATE_REASON == OBJECTIVE_TRACKER_UPDATE_SCENARIO_NEW_STAGE and not inChallengeMode ) then if ( ObjectiveTrackerFrame:IsVisible() ) then if ( currentStage == 1 ) then ScenarioBlocksFrame_SlideIn(); else ScenarioBlocksFrame_SetupStageBlock(scenariocompleted); if ( not scenariocompleted ) then ScenarioBlocksFrame_SlideOut(); end end end LevelUpDisplay_PlayScenario(); -- play sound if not the first stage if ( currentStage > 1 and currentStage <= numStages ) then PlaySound(31754); end elseif ( OBJECTIVE_TRACKER_UPDATE_REASON == OBJECTIVE_TRACKER_UPDATE_SCENARIO_SPELLS ) then ScenarioSpells_SlideIn(objectiveBlock); end -- header if ( inChallengeMode ) then SCENARIO_CONTENT_TRACKER_MODULE.Header.Text:SetText(scenarioName); elseif ( inProvingGrounds or ScenarioProvingGroundsBlock.timerID ) then SCENARIO_CONTENT_TRACKER_MODULE.Header.Text:SetText(TRACKER_HEADER_PROVINGGROUNDS); elseif( dungeonDisplay ) then SCENARIO_CONTENT_TRACKER_MODULE.Header.Text:SetText(TRACKER_HEADER_DUNGEON); else SCENARIO_CONTENT_TRACKER_MODULE.Header.Text:SetText(TRACKER_HEADER_SCENARIO); end else ScenarioBlocksFrame_Hide(); end end SCENARIO_CONTENT_TRACKER_MODULE_UpdateCriteria_Old = SCENARIO_CONTENT_TRACKER_MODULE.UpdateCriteria function SCENARIO_CONTENT_TRACKER_MODULE:UpdateCriteria(numCriteria, objectiveBlock) if IsInCompletedInstance() then Addon.Splits.UpdateSplits(self, numCriteria, objectiveBlock, true) else SCENARIO_CONTENT_TRACKER_MODULE_UpdateCriteria_Old(self, numCriteria, objectiveBlock) end end end local function LoadExclusive() local function IsInActiveInstance() return select(10, C_Scenario.GetInfo()) == LE_SCENARIO_TYPE_CHALLENGE_MODE and select(3, C_Scenario.GetInfo()) ~= 0 end ObjectiveTracker_Update_Old = ObjectiveTracker_Update function ObjectiveTracker_Update(...) if IsInActiveInstance() then local tracker = ObjectiveTrackerFrame local modules_old = tracker.MODULES local modules_ui_old = tracker.MODULES_UI_ORDER tracker.MODULES = { SCENARIO_CONTENT_TRACKER_MODULE } tracker.MODULES_UI_ORDER = { SCENARIO_CONTENT_TRACKER_MODULE } for i = 1, #modules_old do local module = modules_old[i] if module ~= SCENARIO_CONTENT_TRACKER_MODULE then module:BeginLayout() module:EndLayout() module.Header:Hide() if module.Header.animating then module.Header.animating = nil module.Header.HeaderOpenAnim:Stop() end end end ObjectiveTracker_Update_Old(...) tracker.MODULES = modules_old tracker.MODULES_UI_ORDER = modules_ui_old else ObjectiveTracker_Update_Old(...) end end ObjectiveTracker_ReorderModules_Old = ObjectiveTracker_ReorderModules function ObjectiveTracker_ReorderModules() if IsInActiveInstance() then local modules = ObjectiveTrackerFrame.MODULES; local modulesUIOrder = ObjectiveTrackerFrame.MODULES_UI_ORDER; else ObjectiveTracker_ReorderModules_Old() end end end function Mod:CHALLENGE_MODE_COMPLETED() ScenarioTimer_CheckTimers(GetWorldElapsedTimers()) ObjectiveTracker_Update() end function Mod:Startup() if Addon.Config.persistTracker and LoadPersist then LoadPersist() LoadPersist = nil self:RegisterEvent("CHALLENGE_MODE_COMPLETED") end if Addon.Config.exclusiveTracker and LoadExclusive then LoadExclusive() LoadExclusive = nil self:RegisterEvent("CHALLENGE_MODE_COMPLETED") end challengeMapID = C_ChallengeMode.GetActiveChallengeMapID() end function Mod:AfterStartup() if Addon.Config.persistTracker or Addon.Config.exclusiveTracker then ObjectiveTracker_Update() end end
mit
SbssTeam/QuickPlus
plugins/password.lua
1
2225
do local function set_pass(msg, pass, id) local hash = nil if msg.to.type == "channel" then hash = 'setpass:' end local name = string.gsub(msg.to.print_name, '_', '') if hash then redis:hset(hash, pass, id) return send_large_msg("channel#id"..msg.to.id, "ߔ᠐assword of group:\n["..name.."] has been set to:‌\n\n "..pass.."\n\nNow user can join in pm by\n!join "..pass.." ⚜", ok_cb, true) end end local function is_used(pass) local hash = 'setpass:' local used = redis:hget(hash, pass) return used or false end local function show_add(cb_extra, success, result) vardump(result) local receiver = cb_extra.receiver local text = "I added you toߑ堢"..result.title.."(ߑ䢮.result.participants_count..)" send_large_msg(receiver, text) end local function added(msg, target) local receiver = get_receiver(msg) channel_info("channel#id"..target, show_add, {receiver=receiver}) end local function run(msg, matches) if matches[1] == "setpass" and msg.to.type == "channel" and matches[2] then local pass = matches[2] local id = msg.to.id if is_used(pass) then return "Sorry, This pass is already taken." end redis:del("setpass:", id) return set_pass(msg, pass, id) end if matches[1] == "join" and matches[2] then local hash = 'setpass:' local pass = matches[2] local id = redis:hget(hash, pass) local receiver = get_receiver(msg) if not id then return "Could not find a group with this pass\nMaby the pass has been changed" end chat_add_user("channel#id"..id, "user#id"..msg.from.id, ok_cb, false) return added(msg, id) else return "I could not added you to"..string.gsub(msg.to.id.print_name, '_', ' ') end if matches[1] == "pass" then local hash = 'setpass:' local chat_id = msg.to.id local pass = redis:hget(hash, channel_id) local receiver = get_receiver(msg) send_large_msg(receiver, "Password for Group:["..msg.to.print_name.."]\n\nPass > "..pass) end end return { patterns = { "^[/!#](setpass) (.*)$", "^[/!#](pass)$", "^[/!#](join) (.*)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (.+)$", "^!!tgservice (chat_del_user)$" }, run = run } end
gpl-2.0
hadirahimi1380/AhrimanBot
plugins/inrealm.lua
114
25001
-- 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 local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" 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 local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" 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 not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) 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
ingran/balzac
custom_feeds/teltonika_luci/applications/luci-statistics/luasrc/statistics/rrdtool/definitions/olsrd.lua
85
3643
--[[ Luci statistics - olsrd plugin diagram definition Copyright 2011 Manuel Munz <freifunk at somakoma dot de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module("luci.statistics.rrdtool.definitions.olsrd", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) local g = { } if plugin_instance == "routes" then g[#g+1] = { -- diagram data description title = "%H: Total amount of OLSR routes", vlabel = "n", number_format = "%5.0lf", data = { types = { "routes" }, options = { routes = { color = "ff0000", title = "Total number of routes" } } } } g[#g+1] = { title = "%H: Average route ETX", vlabel = "ETX", detail = true, number_format = "%5.1lf",data = { instances = { "average" }, -- falls es irgendwann mal welche pro ip gibt, wie bei links, dann werden die hier excludiert types = { "route_etx" }, options = { route_etx = { title = "Average route ETX" } } } } g[#g+1] = { title = "%H: Average route metric", vlabel = "metric", detail = true, number_format = "%5.1lf", data = { instances = { "average" }, -- falls es irgendwann mal welche pro ip gibt, wie bei links, dann werden die hier excludiert types = { "route_metric" }, options = { route_metric = { title = "Average route metric" } } } } elseif plugin_instance == "links" then g[#g+1] = { -- diagram data description title = "%H: Total amount of OLSR neighbours", vlabel = "n", number_format = "%5.0lf", data = { instances = { "" }, types = { "links" }, options = { links = { color = "00ff00", title = "Number of neighbours" } } } } local instances = graph.tree:data_instances(plugin, plugin_instance, "signal_quality") table.sort(instances) -- define one diagram per host, containing the rx and lq values local i for i = 1, #instances, 2 do local dsn1 = "signal_quality_%s_value" % instances[i]:gsub("[^%w]+", "_") local dsn2 = "signal_quality_%s_value" % instances[i+1]:gsub("[^%w]+", "_") local host = instances[i]:match("^[^%-]+%-([^%-]+)%-.+") g[#g+1] = { title = "%H: Signal Quality" .. " (" .. (host or "avg") ..")", vlabel = "ETX", number_format = "%5.2lf", detail = true, data = { types = { "signal_quality" }, instances = { signal_quality = { instances[i], instances[i+1] }, }, options = { [dsn1] = { color = "00ff00", title = "LQ (%s)" % (host or "avg"), }, [dsn2] = { color = "0000ff", title = "NLQ (%s)" % (host or "avg"), flip = true } } } } end elseif plugin_instance == "topology" then g[#g+1] = { title= "%H: Total amount of OLSR links", vlabel = "n", number_format = "%5.0lf", data = { instances = { "" }, types = { "links" }, options = { links = { color = "0000ff", title = "Total number of links" } } } } g[#g+1] = { title= "%H: Average signal quality", vlabel = "n", number_format = "%5.2lf", detail = true, data = { instances = { "average" }, -- exclude possible per-ip stuff types = { "signal_quality" }, options = { signal_quality = { color = "0000ff", title = "Average signal quality" } } } } end return g end
gpl-2.0
kosua20/GL_Template
src/libs/glfw/premake5.lua
1
1674
project("glfw3") kind("StaticLib") language("C") -- common files files({"src/internal.h", "src/mappings.h", "src/glfw_config.h", "include/GLFW/glfw3.h", "include/GLFW/glfw3native.h", "src/context.c", "src/init.c", "src/input.c", "src/monitor.c", "src/vulkan.c", "src/window.c", "premake5.lua"}) -- system build filters filter("system:windows") defines({"_GLFW_WIN32=1"}) files({"src/win32_platform.h","src/win32_joystick.h","src/wgl_context.h","src/egl_context.h", "src/osmesa_context.h","src/win32_init.c","src/win32_joystick.c","src/win32_monitor.c","src/win32_time.c", "src/win32_thread.c","src/win32_window.c","src/wgl_context.c","src/egl_context.c","src/osmesa_context.c"}) filter("system:macosx") defines({"_GLFW_COCOA=1"}) files({"src/cocoa_platform.h","src/cocoa_joystick.h","src/posix_thread.h","src/nsgl_context.h", "src/egl_context.h","src/osmesa_context.h","src/cocoa_init.m","src/cocoa_joystick.m","src/cocoa_monitor.m", "src/cocoa_window.m","src/cocoa_time.c","src/posix_thread.c","src/nsgl_context.m","src/egl_context.c", "src/osmesa_context.c"}) filter("system:linux") defines({"_GLFW_X11=1"}) files({"src/x11_platform.h", "src/xkb_unicode.h", "src/posix_time.h", "src/posix_thread.h", "src/glx_context.h", "src/egl_context.h", "src/osmesa_context.h", "src/x11_init.c", "src/x11_monitor.c", "src/x11_window.c", "src/xkb_unicode.c", "src/posix_time.c", "src/posix_thread.c", "src/glx_context.c", "src/egl_context.c", "src/osmesa_context.c", "src/linux_joystick.h", "src/linux_joystick.c"}) -- visual studio filters filter("action:vs*") defines({ "_CRT_SECURE_NO_WARNINGS" }) filter({})
mit
nemisis99/BolScripts
EliseMechanics.lua
13
21635
--[[ _____ _____ __ .__ / \_______ / _ \________/ |_|__| ____ __ __ ____ ____ / \ / \_ __ \ / /_\ \_ __ \ __\ |/ ___\| | \/ \ / _ \ / Y \ | \/ / | \ | \/| | | \ \___| | / | ( <_> ) \____|__ /__| \____|__ /__| |__| |__|\___ >____/|___| /\____/ \/ \/ \/ \/ 0.35 - Updated Ranges ]] if myHero.charName ~= "Elise" then return end local version = 0.35 local AUTOUPDATE = true local SCRIPT_NAME = "EliseMechanics" local SOURCELIB_URL = "https://raw.github.com/TheRealSource/public/master/common/SourceLib.lua" local SOURCELIB_PATH = LIB_PATH.."SourceLib.lua" if FileExist(SOURCELIB_PATH) then require("SourceLib") else DOWNLOADING_SOURCELIB = true DownloadFile(SOURCELIB_URL, SOURCELIB_PATH, function() print("Required libraries downloaded successfully, please reload") end) end if DOWNLOADING_SOURCELIB then print("Downloading required libraries, please wait...") return end if AUTOUPDATE then SourceUpdater(SCRIPT_NAME, version, "raw.github.com", "/gmlyra/BolScripts/master/"..SCRIPT_NAME..".lua", SCRIPT_PATH .. GetCurrentEnv().FILE_NAME, "/gmlyra/BolScripts/master/VersionFiles/"..SCRIPT_NAME..".version"):CheckUpdate() end local RequireI = Require("SourceLib") RequireI:Add("vPrediction", "https://raw.github.com/Hellsing/BoL/master/common/VPrediction.lua") RequireI:Add("SOW", "https://raw.github.com/Hellsing/BoL/master/common/SOW.lua") if VIP_USER then RequireI:Add("Prodiction", "https://bitbucket.org/Klokje/public-klokjes-bol-scripts/raw/ec830facccefb3b52212dba5696c08697c3c2854/Test/Prodiction/Prodiction.lua") end --RequireI:Add("mrLib", "https://raw.githubusercontent.com/gmlyra/BolScripts/master/common/mrLib.lua") RequireI:Check() if RequireI.downloadNeeded == true then return end require 'VPrediction' require 'SOW' -- Constants -- local ignite, igniteReady = nil, nil local ts = nil local VP = nil local qMode = false local qOff, wOff, eOff, rOff = 0,0,0,0 local abilitySequence = {2, 1, 3, 2, 2, 4, 1, 1, 2, 2, 4, 1, 1, 3, 3, 4, 3, 3} local Ranges = { AA = 550 } local skills = { Q = { ready = false, name = myHero:GetSpellData(_Q).name, range = 625, delay = myHero:GetSpellData(_Q).delayTotalTimePercent, speed = myHero:GetSpellData(_Q).missileSpeed, width = myHero:GetSpellData(_Q).lineWidth }, W = { ready = false, name = myHero:GetSpellData(_W).name, range = 950, delay = 0.25, speed = 1000, width = 100 }, E = { ready = false, name = myHero:GetSpellData(_E).name, range = 750, delay = 0.25, speed = 1300, width = 55 }, R = { ready = false, name = myHero:GetSpellData(_R).name, range = 0, delay = myHero:GetSpellData(_R).delayTotalTimePercent, speed = myHero:GetSpellData(_R).missileSpeed, width = myHero:GetSpellData(_R).lineWidth }, } local AnimationCancel = { [1]=function() myHero:MoveTo(mousePos.x,mousePos.z) end, --"Move" [2]=function() SendChat('/l') end, --"Laugh" [3]=function() SendChat('/d') end, --"Dance" [4]=function() SendChat('/t') end, --"Taunt" [5]=function() SendChat('/j') end, --"joke" [6]=function() end, } --[[ Slots Itens ]]-- local tiamatSlot, hydraSlot, youmuuSlot, bilgeSlot, bladeSlot, dfgSlot, divineSlot = nil, nil, nil, nil, nil, nil, nil local tiamatReady, hydraReady, youmuuReady, bilgeReady, bladeReady, dfgReady, divineReady = nil, nil, nil, nil, nil, nil, nil --[[Misc]]-- local lastSkin = 0 local isSAC = false local isMMA = false local target = nil local spiderForm = false local focusTarget = nil -- [[ VIP Variables]] -- local Prodict local ProdictE, ProdictECol --Credit Trees function GetCustomTarget() ts:update() if focusTarget ~= nil and not focusTarget.dead and Menu.targetSelector.focusPriority then return focusTarget end if _G.MMA_Target and _G.MMA_Target.type == myHero.type then return _G.MMA_Target end if _G.AutoCarry and _G.AutoCarry.Crosshair and _G.AutoCarry.Attack_Crosshair and _G.AutoCarry.Attack_Crosshair.target and _G.AutoCarry.Attack_Crosshair.target.type == myHero.type then return _G.AutoCarry.Attack_Crosshair.target end return ts.target end function OnLoad() if _G.ScriptLoaded then return end _G.ScriptLoaded = true initComponents() end function initComponents() -- VPrediction Start VP = VPrediction() -- SOW Declare Orbwalker = SOW(VP) -- Target Selector ts = TargetSelector(TARGET_LESS_CAST_PRIORITY, 1075) Menu = scriptConfig("Elise Mechanics by Mr Articuno", "EliseMA") if _G.MMA_Target ~= nil then PrintChat("<font color = \"#33CCCC\">MMA Status:</font> <font color = \"#fff8e7\"> Loaded</font>") isMMA = true elseif _G.AutoCarry ~= nil then PrintChat("<font color = \"#33CCCC\">SAC Status:</font> <font color = \"#fff8e7\"> Loaded</font>") isSAC = true else PrintChat("<font color = \"#33CCCC\">OrbWalker not found:</font> <font color = \"#fff8e7\"> Loading SOW</font>") Menu:addSubMenu("["..myHero.charName.." - Orbwalker]", "SOWorb") Orbwalker:LoadToMenu(Menu.SOWorb) end Menu:addSubMenu("["..myHero.charName.." - Combo]", "EliseCombo") Menu.EliseCombo:addParam("combo", "Combo mode", SCRIPT_PARAM_ONKEYDOWN, false, 32) Menu.EliseCombo:addSubMenu("Q Settings", "qSet") Menu.EliseCombo.qSet:addParam("useQ", "Use Q in combo", SCRIPT_PARAM_ONOFF, true) Menu.EliseCombo:addSubMenu("W Settings", "wSet") Menu.EliseCombo.wSet:addParam("useW", "Use W", SCRIPT_PARAM_ONOFF, true) Menu.EliseCombo:addSubMenu("E Settings", "eSet") Menu.EliseCombo.eSet:addParam("useE", "Use E in combo", SCRIPT_PARAM_ONOFF, true) Menu.EliseCombo:addSubMenu("R Settings", "rSet") Menu.EliseCombo.rSet:addParam("useR", "Auto Change Form", SCRIPT_PARAM_ONOFF, true) Menu.EliseCombo.rSet:addParam("useRE", "Gap Closer Gank", SCRIPT_PARAM_ONOFF, false) Menu:addSubMenu("["..myHero.charName.." - Harass]", "Harass") Menu.Harass:addParam("harass", "Harass", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("G")) Menu.Harass:addParam("useQ", "Use Q in Harass", SCRIPT_PARAM_ONOFF, true) Menu.Harass:addParam("useW", "Use W in Harass", SCRIPT_PARAM_ONOFF, true) Menu.Harass:addParam("useE", "Use E in Harass", SCRIPT_PARAM_ONOFF, true) Menu:addSubMenu("["..myHero.charName.." - Laneclear]", "Laneclear") Menu.Laneclear:addParam("lclr", "Laneclear Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V")) Menu.Laneclear:addParam("useClearQ", "Use Q in Laneclear", SCRIPT_PARAM_ONOFF, true) Menu.Laneclear:addParam("useClearW", "Use W in Laneclear", SCRIPT_PARAM_ONOFF, true) Menu:addSubMenu("["..myHero.charName.." - Jungleclear]", "Jungleclear") Menu.Jungleclear:addParam("jclr", "Jungleclear Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V")) Menu.Jungleclear:addParam("useClearQ", "Use Q in Jungleclear", SCRIPT_PARAM_ONOFF, true) Menu.Jungleclear:addParam("useClearW", "Use W in Jungleclear", SCRIPT_PARAM_ONOFF, true) Menu:addSubMenu("["..myHero.charName.." - Additionals]", "Ads") Menu.Ads:addParam("cancel", "Animation Cancel", SCRIPT_PARAM_LIST, 1, { "Move","Laugh","Dance","Taunt","joke","Nothing" }) Menu.Ads:addParam("autoLevel", "Auto-Level Spells", SCRIPT_PARAM_ONOFF, false) Menu.Ads:addSubMenu("Killsteal", "KS") Menu.Ads.KS:addParam("ignite", "Use Ignite", SCRIPT_PARAM_ONOFF, false) Menu.Ads.KS:addParam("igniteRange", "Minimum range to cast Ignite", SCRIPT_PARAM_SLICE, 470, 0, 600, 0) Menu.Ads:addSubMenu("VIP", "VIP") --Menu.Ads.VIP:addParam("spellCast", "Spell by Packet", SCRIPT_PARAM_ONOFF, true) Menu.Ads.VIP:addParam("prodiction", "Use Prodiction", SCRIPT_PARAM_ONOFF, false) Menu.Ads.VIP:addParam("skin", "Use custom skin", SCRIPT_PARAM_ONOFF, false) Menu.Ads.VIP:addParam("skin1", "Skin changer", SCRIPT_PARAM_SLICE, 1, 1, 3) Menu:addSubMenu("["..myHero.charName.." - Target Selector]", "targetSelector") Menu.targetSelector:addTS(ts) ts.name = "Focus" Menu.targetSelector:addParam("focusPriority", "Force Combo Selected Target", SCRIPT_PARAM_ONOFF, false) Menu:addSubMenu("["..myHero.charName.." - Drawings]", "drawings") local DManager = DrawManager() DManager:CreateCircle(myHero, Ranges.AA, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"AA range", true, true, true) DManager:CreateCircle(myHero, skills.Q.range, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"Q range", true, true, true) DManager:CreateCircle(myHero, skills.W.range, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"W range", true, true, true) DManager:CreateCircle(myHero, skills.E.range, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"E range", true, true, true) targetMinions = minionManager(MINION_ENEMY, 360, myHero, MINION_SORT_MAXHEALTH_DEC) allyMinions = minionManager(MINION_ALLY, 360, myHero, MINION_SORT_MAXHEALTH_DEC) jungleMinions = minionManager(MINION_JUNGLE, 360, myHero, MINION_SORT_MAXHEALTH_DEC) if VIP_USER then require 'Prodiction' require 'Collision' Prodict = ProdictManager.GetInstance() ProdictE = Prodict:AddProdictionObject(_E, skills.E.range, skills.E.speed, skills.E.delay, skills.E.width) ProdictECol = Collision(skills.E.range, skills.E.speed, skills.E.delay, skills.E.width) end if Menu.Ads.VIP.skin and VIP_USER then GenModelPacket("Elise", Menu.Ads.VIP.skin1) lastSkin = Menu.Ads.VIP.skin1 end PrintChat("<font color = \"#33CCCC\">Elise Mechanics by</font> <font color = \"#fff8e7\">Mr Articuno</font>") PrintChat("<font color = \"#4693e0\">Sponsored by www.RefsPlea.se</font> <font color = \"#d6ebff\"> - A League of Legends Referrals service. Get RP cheaper!</font>") end function OnTick() target = GetCustomTarget() targetMinions:update() allyMinions:update() jungleMinions:update() CDHandler() KillSteal() if myHero.dead then return end if not myHero.canMove then return end local focus = GetTarget() if focus ~= nil then if string.find(focus.type, "Hero") and focus.team ~= myHero.team then focusTarget = focus end end if Menu.Ads.VIP.skin and VIP_USER and skinChanged() then GenModelPacket("Elise", Menu.Ads.VIP.skin1) lastSkin = Menu.Ads.VIP.skin1 end if Menu.Ads.autoLevel then AutoLevel() end if Menu.EliseCombo.combo then Combo() end if Menu.Harass.harass then Harass() end if Menu.Laneclear.lclr then LaneClear() end if Menu.Jungleclear.jclr then JungleClear() end end function CDHandler() -- Spells skills.Q.ready = (myHero:CanUseSpell(_Q) == READY) skills.W.ready = (myHero:CanUseSpell(_W) == READY) skills.E.ready = (myHero:CanUseSpell(_E) == READY) skills.R.ready = (myHero:CanUseSpell(_R) == READY) Ranges.AA = myHero.range -- Items tiamatSlot = GetInventorySlotItem(3077) hydraSlot = GetInventorySlotItem(3074) youmuuSlot = GetInventorySlotItem(3142) bilgeSlot = GetInventorySlotItem(3144) bladeSlot = GetInventorySlotItem(3153) dfgSlot = GetInventorySlotItem(3128) divineSlot = GetInventorySlotItem(3131) tiamatReady = (tiamatSlot ~= nil and myHero:CanUseSpell(tiamatSlot) == READY) hydraReady = (hydraSlot ~= nil and myHero:CanUseSpell(hydraSlot) == READY) youmuuReady = (youmuuSlot ~= nil and myHero:CanUseSpell(youmuuSlot) == READY) bilgeReady = (bilgeSlot ~= nil and myHero:CanUseSpell(bilgeSlot) == READY) bladeReady = (bladeSlot ~= nil and myHero:CanUseSpell(bladeSlot) == READY) dfgReady = (dfgSlot ~= nil and myHero:CanUseSpell(dfgSlot) == READY) divineReady = (divineSlot ~= nil and myHero:CanUseSpell(divineSlot) == READY) if myHero.dead then spiderForm = false end -- Summoners if myHero:GetSpellData(SUMMONER_1).name:find("SummonerDot") then ignite = SUMMONER_1 elseif myHero:GetSpellData(SUMMONER_2).name:find("SummonerDot") then ignite = SUMMONER_2 end igniteReady = (ignite ~= nil and myHero:CanUseSpell(ignite) == READY) end -- Harass -- function Harass() if target ~= nil and ValidTarget(target) then if not spiderForm then if skills.E.ready and ValidTarget(target, skills.E.range) and Menu.Harass.useE then if VIP_USER and Menu.Ads.VIP.prodiction then ProdictE:GetPredictionCallBack(target, CastE) else local ePosition, eChance = VP:GetLineCastPosition(target, skills.E.delay, skills.E.width, skills.E.range, skills.E.speed, myHero, true) if ePosition ~= nil and GetDistance(ePosition) < skills.E.range and eChance >= 2 then CastSpell(_E, ePosition.x, ePosition.z) end end end if skills.W.ready and ValidTarget(target, skills.W.range) and Menu.Harass.useW then if VIP_USER and Menu.Ads.VIP.prodiction then local pos, info = Prodiction.GetPrediction(target, skills.W.range, skills.W.speed, skills.W.delay, skills.W.width) if pos then CastSpell(_W, pos.x, pos.z) end else local Position, Chance = VP:GetLineCastPosition(target, skills.W.delay, skills.W.width, skills.W.range, skills.W.speed, myHero, false) if Position ~= nil and GetDistance(Position) < skills.W.range and Chance >= 2 then CastSpell(_W, Position.x, Position.z) end end end if skills.Q.ready and ValidTarget(target, skills.Q.range) and Menu.Harass.useQ then CastSpell(_Q, target) end end if spiderForm then if skills.E.ready and ValidTarget(target, skills.E.range) and Menu.Harass.useE then CastSpell(_E, target) CastSpell(_E, target.x, target.z) end if skills.W.ready and ValidTarget(target, Ranges.AA - 425) and Menu.Harass.useW then CastSpell(_E) end if skills.Q.ready and ValidTarget(target, skills.Q.range - 125) and Menu.Harass.useQ then CastSpell(_Q, target) end end end end -- End Harass -- -- Combo Selector -- function Combo() local typeCombo = 0 if target ~= nil then AllInCombo(target, 0) end end -- Combo Selector -- -- All In Combo -- function AllInCombo(target, typeCombo) if target ~= nil and typeCombo == 0 then ItemUsage(target) if not spiderForm then if skills.E.ready and ValidTarget(target, skills.E.range) and Menu.EliseCombo.eSet.useE then if VIP_USER and Menu.Ads.VIP.prodiction then local pos, info = Prodiction.GetPrediction(target, skills.E.range, skills.E.speed, skills.E.delay, skills.E.width) if info.hitchance > 2 then CastSpell(_E, pos.x, pos.z) end else local ePosition, eChance = VP:GetLineCastPosition(target, skills.E.delay, skills.E.width, skills.E.range, skills.E.speed, myHero, true) if ePosition ~= nil and GetDistance(ePosition) < skills.E.range and eChance >= 2 then CastSpell(_E, ePosition.x, ePosition.z) end end end if skills.W.ready and ValidTarget(target, skills.W.range) and Menu.EliseCombo.wSet.useW then if VIP_USER and Menu.Ads.VIP.prodiction then local pos, info = Prodiction.GetPrediction(target, skills.W.range, skills.W.speed, skills.W.delay, skills.W.width) if info.hitchance >= 2 then CastSpell(_W, pos.x, pos.z) end else local Position, Chance = VP:GetLineCastPosition(target, skills.W.delay, skills.W.width, skills.W.range, skills.W.speed, myHero, false) if Position ~= nil and GetDistance(Position) < skills.W.range and Chance >= 2 then CastSpell(_W, Position.x, Position.z) end end end if skills.Q.ready and ValidTarget(target, skills.Q.range) and Menu.EliseCombo.qSet.useQ then CastSpell(_Q, target) end if skills.R.ready and ValidTarget(target, skills.E.range) and Menu.EliseCombo.rSet.useR then CastSpell(_R) end end if spiderForm then if Menu.EliseCombo.rSet.useRE and ValidTarget(target, skills.E.range) and skills.R.ready then if skills.E.ready then CastSpell(_E) CastSpell(_E, target) CastSpell(_R) end end if skills.E.ready and ValidTarget(target, skills.E.range) and GetDistance(target) >= 425 and Menu.EliseCombo.eSet.useE then CastSpell(_E, target) CastSpell(_E, target.x, target.z) end if skills.Q.ready and ValidTarget(target, skills.Q.range - 125) and Menu.EliseCombo.qSet.useQ then CastSpell(_Q, target) end if skills.W.ready and ValidTarget(target, Ranges.AA - 425) and Menu.EliseCombo.wSet.useW then CastSpell(_W) end if not skills.Q.ready and not skills.E.ready and not skills.W.ready and GetDistance(target) >= 325 then if skills.R.ready and Menu.EliseCombo.rSet.useR then CastSpell(_R) end end end end end -- All In Combo -- function LaneClear() for i, target in pairs(targetMinions.objects) do if target ~= nil then if not spiderForm then if skills.W.ready and ValidTarget(target, skills.W.range) and Menu.Laneclear.useClearW then if VIP_USER and Menu.Ads.VIP.prodiction then local pos, info = Prodiction.GetPrediction(target, skills.W.range, skills.W.speed, skills.W.delay, skills.W.width) if pos then CastSpell(_W, pos.x, pos.z) end else local Position, Chance = VP:GetLineCastPosition(target, skills.W.delay, skills.W.width, skills.W.range, skills.W.speed, myHero, false) if Position ~= nil and GetDistance(Position) < skills.W.range and Chance >= 2 then CastSpell(_W, Position.x, Position.z) end end end if skills.Q.ready and ValidTarget(target, skills.Q.range) and Menu.Laneclear.useClearQ then CastSpell(_Q, target) end if skills.R.ready and ValidTarget(target, skills.E.range) then CastSpell(_R) end end if spiderForm then if skills.W.ready and ValidTarget(target, Ranges.AA - 425) and Menu.Laneclear.useClearW then CastSpell(_W) end if skills.Q.ready and ValidTarget(target, skills.Q.range - 125) and Menu.Laneclear.useClearQ then CastSpell(_Q, target) end end end end end function JungleClear() for i, target in pairs(jungleMinions.objects) do if target ~= nil then if not spiderForm then if skills.W.ready and ValidTarget(target, skills.W.range) and Menu.Jungleclear.useClearW then if VIP_USER and Menu.Ads.VIP.prodiction then local pos, info = Prodiction.GetPrediction(target, skills.W.range, skills.W.speed, skills.W.delay, skills.W.width) if pos then CastSpell(_W, pos.x, pos.z) end else local Position, Chance = VP:GetLineCastPosition(target, skills.W.delay, skills.W.width, skills.W.range, skills.W.speed, myHero, false) if Position ~= nil and GetDistance(Position) < skills.W.range and Chance >= 2 then CastSpell(_W, Position.x, Position.z) end end end if skills.Q.ready and ValidTarget(target, skills.Q.range) and Menu.Jungleclear.useClearQ then CastSpell(_Q, target) end if skills.R.ready and ValidTarget(target, skills.E.range) then CastSpell(_R) end end if spiderForm then if skills.W.ready and ValidTarget(target, Ranges.AA - 425) and Menu.Jungleclear.useClearW then CastSpell(_W) end if skills.Q.ready and ValidTarget(target, skills.Q.range - 125) and Menu.Jungleclear.useClearQ then CastSpell(_Q, target) end end end end end function AutoLevel() local qL, wL, eL, rL = player:GetSpellData(_Q).level + qOff, player:GetSpellData(_W).level + wOff, player:GetSpellData(_E).level + eOff, player:GetSpellData(_R).level + rOff if qL + wL + eL + rL < player.level then local spellSlot = { SPELL_1, SPELL_2, SPELL_3, SPELL_4, } local level = { 0, 0, 0, 0 } for i = 1, player.level, 1 do level[abilitySequence[i]] = level[abilitySequence[i]] + 1 end for i, v in ipairs({ qL, wL, eL, rL }) do if v < level[i] then LevelSpell(spellSlot[i]) end end end end function KillSteal() if Menu.Ads.KS.ignite then IgniteKS() end end -- Auto Ignite get the maximum range to avoid over kill -- function IgniteKS() if igniteReady then local Enemies = GetEnemyHeroes() for i, val in ipairs(Enemies) do if ValidTarget(val, 600) then if getDmg("IGNITE", val, myHero) > val.health and GetDistance(val) >= Menu.Ads.KS.igniteRange then CastSpell(ignite, val) end end end end end -- Auto Ignite -- function HealthCheck(unit, HealthValue) if unit.health > (unit.maxHealth * (HealthValue/100)) then return true else return false end end function animationCancel(unit, spell) if not unit.isMe then return end end function ItemUsage(target) if dfgReady then CastSpell(dfgSlot, target) end if youmuuReady then CastSpell(youmuuSlot, target) end if bilgeReady then CastSpell(bilgeSlot, target) end if bladeReady then CastSpell(bladeSlot, target) end if divineReady then CastSpell(divineSlot, target) end end -- Change skin function, made by Shalzuth function GenModelPacket(champ, skinId) p = CLoLPacket(0x97) p:EncodeF(myHero.networkID) p.pos = 1 t1 = p:Decode1() t2 = p:Decode1() t3 = p:Decode1() t4 = p:Decode1() p:Encode1(t1) p:Encode1(t2) p:Encode1(t3) p:Encode1(bit32.band(t4,0xB)) p:Encode1(1)--hardcode 1 bitfield p:Encode4(skinId) for i = 1, #champ do p:Encode1(string.byte(champ:sub(i,i))) end for i = #champ + 1, 64 do p:Encode1(0) end p:Hide() RecvPacket(p) end function OnProcessSpell(unit, spell) if unit.isMe then if spell.name == 'EliseR' then spiderForm = true elseif spell.name == 'EliseRSpider' then spiderForm = false end end end function CastE(unit, pos, spell) if GetDistance(pos) - getHitBoxRadius(unit)/2 < skills.E.range then local willCollide = ProdictECol:GetMinionCollision(pos, myHero) if not willCollide then CastSpell(_E, pos.x, pos.z) end end end function skinChanged() return Menu.Ads.VIP.skin1 ~= lastSkin end function OnDraw() end
gpl-2.0
liruqi/bigfoot
Interface/AddOns/Recount/locales/Recount-zhCN.lua
1
17910
-- Recount Locale -- Please use the Localization App on WoWAce to Update this -- http://www.wowace.com/projects/recount/localization/ local L = LibStub("AceLocale-3.0"):NewLocale("Recount", "zhCN") if not L then return end L[" at "] = "在" L[" by "] = "由" L[" dies."] = "死亡。" L[" for "] = "为" L["|cff40ff40Enabled|r"] = "|cff40ff40启用|r" L["|cffff4040Disabled|r"] = "|cffff4040禁用|r" L["Ability"] = "技能" L["Ability Name"] = "技能名称" L["Absorbed"] = "被吸收" L["Absorbs"] = "吸收" L["Activity"] = "活跃度" L["Add to Current Graph (Alt Click)"] = "添加到当前图表(Alt 点击)" L["Allows the data of a window to be reported"] = "发送统计数据的结果报告到指定的频道" L["Appearance"] = "外观" L["Arcane"] = "奥术" L["Arenas"] = "竞技场" L["Astral Power Abilities"] = "星界能量技能" L["Astral Power Gained"] = "星界能量获取" L["Astral Power Sources"] = "星界能量来源" L["Attack Name"] = "攻击名称" L["Attack Summary Incoming (Click for Outgoing)"] = "伤害承受统计(点击切换为输出)" L["Attack Summary Outgoing (Click for Incoming)"] = "伤害输出统计(点击切换为承受)" L["Attacked"] = "攻击目标" L["Attacked by"] = "攻击来自" L["Attacked/Healed"] = "攻击/治疗" L["Autodelete Time Data"] = "自动删除分时数据" L["Autohide On Combat"] = "战斗中隐藏" L["Autoswitch Shown Fight"] = "自动切换为当前战斗" L["Available Bandwidth"] = "可用带宽" L["Avg"] = "平均" L["Avg. DOTs Up"] = "平均 DOT 持续" L["Avg. HOTs Up"] = "平均治疗持续" L["Background"] = "背景" L["Bandwidth"] = "带宽" L["Bar Color Selection"] = "计量条颜色" L["Bar Selection"] = "选择样式" L["Bar Text"] = "计量条文本" L["Bar Text Options"] = "计量条文本选项" L["Battlegrounds"] = "战场" L["Block"] = "格挡" L["Blocked"] = "被格挡" L["Bosses"] = "首领" L["Bottom Color"] = "底端颜色" L["Broke"] = "打醒" L["Broke On"] = "打醒" L["Bytes"] = "字节" L["CC Breakers"] = "打醒控制" L["CC Breaking"] = "打醒控制" L["CC's Broken"] = "打醒控制" L["Check Versions"] = "检查版本" L["Clamp To Screen"] = "限于屏幕内" L["Class Colors"] = "职业颜色" L["Click for more Details"] = "点击显示更多细节" L["Click for next Pet"] = "点击切换到下个宠物" L["Click|r to toggle the Recount window"] = "点击|r切换 Recount 窗口" L["Close"] = "关闭" L["Color"] = "颜色" L["Combat Log Range"] = "战斗日志范围" L["Combat Messages"] = "战斗信息" L["Commas"] = "逗号" L["Config"] = "设置" L["Config Access"] = "存取设置" L["Config Recount"] = "配置 Recount" L["Confirmation"] = "确认" L["Content-based Filters"] = "基于内容的过滤器" L["Controls the frame strata of the Recount windows. Default: MEDIUM"] = "控制 Recount 窗口的框架阶层。默认:MEDIUM(中)" L["Controls whether the Recount windows can be dragged offscreen"] = "控制 Recount 窗口是否可被拖拽到屏幕以外" L["Count"] = "次数" L["Crit"] = "爆击" L["Crushing"] = "碾压" L["Current Fight"] = "当前战斗" L["Damage"] = "伤害" L["Damage Abilities"] = "伤害技能" L["Damage Done"] = "伤害输出" L["Damage Focus"] = "伤害比重" L["Damage Report for"] = "伤害报告:" L["Damage Taken"] = "承受伤害" L["Damaged Who"] = "伤害了谁" L["Data"] = "数据" L["Data collection turned off"] = "关闭数据收集" L["Data collection turned on"] = "开启数据收集" L["Data Deletion"] = "数据删除" L["Data Name"] = "数据名" L["Data Options"] = "数据选项" L["Death Details for"] = "详细死亡数据:" L["Death for "] = "死亡原因:" L["Death Graph"] = "死亡图表" L["Death Track"] = "死亡记录" L["Deaths"] = "死亡" L["Delete Combatant (Ctrl-Alt Click)"] = "删除战斗人员(Ctrl-Alt 点击)" L["Delete on Entry"] = "进入时删除" L["Delete on New Group"] = "新队伍时删除" L["Delete on New Raid"] = "新团队时删除" L["Detail"] = "详细" L["Detail Window"] = "细节窗口" L["Dispelled"] = "被驱散" L["Dispelled By"] = "驱散来自" L["Dispels"] = "驱散" L["Display"] = "显示" L["Displaying Versions"] = "显示版本" L["Displays the versions of players in the raid"] = "显示团队成员安装的 Recount 版本" L["Distribution"] = "分布" L["Do you wish to reset the data?"] = "你希望重置数据么?" L["Dodge"] = "闪避" L["DoT"] = "伤害/跳" L["DOT Time"] = "DOT 时间" L["DOT Uptime"] = "DOT 持续时间" L["DOTs"] = "持续伤害" L["Down Traffic"] = "下载流量" L["Downstream Traffic"] = "下行传输" L["DPS"] = "伤害/秒" L["DTPS"] = "承受伤害/秒" L["Duration"] = "持续时间" L["Enabled"] = "启用" L["End"] = "结束" L["Energy Abilities"] = "能量技能" L["Energy Gained"] = "能量获取" L["Energy Sources"] = "能量来源" L["Fight"] = "战斗" L["Fight Segmentation"] = "战斗分段" L["File"] = "文件" L["Filters"] = "过滤器" L["Fire"] = "火焰" L["Fix Ambiguous Log Strings"] = "修正模糊日志" L["Font Selection"] = "选择字体" L["Fought"] = "对手" L["FPS"] = "FPS" L["Frame Strata"] = "框架阶层" L["Friendly Attacks"] = "误伤次数" L["Friendly Fire"] = "队友误伤" L["Friendly Fired On"] = "误伤于" L["From"] = "来自" L["Frost"] = "冰霜" L["Frostfire"] = "冰霜火焰" L["Fury Abilities"] = "怒气技能" L["Fury Gained"] = "怒气获取" L["Fury Sources"] = "怒气来源" L["Gained"] = "获得" L["General Window Options"] = "一般窗口选项" L["Glancing"] = "偏斜" L["Global Data Collection"] = "全局数据收集" L["Global Realtime Windows"] = "全局实时窗口" L["Graph Window"] = "图形窗口" L["Group Based Deletion"] = "组队相关的删除" L["Grouped"] = "已组队" L["Guardian"] = "守护者" L["GUI"] = "图形界面" L["gui"] = "gui" L["Guild"] = "公会" L["Heal"] = "治疗" L["Heal Focus"] = "治疗比重" L["Heal Name"] = "治疗名称" L["Healed"] = "已治疗" L["Healed By"] = "治疗来自" L["Healed Who"] = "治疗了谁" L["Healing"] = "治疗" L["Healing Done"] = "治疗输出" L["Healing Taken"] = "获得治疗" L["Heals"] = "治疗" L["Health"] = "生命" L["Hide"] = "隐藏" L["Hide When Not Collecting"] = "不收集数据时隐藏" L["Hide While In Pet Battle"] = "宠物战斗时隐藏" L["Hides the main window"] = "隐藏主窗口" L["Hit"] = "命中" L["Holy"] = "神圣" L["Hostile"] = "敌对" L["HoT"] = "治疗/跳" L["HOT Time"] = "HOT 时间" L["HOT Uptime"] = "HOT 持续时间" L["HOTs"] = "持续治疗" L["HPS"] = "治疗/秒" L["HTPS"] = "接受治疗/秒" L["Incoming"] = "承受" L["Instance"] = "副本" L["Instance Based Deletion"] = "副本相关的删除" L["Integrate"] = "整合" L["Interrupted"] = "被打断" L["Interrupted Who"] = "打断了谁" L["Interrupts"] = "打断施法" L["Is this shown in the main window?"] = "是否在主窗口已显示?" L["Keep Only Boss Segments"] = "只保留首领战分段" L["Killed By"] = "被谁杀" L["Lag"] = "延时" L["Last Fight"] = "上次战斗" L["Latency"] = "延迟" L["Lines Reported"] = "报告行数" L["Lines reported set to: "] = "设置报告行数为:" L["Lock"] = "锁定" L["Lock Windows"] = "锁定窗口" L["Maelstorm Abilities"] = "漩涡技能" L["Maelstorm Gained"] = "漩涡获取" L["Maelstorm Sources"] = "漩涡来源" L["Main"] = "主要" L["Main Window"] = "主窗口" L["Main Window Options"] = "主窗口选项" L["Mana Abilities"] = "法力技能" L["Mana Gained"] = "法力获取" L["Mana Sources"] = "法力来源" L["Max"] = "最大" L["Melee"] = "肉搏" L["Merge Absorbs w/ Damage"] = "合并吸收和伤害" L["Merge Absorbs w/ Heals"] = "合并吸收和治疗" L["Merge Pets w/ Owners"] = "将宠物和主人合并" L["Messages"] = "信息" L["Min"] = "最小" L["Misc"] = "其他" L["Miss"] = "未击中" L["Mob"] = "怪物" L["Mobs"] = "怪物" L["Name of Ability"] = "技能的名称" L["Nature"] = "自然" L["Naturefire"] = "自然火焰" L["Network"] = "网络" L["Network and FPS"] = "网络与 FPS" L["Network Traffic"] = "网络流量" L["Network Traffic(by Player)"] = "网络传输(玩家排列)" L["Network Traffic(by Prefix)"] = "网络传输(前缀排列)" L["New"] = "新建" L["Next"] = "下一个" L["No"] = "否" L["No Absorb"] = "未被吸收" L["No Block"] = "未被格挡" L["No other Recount users found."] = "未找到其他 Recount 用户。" L["No Pet"] = "无宠物" L["No Resist"] = "未被抵抗" L["Non-Trivial"] = "有价值" L["Normalize"] = "标准化" L["Number Format"] = "数字格式" L["Officer"] = "官员" L["Open Ace3 Config GUI"] = "打开 Ace3 配置图形界面" L["Other Windows"] = "其他窗口" L["Outgoing"] = "输出" L["Outside Instances"] = "副本之外" L["Over Heals"] = "过量治疗" L["Overall Data"] = "所有数据" L["Overheal"] = "过量治疗" L["Overhealing"] = "过量治疗" L["Overhealing Done"] = "过量治疗输出" L["Pain Abilities"] = "痛苦技能" L["Pain Gained"] = "痛苦获取" L["Pain Sources"] = "痛苦来源" L["Parry"] = "招架" L["Party"] = "队伍" L["Party Instances"] = "小队副本" L["Pause"] = "暂停" L["pause"] = "pause" L["Per Second"] = "每秒" L["Percent"] = "百分比" L["Pet"] = "宠物" L["Pet Attacked"] = "宠物攻击目标" L["Pet Damage"] = "宠物伤害" L["Pet Damage Abilities"] = "宠物伤害技能" L["Pet Focus"] = "宠物伤害比重" L["Pet Healed"] = "宠物被治疗" L["Pet Healing Abilities"] = "治疗宠物技能" L["Pet Time"] = "宠物时间" L["Pets"] = "宠物" L["Physical"] = "物理" L["Player/Mob Name"] = "玩家/怪物名" L["Players"] = "玩家" L["Prefix"] = "前缀" L["Previous"] = "上一个" L["Profiles"] = "配置文件" L["Rage Abilities"] = "怒气技能" L["Rage Gained"] = "怒气获取" L["Rage Sources"] = "怒气来源" L["Raid"] = "团队" L["Raid Instances"] = "团队副本" L["Rank Number"] = "排名" L["Realtime"] = "实时曲线图" L["Record Buffs/Debuffs"] = "记录增益效果/负面影响" L["Record Data"] = "记录数据" L["Record Deaths"] = "记录死亡" L["Record Time Data"] = "记录时间数据" L["Recorded Fights"] = "已记录战斗" L["Records the times and applications of buff/debuffs on this type"] = "记录该类型增益效果/负面影响的应用以及时间的数据" L["Records when deaths occur and the past few actions involving this type"] = "记录该类型死亡何时发生的以及死亡前的部分动作" L["Recount"] = "Recount" L["Recount Version"] = "Recount 版本" L["Report"] = "报告" L["Report Data"] = "数据报告" L["Report for"] = "报告:" L["Report the DeathTrack Window Data"] = "报告死亡记录窗口的数据" L["Report the Detail Window Data"] = "发送详细的数据报告" L["Report the Main Window Data"] = "只发送主窗口中显示的统计数据报告" L["Report To"] = "报告给" L["Report Top"] = "报告人数" L["Reset"] = "重置" L["reset"] = "reset" L["Reset Colors"] = "重置颜色" L["Reset Positions"] = "重置位置" L["Reset Recount?"] = "重置 Recount?" L["ResetPos"] = "重置位置" L["Resets the data"] = "重置统计数据" L["Resets the positions of the detail, graph, and main windows"] = "恢复各个窗口的默认显示位置" L["Resist"] = "抵抗" L["Resisted"] = "被抵抗" L["Ressed"] = "已复活" L["Ressed Who"] = "复活了谁" L["Ressers"] = "复活" L["Right-click|r to open the options menu"] = "右击|r打开选项菜单" L["Row Height"] = "行高" L["Row Spacing"] = "行间距" L["Runic Power Abilities"] = "符文能量技能" L["Runic Power Gained"] = "获得符文能量" L["Runic Power Sources"] = "符文能量来源" L["'s Absorbs"] = "的吸收" L["'s Astral Power Gained"] = "的星界能量获取" L["'s Astral Power Gained From"] = "的星界能量获取从" L["'s Dispels"] = "的驱散次数" L["'s DOT Uptime"] = "的 DOT 持续时间" L["'s DPS"] = "的每秒伤害" L["'s DTPS"] = "的每秒承受伤害" L["'s Effective Healing"] = "的有效治疗" L["'s Energy Gained"] = "的能量获取" L["'s Energy Gained From"] = "的能量获取自" L["'s Friendly Fire"] = "的队友误伤" L["'s Fury Gained"] = "的怒气获取" L["'s Fury Gained From"] = "的怒气获取从" L["'s Hostile Attacks"] = "的敌对攻击" L["'s HOT Uptime"] = "的 HOT 持续时间" L["'s HPS"] = "的每秒治疗" L["'s HTPS"] = "的每秒接受治疗" L["'s Interrupts"] = "的打断次数" L["'s Maelstorm Gained"] = "的漩涡获取" L["'s Maelstorm Gained From"] = "的漩涡获取从" L["'s Mana Gained"] = "的法力获取" L["'s Mana Gained From"] = "的法力获取自" L["'s Network Traffic"] = "的网络流量" L["'s Overhealing"] = "的过量治疗" L["'s Pain Gained"] = "的痛苦获取" L["'s Pain Gained From"] = "的痛苦获取从" L["'s Partial Resists"] = "的部分抵抗" L["'s Rage Gained"] = "的怒气获取" L["'s Rage Gained From"] = "的怒气获取自" L["'s Resses"] = "的复活次数" L["'s Runic Power Gained"] = "的符文能量获取" L["'s Runic Power Gained From"] = "的符文能量获取从" L["'s Time Spent"] = "的时间花费" L["'s Time Spent Attacking"] = "攻击花费的时间" L["'s Time Spent Healing"] = "治疗花费的时间" L["'s TPS"] = "的每秒仇恨" L["Say"] = "说" L["Scenario Instances"] = "场景战役副本" L["Seconds"] = "秒" L["Self"] = "自己" L["Server Name"] = "服务器名称" L["Set Combat Log Range"] = "设置战斗日志范围" L["Set the maximum number of lines to report"] = "设置最大报告行数为:" L["Set the maximum number of recorded fight segments"] = "设定最高数量战斗记录分段" L["Shadow"] = "暗影" L["Shielded"] = "盾" L["Shielded Who"] = "被套盾" L["Short"] = "简短" L["Show"] = "显示" L["show"] = "show" L["Show Buttons"] = "显示按钮" L["Show Death Track (Left Click)"] = "显示死亡记录(左键点击)" L["Show Details (Left Click)"] = "显示细节(左键点击)" L["Show Graph"] = "显示图表" L["Show Graph (Shift Click)"] = "显示图表(Shift 点击)" L["Show next main page"] = "显示下一个主要页面" L["Show previous main page"] = "显示前一个主要页面" L["Show Realtime Graph (Ctrl Click)"] = "显示实时图表(Ctrl 点击)" L["Show Scrollbar"] = "显示滚动条" L["Show Total Bar"] = "显示总量条" L["Shows found unknown spells in BabbleSpell"] = "显示 BabbleSpell 库中找到的未知法术" L["Shows the config window"] = "显示插件的设置窗口" L["Shows the main window"] = "显示主窗口" L["Solo"] = "单独" L["Specialized Realtime Graphs"] = "显示指定单位的实时统计曲线图" L["Split"] = "平分" L["Stack"] = "叠加" L["Standard"] = "标准" L["Start"] = "开始" L["Starts a realtime window tracking amount of available AceComm bandwidth left"] = "开启一个实时监控 AceComm 可用带宽情况的曲线图" L["Starts a realtime window tracking your downstream traffic"] = "开启一个实时监控网络下行传输情况的曲线图" L["Starts a realtime window tracking your FPS"] = "开启一个实时监控画面帧数的曲线图" L["Starts a realtime window tracking your latency"] = "开启一个实时监控网络延时的曲线图" L["Starts a realtime window tracking your upstream traffic"] = "开启一个实时监控网络上行传输情况的曲线图" L["Summary Report for"] = "综合报表:" L["Swap Text and Bar Color"] = "文本与计量条颜色互换" L["Sync"] = "同步" L["sync"] = "sync" L["Sync Data"] = "同步数据" L["Sync Options"] = "同步选项" L["Taken"] = "承受" L["Threat"] = "仇恨" L["Threat on"] = "仇恨于" L["Tick"] = "跳" L["Ticked on"] = "每跳于" L["Time"] = "时间" L["Time (s)"] = "时间" L["Time Damaging"] = "伤害时间" L["Time Healing"] = "治疗时间" L["Times"] = "次数" L["Title"] = "标题" L["Title Text"] = "标题文本" L["Toggle"] = "开启/关闭" L["Toggle merge pets"] = "切换宠物合并" L["Toggle pause of global data collection"] = "开关全局数据收集" L["Toggles sending synchronization messages"] = "开启/关闭发送同步信息" L["Toggles the main window"] = "开启/关闭主窗口显示" L["Toggles windows being locked"] = "开启/关闭窗口的显示位置锁定" L["Took Damage From"] = "承受伤害自" L["Top 3"] = "排行前三的" L["Top Color"] = "顶端颜色" L["Total"] = "总和" L["Total Bar"] = "总量条" L["Tracks Raid Damage Per Second"] = "开启一个实时监控团队整体每秒伤害输出量的曲线图" L["Tracks Raid Damage Taken Per Second"] = "开启一个实时监控团队整体每秒伤害承受量的曲线图" L["Tracks Raid Healing Per Second"] = "开启一个实时监控团队整体每秒治疗输出量的曲线图" L["Tracks Raid Healing Taken Per Second"] = "开启一个实时监控团队整体每秒治疗承受量的曲线图" L["Tracks your entire raid"] = "追踪团队整体状况的曲线图" L["Trivial"] = "无价值" L["Type"] = "类型" L["Ungrouped"] = "未组队" L["Unknown"] = "未知" L["Unknown Spells"] = "未知法术" L["Unknown Spells:"] = "未知法术:" L["Up Traffic"] = "上传流量" L["Upstream Traffic"] = "上行传输" L["VerChk"] = "版本检查" L["verChk"] = "verChk" L["was Dispelled by"] = "被驱散自" L["was Healed by"] = "被治疗自" L["Whether data is recorded for this type"] = "该类型的数据是否已经被记录" L["Whether time data is recorded for this type (used for graphs can be a |cffff2020memory hog|r if you are concerned about memory)"] = "该类型的时间数据是否已经被记录(用于图表上会|cffff2020占用极大的内存|r,如果你比较在意内存占用的话)" L["Whisper"] = "密语" L["Whisper Target"] = "密语目标" L["Who"] = "谁" L["Window"] = "窗口" L["Window Color Selection"] = "窗口颜色选择" L["Window Options"] = "窗口选项" L["Window Scaling"] = "窗口缩放" L["X Gridlines Represent"] = "X 轴每格代表" L["Yes"] = "是"
mit
liruqi/bigfoot
Interface/AddOns/BigFoot/AceLibs/AceGUI-3.0-SharedMediaWidgets/StatusbarWidget.lua
2
6674
-- Widget is based on the AceGUIWidget-DropDown.lua supplied with AceGUI-3.0 -- Widget created by Yssaril local AceGUI = LibStub("AceGUI-3.0") local Media = LibStub("LibSharedMedia-3.0") local AGSMW = LibStub("AceGUISharedMediaWidgets-1.0") do local widgetType = "LSM30_Statusbar" local widgetVersion = 11 local contentFrameCache = {} local function ReturnSelf(self) self:ClearAllPoints() self:Hide() self.check:Hide() table.insert(contentFrameCache, self) end local function ContentOnClick(this, button) local self = this.obj self:Fire("OnValueChanged", this.text:GetText()) if self.dropdown then self.dropdown = AGSMW:ReturnDropDownFrame(self.dropdown) end end local function GetContentLine() local frame if next(contentFrameCache) then frame = table.remove(contentFrameCache) else frame = CreateFrame("Button", nil, UIParent) --frame:SetWidth(200) frame:SetHeight(18) frame:SetHighlightTexture([[Interface\QuestFrame\UI-QuestTitleHighlight]], "ADD") frame:SetScript("OnClick", ContentOnClick) local check = frame:CreateTexture("OVERLAY") check:SetWidth(16) check:SetHeight(16) check:SetPoint("LEFT",frame,"LEFT",1,-1) check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check") check:Hide() frame.check = check local bar = frame:CreateTexture("ARTWORK") bar:SetHeight(16) bar:SetPoint("LEFT",check,"RIGHT",1,0) bar:SetPoint("RIGHT",frame,"RIGHT",-1,0) frame.bar = bar local text = frame:CreateFontString(nil,"OVERLAY","GameFontWhite") local font, size = text:GetFont() text:SetFont(font,size,"OUTLINE") text:SetPoint("TOPLEFT", check, "TOPRIGHT", 3, 0) text:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -2, 0) text:SetJustifyH("LEFT") text:SetText("Test Test Test Test Test Test Test") frame.text = text frame.ReturnSelf = ReturnSelf end frame:Show() return frame end local function OnAcquire(self) self:SetHeight(44) self:SetWidth(200) end local function OnRelease(self) self:SetText("") self:SetLabel("") self:SetDisabled(false) self.value = nil self.list = nil self.open = nil self.hasClose = nil self.frame:ClearAllPoints() self.frame:Hide() end local function SetValue(self, value) -- Set the value to an item in the List. if self.list then self:SetText(value or "") end self.value = value end local function GetValue(self) return self.value end local function SetList(self, list) -- Set the list of values for the dropdown (key => value pairs) self.list = list or Media:HashTable("statusbar") end local function SetText(self, text) -- Set the text displayed in the box. self.frame.text:SetText(text or "") local statusbar = self.list[text] ~= text and self.list[text] or Media:Fetch('statusbar',text) self.bar:SetTexture(statusbar) end local function SetLabel(self, text) -- Set the text for the label. self.frame.label:SetText(text or "") end local function AddItem(self, key, value) -- Add an item to the list. self.list = self.list or {} self.list[key] = value end local SetItemValue = AddItem -- Set the value of a item in the list. <<same as adding a new item>> local function SetMultiselect(self, flag) end -- Toggle multi-selecting. <<Dummy function to stay inline with the dropdown API>> local function GetMultiselect() return false end-- Query the multi-select flag. <<Dummy function to stay inline with the dropdown API>> local function SetItemDisabled(self, key) end-- Disable one item in the list. <<Dummy function to stay inline with the dropdown API>> local function SetDisabled(self, disabled) -- Disable the widget. self.disabled = disabled if disabled then self.frame:Disable() else self.frame:Enable() end end local function textSort(a,b) return string.upper(a) < string.upper(b) end local sortedlist = {} local function ToggleDrop(this) local self = this.obj if self.dropdown then self.dropdown = AGSMW:ReturnDropDownFrame(self.dropdown) AceGUI:ClearFocus() else AceGUI:SetFocus(self) self.dropdown = AGSMW:GetDropDownFrame() local width = self.frame:GetWidth() self.dropdown:SetPoint("TOPLEFT", self.frame, "BOTTOMLEFT") self.dropdown:SetPoint("TOPRIGHT", self.frame, "BOTTOMRIGHT", width < 160 and (160 - width) or 0, 0) for k, v in pairs(self.list) do sortedlist[#sortedlist+1] = k end table.sort(sortedlist, textSort) for i, k in ipairs(sortedlist) do local f = GetContentLine() f.text:SetText(k) --print(k) if k == self.value then f.check:Show() end local statusbar = self.list[k] ~= k and self.list[k] or Media:Fetch('statusbar',k) f.bar:SetTexture(statusbar) f.obj = self f.dropdown = self.dropdown self.dropdown:AddFrame(f) end wipe(sortedlist) end end local function ClearFocus(self) if self.dropdown then self.dropdown = AGSMW:ReturnDropDownFrame(self.dropdown) end end local function OnHide(this) local self = this.obj if self.dropdown then self.dropdown = AGSMW:ReturnDropDownFrame(self.dropdown) end end local function Drop_OnEnter(this) this.obj:Fire("OnEnter") end local function Drop_OnLeave(this) this.obj:Fire("OnLeave") end local function Constructor() local frame = AGSMW:GetBaseFrame() local self = {} self.type = widgetType self.frame = frame frame.obj = self frame.dropButton.obj = self frame.dropButton:SetScript("OnEnter", Drop_OnEnter) frame.dropButton:SetScript("OnLeave", Drop_OnLeave) frame.dropButton:SetScript("OnClick",ToggleDrop) frame:SetScript("OnHide", OnHide) local bar = frame:CreateTexture(nil, "OVERLAY") bar:SetPoint("TOPLEFT", frame,"TOPLEFT",6,-25) bar:SetPoint("BOTTOMRIGHT", frame,"BOTTOMRIGHT", -21, 5) bar:SetAlpha(0.5) self.bar = bar self.alignoffset = 31 self.OnRelease = OnRelease self.OnAcquire = OnAcquire self.ClearFocus = ClearFocus self.SetText = SetText self.SetValue = SetValue self.GetValue = GetValue self.SetList = SetList self.SetLabel = SetLabel self.SetDisabled = SetDisabled self.AddItem = AddItem self.SetMultiselect = SetMultiselect self.GetMultiselect = GetMultiselect self.SetItemValue = SetItemValue self.SetItemDisabled = SetItemDisabled self.ToggleDrop = ToggleDrop AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion) end
mit
liruqi/bigfoot
Interface/AddOns/MySlot/libs/base64.lua
1
1282
-- 原作者 Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de> -- 修改使兼容byte seq table by T.G. <farmer1992@gmail.com> 2010 Oct 24 local base64 = LibStub:NewLibrary("BASE64-1.0", 1) local b ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' local function enc(data) local t = {} for _, x in pairs(data) do local r,b='',x for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end t[#t+1] = r end t[#t+1] = '0000' local r = {} table.concat(t):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return nil end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end r[#r+1] = b:sub(c+1,c+1) end) r[#r+1] = ({ '', '==', '=' })[#data%3+1] return table.concat(r) end -- decoding local function dec(data) data = string.gsub(data, '[^'..b..'=]', '') local t = {} data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(b:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return nil end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end t[#t+1] = c end) return t end base64.enc = enc base64.dec = dec
mit
ckaotik/ESO-Midget
libs/LibAddonMenu-2.0/controls/panel.lua
6
5022
--[[panelData = { type = "panel", name = "Window Title", displayName = "My Longer Window Title", --(optional) (can be useful for long addon names or if you want to colorize it) author = "Seerah", --(optional) version = "2.0", --(optional) slashCommand = "/myaddon", --(optional) will register a keybind to open to this panel (don't forget to include the slash!) registerForRefresh = true, --boolean (optional) (will refresh all options controls when a setting is changed and when the panel is shown) registerForDefaults = true, --boolean (optional) (will set all options controls back to default values) resetFunc = function() print("defaults reset") end, --(optional) custom function to run after settings are reset to defaults } ]] local widgetVersion = 8 local LAM = LibStub("LibAddonMenu-2.0") if not LAM:RegisterWidget("panel", widgetVersion) then return end local wm = WINDOW_MANAGER local cm = CALLBACK_MANAGER local function RefreshPanel(control) local panel = control.panel or control --callback can be fired by a single control or by the panel showing local panelControls = panel.controlsToRefresh for i = 1, #panelControls do local updateControl = panelControls[i] if updateControl ~= control then if updateControl.UpdateValue then updateControl:UpdateValue() end if updateControl.UpdateDisabled then updateControl:UpdateDisabled() end end end end local function ForceDefaults(panel) local panelControls = panel.controlsToRefresh for i = 1, #panelControls do local updateControl = panelControls[i] if updateControl.UpdateValue and updateControl.data.default ~= nil then updateControl:UpdateValue(true) end end if panel.data.resetFunc then panel.data.resetFunc() end cm:FireCallbacks("LAM-RefreshPanel", panel) end ESO_Dialogs["LAM_DEFAULTS"] = { title = { text = SI_OPTIONS_RESET_TITLE, }, mainText = { text = SI_OPTIONS_RESET_PROMPT, align = TEXT_ALIGN_CENTER, }, buttons = { [1] = { text = SI_OPTIONS_RESET, callback = function(dialog) ForceDefaults(dialog.data[1]) end, }, [2] = { text = SI_DIALOG_CANCEL, }, }, } local callbackRegistered = false LAMCreateControl.scrollCount = LAMCreateControl.scrollCount or 1 function LAMCreateControl.panel(parent, panelData, controlName) local control = wm:CreateTopLevelWindow(controlName) control:SetParent(parent) control.bg = wm:CreateControl(nil, control, CT_BACKDROP) local bg = control.bg bg:SetAnchorFill() bg:SetEdgeTexture("EsoUI\\Art\\miscellaneous\\borderedinsettransparent_edgefile.dds", 128, 16) bg:SetCenterColor(0, 0, 0, 0) control.label = wm:CreateControlFromVirtual(nil, control, "ZO_Options_SectionTitleLabel") local label = control.label label:SetAnchor(TOPLEFT, control, TOPLEFT, 10, 10) label:SetText(panelData.displayName and panelData.displayName or panelData.name) if panelData.author or panelData.version then control.info = wm:CreateControl(nil, control, CT_LABEL) local info = control.info info:SetFont("$(CHAT_FONT)|14|soft-shadow-thin") info:SetColor(ZO_HIGHLIGHT_TEXT:UnpackRGBA()) info:SetHeight(13) info:SetAnchor(TOPRIGHT, control, BOTTOMRIGHT, -5, 2) if panelData.author and panelData.version then --info:SetText("Version: "..panelData.version.." - "..GetString(SI_ADDON_MANAGER_AUTHOR)..": "..panelData.author) info:SetText(string.format("Version: %s - %s: %s", panelData.version, GetString(SI_ADDON_MANAGER_AUTHOR), panelData.author)) elseif panelData.author then info:SetText(string.format("%s: %s", GetString(SI_ADDON_MANAGER_AUTHOR), panelData.author)) else info:SetText("Version: "..panelData.version) end end control.container = wm:CreateControlFromVirtual("LAMAddonPanelContainer"..LAMCreateControl.scrollCount, control, "ZO_ScrollContainer") LAMCreateControl.scrollCount = LAMCreateControl.scrollCount + 1 local container = control.container container:SetAnchor(TOPLEFT, label, BOTTOMLEFT, 0, 20) container:SetAnchor(BOTTOMRIGHT, control, BOTTOMRIGHT, -3, -3) control.scroll = GetControl(control.container, "ScrollChild") control.scroll:SetResizeToFitPadding(0, 20) if panelData.registerForDefaults then control.defaultButton = wm:CreateControlFromVirtual(nil, control, "ZO_DefaultTextButton") local defaultButton = control.defaultButton defaultButton:SetFont("ZoFontDialogKeybindDescription") defaultButton:SetHorizontalAlignment(TEXT_ALIGN_LEFT) --defaultButton:SetText("Reset To Defaults") defaultButton:SetText(GetString(SI_OPTIONS_RESET_TITLE)) defaultButton:SetDimensions(200, 30) defaultButton:SetAnchor(TOPLEFT, control, BOTTOMLEFT, 0, 2) defaultButton:SetHandler("OnClicked", function() ZO_Dialogs_ShowDialog("LAM_DEFAULTS", {control}) end) end if panelData.registerForRefresh and not callbackRegistered then --don't want to register our callback more than once cm:RegisterCallback("LAM-RefreshPanel", RefreshPanel) callbackRegistered = true end control.data = panelData control.controlsToRefresh = {} return control end
mit
ingran/balzac
custom_feeds/teltonika_luci/libs/web/luasrc/http.lua
1
8222
--[[ LuCI - HTTP-Interaction Description: HTTP-Header manipulator and form variable preprocessor FileId: $Id: http.lua 8573 2012-04-16 16:48:59Z jow $ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local ltn12 = require "luci.ltn12" local protocol = require "luci.http.protocol" local util = require "luci.util" local string = require "string" local coroutine = require "coroutine" local table = require "table" local ipairs, pairs, next, type, tostring, error = ipairs, pairs, next, type, tostring, error --- LuCI Web Framework high-level HTTP functions. module "luci.http" context = util.threadlocal() Request = util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler self.filehandler = function() end -- HTTP-Message table self.message = { env = env, headers = {}, params = protocol.urldecode_params(env.QUERY_STRING or ""), } self.parsed_input = false end function Request.formvalue(self, name, noparse) if not noparse and not self.parsed_input then self:_parse_input() end if name then return self.message.params[name] else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." if not self.parsed_input then self:_parse_input() end local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.content(self) if not self.parsed_input then self:_parse_input() end return self.message.content, self.message.content_length end function Request.getcookie(self, name) local c = string.gsub(";" .. (self:getenv("HTTP_COOKIE") or "") .. ";", "%s*;%s*", ";") local p = ";" .. name .. "=(.-);" local i, j, value = c:find(p) return value and urldecode(value) end function Request.getenv(self, name) if name then return self.message.env[name] else return self.message.env end end function Request.setfilehandler(self, callback) self.filehandler = callback end function Request._parse_input(self) protocol.parse_message_body( self.input, self.message, self.filehandler ) self.parsed_input = true end --- Close the HTTP-Connection. function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end --- Return the request content if the request was of unknown type. -- @return HTTP request body -- @return HTTP request body length function content() return context.request:content() end --- Get a certain HTTP input value or a table of all input values. -- @param name Name of the GET or POST variable to fetch -- @param noparse Don't parse POST data before getting the value -- @return HTTP input value or table of all input value function formvalue(name, noparse) return context.request:formvalue(name, noparse) end --- Get a table of all HTTP input values with a certain prefix. -- @param prefix Prefix -- @return Table of all HTTP input values with given prefix function formvaluetable(prefix) return context.request:formvaluetable(prefix) end --- Get the value of a certain HTTP-Cookie. -- @param name Cookie Name -- @return String containing cookie data function getcookie(name) return context.request:getcookie(name) end --- Get the value of a certain HTTP environment variable -- or the environment table itself. -- @param name Environment variable -- @return HTTP environment value or environment table function getenv(name) return context.request:getenv(name) end --- Set a handler function for incoming user file uploads. -- @param callback Handler function function setfilehandler(callback) return context.request:setfilehandler(callback) end --- Send a HTTP-Header. -- @param key Header key -- @param value Header value function header(key, value) if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end --- Set the mime type of following content data. -- @param mime Mimetype of following content function prepare_content(mime) if not context.headers or not context.headers["content-type"] then if mime == "application/xhtml+xml" then if not getenv("HTTP_ACCEPT") or not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then mime = "text/html; charset=UTF-8" end header("Vary", "Accept") end header("Content-Type", mime) end end --- Get the RAW HTTP input source -- @return HTTP LTN12 source function source() return context.request.input end --- Set the HTTP status code and status message. -- @param code Status code -- @param message Status message function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end --- Send a chunk of content data to the client. -- This function is as a valid LTN12 sink. -- If the content chunk is nil this function will automatically invoke close. -- @param content Content chunk -- @param src_err Error object from source (optional) -- @see close function write(content, src_err) if not content then if src_err then error(src_err) else close() end return true elseif #content == 0 then return true else if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end if not context.headers["cache-control"] then header("Cache-Control", "no-cache") header("Expires", "0") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) return true end end --- Splice data from a filedescriptor to the client. -- @param fp File descriptor -- @param size Bytes to splice (optional) function splice(fd, size) coroutine.yield(6, fd, size) end --- Redirects the client to a new URL and closes the connection. -- @param url Target URL function redirect(url) status(302, "Found") header("Location", url) close() end --- Create a querystring out of a table of key - value pairs. -- @param table Query string source table -- @return Encoded HTTP query string function build_querystring(q) local s = { "?" } for k, v in pairs(q) do if #s > 1 then s[#s+1] = "&" end s[#s+1] = urldecode(k) s[#s+1] = "=" s[#s+1] = urldecode(v) end return table.concat(s, "") end --- Return the URL-decoded equivalent of a string. -- @param str URL-encoded string -- @param no_plus Don't decode + to " " -- @return URL-decoded string -- @see urlencode urldecode = protocol.urldecode --- Return the URL-encoded equivalent of a string. -- @param str Source string -- @return URL-encoded string -- @see urldecode urlencode = protocol.urlencode --- Send the given data as JSON encoded string. -- @param data Data to send function write_json(x) if x == nil then write("null") elseif type(x) == "table" then local k, v if type(next(x)) == "number" then write("[ ") for k, v in ipairs(x) do write_json(v) if next(x, k) then write(", ") end end write(" ]") else write("{ ") for k, v in pairs(x) do write("%q: " % k) write_json(v) if next(x, k) then write(", ") end end write(" }") end elseif type(x) == "number" or type(x) == "boolean" then if (x ~= x) then -- NaN is the only value that doesn't equal to itself. write("Number.NaN") else write(tostring(x)) end elseif type(x) == "string" then write("%q" % tostring(x)) end end
gpl-2.0
sduponch/overthebox-feeds
otb-luci-swconfig/files/usr/lib/lua/luci/controller/otb_swconfig.lua
3
1664
-- vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 : module("luci.controller.otb_swconfig", package.seeall) function index() local has_switch = false local uci = require("luci.model.uci").cursor() uci:foreach("network", "switch", function(s) if s.name == 'otbv2sw' then has_switch = true return end end) if has_switch then entry({"admin", "overthebox", "switch"}, template("otb_swconfig"), "Switch", 30) entry({"admin", "overthebox", "switch_config"}, call("switch_config")).dependent = false entry({"admin", "overthebox", "switch_reset"}, call("switch_reset")).dependent = false end end function switch_config() local data = {} local uci = require("luci.model.uci").cursor() uci:foreach("network", "switch_vlan", function(s) if not (s["device"] == 'otbv2sw') then return end local vlan = tonumber(s.vlan) local ports if s.ports then ports = string.split(s.ports, " ") end -- LAN local portType = "wan" if vlan == 2 then portType = "lan" end for i, port in ipairs(ports) do -- Check if the port is tagged local taggedValue = false if string.find(port, "t") then port = string.match(port,"(%d+)t") taggedValue = true end if not data[port] then data[port] = { type = portType, tagged = taggedValue } end end end) luci.http.prepare_content("application/json") luci.http.write_json(data) end function switch_reset() local wans = luci.http.formvalue("wans") if os.execute("swconfig-reset "..wans) then luci.http.status(200, "OK") else luci.http.status(500, "ERROR") end end
gpl-3.0
liruqi/bigfoot
Interface/AddOns/Bartender4/locale/enUS.lua
1
12790
-- Bartender4 Locale -- Please use the Localization App on WoWAce to Update this -- http://www.wowace.com/projects/bartender4/localization/ ;¶ local debug = false --[===[@debug@ debug = true --@end-debug@]===] local L = LibStub("AceLocale-3.0"):NewLocale("Bartender4", "enUS", true, debug) L[ [=["None" as modifier means its always active, and no modifier is required. Remember to enable Mouse-Over Casting for the individual bars, on the "State Configuration" tab, if you want it to be active for a specific bar.]=] ] = true L["|cffff0000WARNING|cffffffff: Pressing the button will reset your complete profile! If you're not sure about this, create a new profile and use that to experiment."] = true L["|cffffff00Click|r to toggle bar lock"] = true L["|cffffff00Right-click|r to open the options menu"] = true L["ActionBar Paging"] = true L["Alpha"] = true L["ALT"] = true L["Alternatively, you can also find us on |cffffff78irc://irc.freenode.org/wowace|r"] = true L["Always Hide"] = true L["Anchor"] = true L["Apply Preset"] = true L["Artifact Power Bar"] = true L["Auto-Assist Casting"] = true L["Bag Bar"] = true L["Bar %s"] = true L["Bar Options"] = true L["Bar Paging"] = true L["Bar Snapping"] = true L["Bar Style & Layout"] = true L["Bars"] = true L["Bars unlocked. Move them now and click Lock when you are done."] = true L["Bartender4"] = true L["Bartender4 only converts the bindings of Bar1 to be directly usable, all other Bars will have to be re-bound to the Bartender4 keys. A direct indicator if your key-bindings are setup correctly is the hotkey display on the buttons. If the key-bindings shows correctly on your button, everything should work fine as well."] = true L["Bartender4 was written by Nevcairiel of EU-Antonidas. He will accept cookies as compensation for his hard work!"] = true L["Blizzard Art"] = true L["Blizzard Art Bar"] = true L["Blizzard interface"] = true L["Button %s"] = true L["Button Grid"] = true L["Button Lock"] = true L["Button Look"] = true L["Button Tooltip"] = true L["Buttons"] = true L["Cannot access options during combat."] = true L["Center Horizontally"] = true L["Center Vertically"] = true L["Centers the bar horizontally on screen."] = true L["Centers the bar vertically on screen."] = true L["Change the current anchor point of the bar."] = true L["Choose between the classic WoW layout and two variations"] = true L["Choose the ending to the left"] = true L["Choose the ending to the right"] = true L["Classic"] = true L["Click-Through"] = true L["Colors"] = true L["Configure the Stance Bar"] = true L["Configure actionbar paging when the %s key is down."] = true L["Configure all of Bartender to preset defaults"] = true L["Configure Bar %s"] = true L["Configure how the Out of Range Indicator should display on the buttons."] = true L["Configure the alpha of the bar."] = true L["Configure the Artifact Power Bar"] = true L["Configure the Bag Bar"] = true L["Configure the Blizzard Art Bar"] = true L["Configure the Button Tooltip."] = true L["Configure the Extra Action Bar"] = true L["Configure the Fade Out Alpha"] = true L["Configure the Fade Out Delay"] = true L["Configure the Micro Menu"] = true L["Configure the padding of the buttons."] = true L["Configure the Pet Bar"] = true L["Configure the Reputation Bar"] = true L["Configure the scale of the bar."] = true L["Configure the VehicleBar"] = true L["Configure the XP Bar"] = true L["Configure the Zone Ability Bar"] = true L["Copy Conditionals"] = true L["Create a copy of the auto-generated conditionals in the custom configuration as a base template."] = true L["CTRL"] = true L["Custom Conditionals"] = true L["Default Bar State"] = true L["Direction of the button flyouts on this bar (eg. summon demon/pet)"] = true L["Disable any reaction to mouse events on this bar, making the bar click-through."] = true L["Disabled"] = true L["Disabled in Combat"] = true L["Don't Page"] = true L["Down"] = true L["Empty button background"] = true L[ [=[Enable Auto-Assist for this bar. Auto-Assist will automatically try to cast on your target's target if your target is no valid target for the selected spell.]=] ] = true L[ [=[Enable Bar Switching based on the actionbar controls provided by the game. See Blizzard Key Bindings for assignments - Usually Shift-Mouse Wheel and Shift+1 - Shift+6.]=] ] = true L[ [=[Enable Mouse-Over Casting for this bar. Mouse-Over Casting will automatically cast onto the unit under your mouse without targeting it, if possible.]=] ] = true L["Enable State-based Button Swaping"] = true L["Enable the Artifact Power Bar"] = true L["Enable the Bag Bar"] = true L["Enable the Blizzard Art Bar"] = true L["Enable the Extra Action Bar"] = true L["Enable the FadeOut mode"] = true L["Enable the Micro Menu"] = true L["Enable the PetBar"] = true L["Enable the Reputation Bar"] = true L["Enable the StanceBar"] = true L["Enable the use of a custom condition, disabling all of the above."] = true L["Enable the use of the Blizzard Vehicle UI, hiding any Bartender4 bars in the meantime."] = true L["Enable the Vehicle Bar"] = true L["Enable the XP Bar"] = true L["Enable the Zone Ability Bar"] = true L["Enable/Disable the bar."] = true L["Enabled"] = true L["Extra Action Bar"] = true L["Fade Out"] = true L["Fade Out Alpha"] = true L["Fade Out Delay"] = true L["FAQ"] = true L["Flyout Direction"] = true L["Focus-Cast by modifier"] = true L["Focus-Cast Modifier"] = true L["Frequently Asked Questions"] = true L["Full Button Mode"] = true L["Full reset"] = true L["General Settings"] = true L["Griffin"] = true L["Hide Equipped Border"] = true L["Hide Hotkey"] = true L["Hide in Combat"] = true L["Hide in Stance/Form"] = true L["Hide Macro Text"] = true L["Hide on Vehicle"] = true L["Hide out of Combat"] = true L["Hide the Hotkey on the buttons of this bar."] = true L["Hide the inner border indicating the equipped status on the buttons of this bar."] = true L["Hide the Macro Text on the buttons of this bar."] = true L["Hide this bar in a specific Stance or Form."] = true L["Hide this bar when a override bar is active."] = true L["Hide this bar when the game wants to show a vehicle UI."] = true L["Hide this bar when you are possessing a NPC."] = true L["Hide this bar when you are riding on a vehicle."] = true L["Hide this bar when you have a pet."] = true L["Hide this bar when you have no pet."] = true L["Hide when Possessing"] = true L["Hide with Override Bar"] = true L["Hide with pet"] = true L["Hide with Vehicle UI"] = true L["Hide without pet"] = true L["Horizontal Growth"] = true L["Horizontal growth direction for this bar."] = true L["Hotkey Mode"] = true L["How do I change the Bartender4 Keybindings then?"] = true L["I just installed Bartender4, but my keybindings do not show up on the buttons/do not work."] = true L["I've found a bug! Where do I report it?"] = true L["Key Bindings"] = true L["Layout"] = true L["Left"] = true L["Left ending"] = true L["Lion"] = true L["Lock"] = true L["Lock all bars."] = true L["Lock the buttons."] = true L["Micro Menu"] = true L["Minimap Icon"] = true L["Modifier Based Switching"] = true L["Mouse-Over Casting"] = true L["Mouse-Over casting can be limited to be only active when a modifier key is being held down. You can configure the modifier in the global \"Bar\" Options."] = true L["Mouse-Over Casting Modifier"] = true L["No Display"] = true L["No Stance/Form"] = true L["None"] = true L["Note: Enabling Custom Conditionals will disable all of the above settings!"] = true L["Number of buttons."] = true L["Number of rows."] = true L["Offset in X direction (horizontal) from the given anchor point."] = true L["Offset in Y direction (vertical) from the given anchor point."] = true L["Once open, simply hover the button you want to bind, and press the key you want to be bound to that button. The keyBound tooltip and on-screen status will inform you about already existing bindings to that button, and the success of your binding attempt."] = true L["One action bar only"] = true L["One Bag"] = true L["Only show one Bag Button in the BagBar."] = true L["Out of Mana Indicator"] = true L["Out of Range Indicator"] = true L["Padding"] = true L["Page %2d"] = true L["Pet Bar"] = true L["Positioning"] = true L["Possess Bar"] = true L["Presets"] = true L["Reputation Bar"] = true L["Reset Position"] = true L["Reset the position of this bar completly if it ended up off-screen and you cannot reach it anymore."] = true L["Right"] = true L["Right ending"] = true L["Right-click Self-Cast"] = true L["Rows"] = true L["Scale"] = true L["Select a modifier for Mouse-Over Casting"] = true L["Select the Focus-Cast Modifier"] = true L["Select the Self-Cast Modifier"] = true L["Self-Cast by modifier"] = true L["Self-Cast Modifier"] = true L["SHIFT"] = true L["Show a Icon to open the config at the Minimap"] = true L["Show Artifact Power Bar"] = true L["Show Reputation Bar"] = true L["Show XP Bar"] = true L["Smart Target selection"] = true L["Specify the Color of the Out of Mana Indicator"] = true L["Specify the Color of the Out of Range Indicator"] = true L["Stance Bar"] = true L["Stance Configuration"] = true L["State Configuration"] = true L["Switch this bar to the Possess Bar when possessing a npc (eg. Mind Control)"] = true L["Switch to key-binding mode"] = true L["The background of button places where no buttons are placed"] = true L["The bar default is to be visible all the time, you can configure conditions here to control when the bar should be hidden."] = true L["The default behaviour of this bar when no state-based paging option affects it."] = true L["The Positioning options here will allow you to position the bar to your liking and with an absolute precision."] = true L["These options can automatically select a different target for your spell, based on macro conditions. Note however that they will overrule any target changes from normal macros."] = true L["This bar will be hidden once you enter combat."] = true L["This bar will be hidden whenever you are not in combat."] = true L["Three bars stacked"] = true L["Toggle actions on key press instead of release"] = true L[ [=[Toggle Button Zoom For more style options you need to install ButtonFacade]=] ] = true L["Toggle the button grid."] = true L["Toggle the use of the modifier-based focus-cast functionality."] = true L["Toggle the use of the modifier-based self-cast functionality."] = true L["Toggle the use of the right-click self-cast functionality."] = true L["Toggles actions immediately when you press the key, and not only on release. Note that draging actions will cause them to be cast in this mode."] = true L["Two action bars"] = true L["Two bars wide"] = true L["Up"] = true L["Use Blizzard Vehicle UI"] = true L["Use Custom Condition"] = true L["Vehicle Bar"] = true L["VehicleBar"] = true L["Vertical Growth"] = true L["Vertical growth direction for this bar."] = true L["Visibility"] = true L["When reporting a bug, make sure you include the |cffffff78steps on how to reproduce the bug|r, supply any |cffffff78error messages|r with stack traces if possible, give the |cffffff78revision number|r of Bartender4 the problem occured in and state whether you are using an |cffffff78English client or otherwise|r."] = true L["Who wrote this cool addon?"] = true L["X Offset"] = true L["XP Bar"] = true L["Y Offset"] = true L["You can either click the KeyBound button in the options, or use the |cffffff78/kb|r chat command to open the keyBound control. Alternatively, you can also use the Blizzard Keybinding Interface."] = true L["You can report bugs or give suggestions at the discussion forums at |cffffff78http://forums.wowace.com/showthread.php?t=12513|r or check the project page at |cffffff78http://www.wowace.com/addons/bartender4/|r"] = true L["You can set the bar to be always hidden, if you only wish to access it using key-bindings."] = true L[ [=[You can use any macro conditionals in the custom string, using "show" and "hide" as values. Example: [combat]hide;show]=] ] = true L[ [=[You can use any macro conditionals in the custom string, using the number of the bar as target value. Example: [form:1]9;0]=] ] = true L["You can use the preset defaults as a starting point for setting up your interface. Just choose your preferences here and click the button below to reset your profile to the preset default. Note that not all defaults show all bars."] = true L["You have to exit the vehicle in order to be able to change the Vehicle UI settings."] = true L["Zone Ability Bar"] = true L["Zoom"] = true
mit
klukonin/nodemcu-firmware
lua_examples/http_server.lua
53
3696
-- -- Simple NodeMCU web server (done is a not so nodeie fashion :-) -- -- Highly modified by Bruce Meacham, based on work by Scott Beasley 2015 -- Open and free to change and use. Enjoy. [Beasley/Meacham 2015] -- -- Meacham Update: I streamlined/improved the parsing to focus on simple HTTP GET request and their simple parameters -- Also added the code to drive a servo/light. Comment out as you see fit. -- -- Usage: -- Change SSID and SSID_PASSPHRASE for your wifi network -- Download to NodeMCU -- node.compile("http_server.lua") -- dofile("http_server.lc") -- When the server is esablished it will output the IP address. -- http://{ip address}/?s0=1200&light=1 -- s0 is the servo position (actually the PWM hertz), 500 - 2000 are all good values -- light chanel high(1)/low(0), some evaluation boards have LEDs pre-wired in a "pulled high" confguration, so '0' ground the emitter and turns it on backwards. -- -- Add to init.lua if you want it to autoboot. -- -- Your Wifi connection data local SSID = "YOUR WIFI SSID" local SSID_PASSWORD = "YOUR SSID PASSPHRASE" -- General setup local pinLight = 2 -- this is GPIO4 gpio.mode(pinLight,gpio.OUTPUT) gpio.write(pinLight,gpio.HIGH) servo = {} servo.pin = 4 --this is GPIO2 servo.value = 1500 servo.id = "servo" gpio.mode(servo.pin, gpio.OUTPUT) gpio.write(servo.pin, gpio.LOW) -- This alarm drives the servo tmr.alarm(0,10,1,function() -- 50Hz if servo.value then -- generate pulse gpio.write(servo.pin, gpio.HIGH) tmr.delay(servo.value) gpio.write(servo.pin, gpio.LOW) end end) local function connect (conn, data) local query_data conn:on ("receive", function (cn, req_data) params = get_http_req (req_data) cn:send("HTTP/1.1 200/OK\r\nServer: NodeLuau\r\nContent-Type: text/html\r\n\r\n") cn:send ("<h1>ESP8266 Servo &amp; Light Server</h1>\r\n") if (params["light"] ~= nil) then if ("0" == params["light"]) then gpio.write(pinLight, gpio.LOW) else gpio.write(pinLight, gpio.HIGH) end end if (params["s0"] ~= nil) then servo.value = tonumber(params["s0"]); end -- Close the connection for the request cn:close ( ) end) end -- Build and return a table of the http request data function get_http_req (instr) local t = {} local str = string.sub(instr, 0, 200) local v = string.gsub(split(str, ' ')[2], '+', ' ') parts = split(v, '?') local params = {} if (table.maxn(parts) > 1) then for idx,part in ipairs(split(parts[2], '&')) do parmPart = split(part, '=') params[parmPart[1]] = parmPart[2] end end return params end -- Source: http://lua-users.org/wiki/MakingLuaLikePhp -- Credit: http://richard.warburton.it/ function split(str, splitOn) if (splitOn=='') then return false end local pos,arr = 0,{} for st,sp in function() return string.find(str,splitOn,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) pos = sp + 1 end table.insert(arr,string.sub(str,pos)) return arr end -- Configure the ESP as a station (client) wifi.setmode (wifi.STATION) wifi.sta.config (SSID, SSID_PASSWORD) wifi.sta.autoconnect (1) -- Hang out until we get a wifi connection before the httpd server is started. tmr.alarm (1, 800, 1, function ( ) if wifi.sta.getip ( ) == nil then print ("Waiting for Wifi connection") else tmr.stop (1) print ("Config done, IP is " .. wifi.sta.getip ( )) end end) -- Create the httpd server svr = net.createServer (net.TCP, 30) -- Server listening on port 80, call connect function if a request is received svr:listen (80, connect)
mit
borromeotlhs/nodemcu-firmware
lua_examples/http_server.lua
53
3696
-- -- Simple NodeMCU web server (done is a not so nodeie fashion :-) -- -- Highly modified by Bruce Meacham, based on work by Scott Beasley 2015 -- Open and free to change and use. Enjoy. [Beasley/Meacham 2015] -- -- Meacham Update: I streamlined/improved the parsing to focus on simple HTTP GET request and their simple parameters -- Also added the code to drive a servo/light. Comment out as you see fit. -- -- Usage: -- Change SSID and SSID_PASSPHRASE for your wifi network -- Download to NodeMCU -- node.compile("http_server.lua") -- dofile("http_server.lc") -- When the server is esablished it will output the IP address. -- http://{ip address}/?s0=1200&light=1 -- s0 is the servo position (actually the PWM hertz), 500 - 2000 are all good values -- light chanel high(1)/low(0), some evaluation boards have LEDs pre-wired in a "pulled high" confguration, so '0' ground the emitter and turns it on backwards. -- -- Add to init.lua if you want it to autoboot. -- -- Your Wifi connection data local SSID = "YOUR WIFI SSID" local SSID_PASSWORD = "YOUR SSID PASSPHRASE" -- General setup local pinLight = 2 -- this is GPIO4 gpio.mode(pinLight,gpio.OUTPUT) gpio.write(pinLight,gpio.HIGH) servo = {} servo.pin = 4 --this is GPIO2 servo.value = 1500 servo.id = "servo" gpio.mode(servo.pin, gpio.OUTPUT) gpio.write(servo.pin, gpio.LOW) -- This alarm drives the servo tmr.alarm(0,10,1,function() -- 50Hz if servo.value then -- generate pulse gpio.write(servo.pin, gpio.HIGH) tmr.delay(servo.value) gpio.write(servo.pin, gpio.LOW) end end) local function connect (conn, data) local query_data conn:on ("receive", function (cn, req_data) params = get_http_req (req_data) cn:send("HTTP/1.1 200/OK\r\nServer: NodeLuau\r\nContent-Type: text/html\r\n\r\n") cn:send ("<h1>ESP8266 Servo &amp; Light Server</h1>\r\n") if (params["light"] ~= nil) then if ("0" == params["light"]) then gpio.write(pinLight, gpio.LOW) else gpio.write(pinLight, gpio.HIGH) end end if (params["s0"] ~= nil) then servo.value = tonumber(params["s0"]); end -- Close the connection for the request cn:close ( ) end) end -- Build and return a table of the http request data function get_http_req (instr) local t = {} local str = string.sub(instr, 0, 200) local v = string.gsub(split(str, ' ')[2], '+', ' ') parts = split(v, '?') local params = {} if (table.maxn(parts) > 1) then for idx,part in ipairs(split(parts[2], '&')) do parmPart = split(part, '=') params[parmPart[1]] = parmPart[2] end end return params end -- Source: http://lua-users.org/wiki/MakingLuaLikePhp -- Credit: http://richard.warburton.it/ function split(str, splitOn) if (splitOn=='') then return false end local pos,arr = 0,{} for st,sp in function() return string.find(str,splitOn,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) pos = sp + 1 end table.insert(arr,string.sub(str,pos)) return arr end -- Configure the ESP as a station (client) wifi.setmode (wifi.STATION) wifi.sta.config (SSID, SSID_PASSWORD) wifi.sta.autoconnect (1) -- Hang out until we get a wifi connection before the httpd server is started. tmr.alarm (1, 800, 1, function ( ) if wifi.sta.getip ( ) == nil then print ("Waiting for Wifi connection") else tmr.stop (1) print ("Config done, IP is " .. wifi.sta.getip ( )) end end) -- Create the httpd server svr = net.createServer (net.TCP, 30) -- Server listening on port 80, call connect function if a request is received svr:listen (80, connect)
mit
liruqi/bigfoot
Interface/AddOns/MySlot/libs/lua-pb/pb/standard/message.lua
1
8142
-- Copyright (c) 2011, Robert G. Jakabosky <bobby@sharedrealm.com> All rights reserved. local _require = LibStub:GetLibrary('pblua.require') local require = _require.require local _M = LibStub:NewLibrary("pblua.message", 1) local error = error local assert = assert local tostring = tostring local setmetatable = setmetatable local rawget = rawget local mod_path = string.match(...,".*%.") or '' local repeated = require(mod_path .. "repeated") local new_repeated = repeated.new local buffer = require(mod_path .. "buffer") local new_buffer = buffer.new local unknown = require(mod_path .. "unknown") local new_unknown = unknown.new local mod_parent_path = mod_path:match("(.*%.)[^.]*%.") or '' local utils = require(mod_parent_path .. "utils") local copy = utils.copy --local _M = {} local basic_types = { -- Varint types int32 = true, int64 = true, uint32 = true, uint64 = true, sint32 = true, sint64 = true, bool = true, -- 64-bit fixed fixed64 = true, sfixed64 = true, double = true, -- Length-delimited string = true, bytes = true, -- 32-bit fixed fixed32 = true, sfixed32 = true, float = true, } local msg_tag = {} local function new_message(mt, data) -- check if data is already a message of this type. if data and data[msg_tag] == mt then return data end -- create new message. local msg = setmetatable({ ['.data'] = {}}, mt) -- if data is nil, then message is empty. if not data then return msg end -- copy data into message local fields = mt.fields for i=1,#fields do local field = fields[i] local name = field.name local value = data[name] if value then msg[name] = value end end return msg end _M.new = new_message function _M.def(parent, name, ast) local methods = {} local fields = copy(ast.fields) local tags = {} -- create Metatable for Message/Group. local is_group = (ast['.type'] == 'group') local mt = { name = name, is_message = not is_group, is_group = is_group, fields = fields, methods = methods, tags = tags, extensions = copy(ast.extensions), -- hid this metatable. __metatable = false, } function mt.__index(msg, name) local data = rawget(msg, '.data') -- field data. -- get field value. local value = data[name] -- field is already set, just return the value if value then return value end -- check field for a default value. local field = fields[name] -- field info. if field then return field.default end -- check methods local method = methods[name] if method then return method end -- check for unknown field. if name == 'unknown_fields' then -- create Unknown field set object value = new_unknown() data.unknown_fields = value return value end -- check for special 'msg_tag' if name == msg_tag then -- return metatable. This is for message type validation. return mt end error("Invalid field:" .. name) end function mt.__newindex(msg, name, value) local data = rawget(msg, '.data') -- field data. -- get field info. local field = fields[name] if not field then error("Invalid field:" .. name) end if value then -- check if field is a message/group local new = field.new if new then value = new(value) end end data[name] = value end function mt.__tostring(msg) local data = rawget(msg, '.data') -- field data. local str = tostring(data) return str:gsub('table', name) end -- create message contructor local function new_msg(data) return new_message(mt, data) end mt.new = new_msg -- process fields for i=1,#fields do local field = fields[i] -- field rule to 'is_<rule>' mapping. field['is_' .. field.rule] = true -- check if the field is a basic type. if basic_types[field.ftype] then -- basic type field.is_basic = true else -- field is a user type, it needs to be resolved. field.need_resolve = true end end -- Type methods if is_group then -- store group tag in metatable. mt.tag = ast.tag else -- top-level message Serialize/Parse functions function methods:SerializePartial(format, depth) format = format or 'binary' local encode = mt.encode[format] if not encode then return false, "Unsupported serialization format: " .. format end return encode(self, depth) end function methods:Merge(data, format, off) format = format or 'binary' local decode = mt.decode[format] if not decode then return false, "Unsupported serialization format: " .. format end return decode(self, data, off or 1) end function methods:Serialize(format, depth) -- validate message before serialization. local init, errmsg = self:IsInitialized() if not init then return init, errmsg end -- now serialize message return self:SerializePartial(format, depth) end function methods:ParsePartial(data, format, off) -- Clear message before parsing it. self:Clear() -- Merge message data into empty message. return self:Merge(data, format, off) end function methods:Parse(data, format, off) -- Clear message before parsing it. self:Clear() -- Merge message data into empty message. local msg, off_err = self:Merge(data, format, off) if not msg then return msg, off_err end -- validate message. local init, errmsg = self:IsInitialized() if not init then return init, errmsg end return msg, off_err end end -- common methods. -- Clear() function methods:Clear() local data = rawget(self, '.data') -- field data. for i=1,#fields do local field = fields[i] data[field.name] = nil end end -- IsInitialized() function methods:IsInitialized() local data = rawget(self, '.data') -- field data. for i=1,#fields do local field = fields[i] local name = field.name local val = data[name] if val then -- check if group/message/repeated fields are intializied if field.is_complex then local init, errmsg = val:IsInitialized() if not init then return init, errmsg end end elseif field.is_required then return false, "Missing required field: " .. name end end -- this group/message is intialized. return true end -- MergeFrom() function methods:MergeFrom(msg2) local data = rawget(self, '.data') -- field data. This is for raw field access. for i=1,#fields do local field = fields[i] local name = field.name local val2 = msg2[name] if val2 then -- check if field is a group/message/repeated if field.is_complex then local val = data[name] -- create new group/message if field is nil. if not val then val = field.new() data[name] = val end -- merge sub group/message. val:MergeFrom(val2) else -- simple value, just copy it. data[name] = val2 end end end end -- CopyFrom() function methods:CopyFrom(msg2) -- first clear this message. self:Clear() -- then merge new data. self:MergeFrom(msg2) end return mt end function _M.compile(node, mt, fields) local tags = mt.tags for i=1,#fields do local field = fields[i] -- packed arrays have a length field.has_length = field.is_packed -- get field tag local tag = field.tag -- check if the field is a user type local user_type_mt = field.user_type_mt if user_type_mt then -- get new function from metatable. field.new = user_type_mt.new if field.is_group then field.is_complex = true elseif user_type_mt.is_enum then field.is_enum = true else field.has_length = true field.is_message = true field.is_complex = true end elseif field.is_packed then -- packed basic type field.is_basic = true else -- basic type field.is_basic = true end -- if field is repeated, then create a new 'repeated' type for it. if field.is_repeated then field.new = new_repeated(field) field.is_complex = true end tags[tag] = field end end return _M
mit
ingran/balzac
custom_feeds/teltonika_luci/applications/luci-load_balancing/luasrc/controller/balancing.lua
1
2190
module("luci.controller.balancing", package.seeall) function index() if not nixio.fs.access("/etc/config/load_balancing") then return end entry({"admin", "network", "balancing"}, alias("admin", "network", "balancing", "configuration"), _("Load Balancing"), 600) entry({"admin", "network", "balancing", "configuration"}, cbi("load_balancing/load_balancing_interface")) entry({"admin", "network", "balancing", "policy"}, cbi("load_balancing/load_balancing_policyconfig")).leaf = true entry({"admin", "network", "balancing", "rule"}, cbi("load_balancing/load_balancing_ruleconfig")).leaf = true entry({"admin", "network", "balancing", "status"}, call("load_balancing_status")) end function load_balancing_status() local uci = require "luci.model.uci".cursor() local names = { {ifname="3g-ppp", genName="Mobile", type="3G"}, {ifname="eth2", genName="Mobile", type="3G"}, {ifname="usb0", genName="WiMAX", type="WiMAX"}, {ifname="eth1", genName="Wired", type="vlan"}, {ifname="wlan0", genName="WiFi", type="wifi"}, {ifname="none", genName="Mobile bridged", type="3G"}, {ifname="wwan0", genName="Mobile", type="3G"}, {ifname="wm0", genName="WiMAX", type="WiMAX"}, } local interface, status, usage, name, ifname output = assert (io.popen("/usr/sbin/load_balancing interfaces")) interfaces = {} policies = {} for line in output:lines() do interface = line:match("wa%w+") if interface then ifname = uci:get("network", interface, "ifname") for n, i in ipairs(names) do if i.ifname == ifname then name = i.genName end end status = line:match("%w+$") if status then table.insert(interfaces, { interface = interface, status = status, name = name}) end end end output:close() output = assert (io.popen("/usr/sbin/load_balancing policies")) for line in output:lines() do interface = line:match("wa%w+") if interface then usage = line:match("%d+%%") if status then table.insert(policies, { interface = interface, usage = usage}) end end end output:close() rv = { interfaces = interfaces, policies = policies } luci.http.prepare_content("application/json") luci.http.write_json(rv) end
gpl-2.0
liruqi/bigfoot
Interface/AddOns/DBM-Challenges/LegionArtifacts/Healer.lua
1
5036
local mod = DBM:NewMod("ArtifactHealer", "DBM-Challenges", 2) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 84 $"):sub(12, -3)) mod:SetZone()--Healer (1710), Tank (1698), DPS (1703-The God-Queen's Fury), DPS (Fel Totem Fall) mod:RegisterEvents( "SPELL_AURA_APPLIED 235984 237188", "SPELL_AURA_APPLIED_DOSE 235833", "UNIT_DIED" -- "UNIT_SPELLCAST_SUCCEEDED boss1 boss2 boss3 boss4 boss5",--need all 5? -- "SCENARIO_UPDATE" ) mod.noStatistics = true --Notes: --TODO, all. mapids, mob iDs, win event to stop timers (currently only death event stops them) --Healer -- Need ignite soul equiv name/ID. -- Need fear name/Id local warnArcaneBlitz = mod:NewStackAnnounce(235833, 2) local specWarnManaSling = mod:NewSpecialWarningMoveTo(235984, nil, nil, nil, 1, 2) local specWarnArcaneBlitz = mod:NewSpecialWarningStack(235833, nil, 4, nil, nil, 1, 6)--Fine tune the numbers local specWarnIgniteSoul = mod:NewSpecialWarningYou(237188, nil, nil, nil, 3, 2) --local timerEarthquakeCD = mod:NewNextTimer(60, 237950, nil, nil, nil, 2) local timerIgniteSoulCD = mod:NewAITimer(25, 237188, nil, nil, nil, 3, nil, DBM_CORE_DEADLY_ICON) local countdownIngiteSoul = mod:NewCountdownFades("AltTwo9", 237188) local voiceManaSling = mod:NewVoice(235984)--findshelter local voiceArcaneBlitz = mod:NewVoice(235833)--stackhigh local voiceIgniteSoul = mod:NewVoice(237188) mod:RemoveOption("HealthFrame") --local started = false --local activeBossGUIDS = {} --[[ function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 234423 then end end function mod:SPELL_CAST_SUCCESS(args) local spellId = args.spellId if spellId == 237950 then specWarnEarthquake:Show(args.sourceName) voiceEarthquake:Play("aesoon") timerEarthquakeCD:Start() elseif spellId == 242730 then warnFelShock:Show() end end --]] function mod:SPELL_AURA_APPLIED(args) local spellId = args.spellId if spellId == 235833 then local amount = args.amount or 1 if amount % 2 == 0 then if amount >= 4 then specWarnArcaneBlitz:Show(amount) voiceArcaneBlitz:Play("stackhigh") else warnArcaneBlitz:Show(args.destName, amount) end end elseif spellId == 235984 and args:IsPlayer() then specWarnManaSling:Show(DBM_ALLY) voiceManaSling:Play("findshelter") elseif spellId == 237188 then countdownIngiteSoul:Start() specWarnIgniteSoul:Show() voiceIgniteSoul:Play("targetyou") timerIgniteSoulCD:Start() end end mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED function mod:UNIT_DIED(args) if args.destGUID == UnitGUID("player") then--Solo scenario, a player death is a wipe --started = false --table.wipe(activeBossGUIDS) timerIgniteSoulCD:Stop() end --local cid = self:GetCIDFromGUID(args.destGUID) -- if cid == 177933 then--Variss -- end end --[[ function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, spellGUID) local spellId = tonumber(select(5, strsplit("-", spellGUID)), 10) if spellId == 234428 then--Summon Tormenting Eye end end function mod:INSTANCE_ENCOUNTER_ENGAGE_UNIT() for i = 1, 5 do local unitID = "boss"..i local unitGUID = UnitGUID(unitID) if UnitExists(unitID) and not activeBossGUIDS[unitGUID] then local bossName = UnitName(unitID) local cid = self:GetUnitCreatureId(unitID) --Tank if cid == 177933 then--Variss (Tank/Kruul Scenario) started = true timerTormentingEyeCD:Start(1)--3.8? timerHolyWardCD:Start(1)--8? timerDrainLifeCD:Start(1)--9? timerNetherAbberationCD:Start(1) elseif cid == 117230 then--Tugar Bloodtotem (DPS Fel Totem Fall) started = true timerFelRuptureCD:Start(7.5) timerEarthquakeCD:Start(20.5) timerFelSurgeCD:Start(62)--Correct place to do it? end end end end function mod:SCENARIO_UPDATE(newStep) local diffID, currWave, maxWave, duration = C_Scenario.GetProvingGroundsInfo() if diffID > 0 then started = true countdownTimer:Cancel() countdownTimer:Start(duration) if DBM.Options.AutoRespond then--Use global whisper option self:RegisterShortTermEvents( "CHAT_MSG_WHISPER" ) end elseif started then started = false countdownTimer:Cancel() self:UnregisterShortTermEvents() end end local mode = { [1] = CHALLENGE_MODE_MEDAL1, [2] = CHALLENGE_MODE_MEDAL2, [3] = CHALLENGE_MODE_MEDAL3, [4] = L.Endless, } function mod:CHAT_MSG_WHISPER(msg, name, _, _, _, status) if status ~= "GM" then--Filter GMs name = Ambiguate(name, "none") local diffID, currWave, maxWave, duration = C_Scenario.GetProvingGroundsInfo() local message = L.ReplyWhisper:format(UnitName("player"), mode[diffID], currWave) if msg == "status" then SendChatMessage(message, "WHISPER", nil, name) elseif self:AntiSpam(20, name) then--If not "status" then auto respond only once per 20 seconds per person. SendChatMessage(message, "WHISPER", nil, name) end end end --]]
mit
MocoNinja/LinuxConfs
Archlabs/.config/awesome/themes/default/theme.lua
1
8354
--------------------------- -- Default ArchLabs theme -- --------------------------- local awful = require("awful") --Configure home path so you dont have too home_path = os.getenv('HOME') .. '/' theme = {} theme.wallpaper_cmd = { "awsetbg /usr/share/backgrounds/archlabs/archlabs.png" } theme.font = "Ubuntu 10" theme.bg_normal = "#222222" theme.bg_focus = "#535d6c" theme.bg_urgent = "#ff0000" theme.bg_minimize = "#444444" theme.bg_tooltip = "#d6d6d6" theme.bg_em = "#5a5a5a" theme.bg_systray = theme.bg_normal theme.fg_normal = "#aaaaaa" theme.fg_focus = "#ffffff" theme.fg_urgent = "#ffffff" theme.fg_minimize = "#ffffff" theme.fg_tooltip = "#1a1a1a" theme.fg_em = "#d6d6d6" theme.border_width = "1" theme.border_normal = "#000000" theme.border_focus = "#535d6c" theme.border_marked = "#91231c" theme.fg_widget_value = "#aaaaaa" theme.fg_widget_clock = "#aaaaaa" theme.fg_widget_value_important = "#aaaaaa" theme.fg_widget = "#908884" theme.fg_center_widget = "#636363" theme.fg_end_widget = "#1a1a1a" theme.bg_widget = "#2a2a2a" theme.border_widget = "#3F3F3F" -- There are other variable sets -- overriding the default one when -- defined, the sets are: -- [taglist|tasklist]_[bg|fg]_[focus|urgent] -- titlebar_[bg|fg]_[normal|focus] -- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color] -- mouse_finder_[color|timeout|animate_timeout|radius|factor] -- Example: --theme.taglist_bg_focus = "#ff0000" -- Display the taglist squares theme.taglist_squares_sel = home_path .. '.config/awesome/themes/default/taglist/squarefw.png' theme.taglist_squares_unsel = home_path .. '.config/awesome/themes/default/taglist/squarew.png' theme.tasklist_floating_icon = home_path .. '.config/awesome/themes/default/tasklist/floatingw.png' -- Variables set for theming the menu: -- menu_[bg|fg]_[normal|focus] -- menu_[border_color|border_width] theme.menu_submenu_icon = home_path .. '.config/awesome/themes/default/submenu.png' theme.menu_height = "20" theme.menu_width = "150" -- You can add as many variables as -- you wish and access them by using -- beautiful.variable in your rc.lua --theme.bg_widget = "#cc0000" -- Define the image to load theme.titlebar_close_button_normal = home_path .. '.config/awesome/themes/default/titlebar/close_normal.png' theme.titlebar_close_button_focus = home_path .. '.config/awesome/themes/default/titlebar/close_focus.png' theme.titlebar_ontop_button_normal_inactive = home_path .. '.config/awesome/themes/default/titlebar/ontop_normal_inactive.png' theme.titlebar_ontop_button_focus_inactive = home_path .. '.config/awesome/themes/default/titlebar/ontop_focus_inactive.png' theme.titlebar_ontop_button_normal_active = home_path .. '/home/setkeh/.config/awesome/themes/default/titlebar/ontop_normal_active.png' theme.titlebar_ontop_button_focus_active = home_path .. '.config/awesome/themes/default/titlebar/ontop_focus_active.png' theme.titlebar_sticky_button_normal_inactive = home_path .. '.config/awesome/themes/default/titlebar/sticky_normal_inactive.png' theme.titlebar_sticky_button_focus_inactive = home_path .. '.config/awesome/themes/default/titlebar/sticky_focus_inactive.png' theme.titlebar_sticky_button_normal_active = home_path .. '.config/awesome/themes/default/titlebar/sticky_normal_active.png' theme.titlebar_sticky_button_focus_active = home_path .. '.config/awesome/themes/default/titlebar/sticky_focus_active.png' theme.titlebar_floating_button_normal_inactive = home_path .. '.config/awesome/themes/default/titlebar/floating_normal_inactive.png' theme.titlebar_floating_button_focus_inactive = home_path .. '.config/awesome/themes/default/titlebar/floating_focus_inactive.png' theme.titlebar_floating_button_normal_active = home_path .. '.config/awesome/themes/default/titlebar/floating_normal_active.png' theme.titlebar_floating_button_focus_active = home_path .. '.config/awesome/themes/default/titlebar/floating_focus_active.png' theme.titlebar_maximized_button_normal_inactive = home_path .. '.config/awesome/themes/default/titlebar/maximized_normal_inactive.png' theme.titlebar_maximized_button_focus_inactive = home_path .. '.config/awesome/themes/default/titlebar/maximized_focus_inactive.png' theme.titlebar_maximized_button_normal_active = home_path .. '.config/awesome/themes/default/titlebar/maximized_normal_active.png' theme.titlebar_maximized_button_focus_active = home_path .. '.config/awesome/themes/default/titlebar/maximized_focus_active.png' -- You can use your own layout icons like this: theme.layout_fairh = home_path .. '.config/awesome/themes/default/layouts/fairhw.png' theme.layout_fairv = home_path .. '.config/awesome/themes/default/layouts/fairvw.png' theme.layout_floating = home_path .. '.config/awesome/themes/default/layouts/floatingw.png' theme.layout_magnifier = home_path .. '.config/awesome/themes/default/layouts/magnifierw.png' theme.layout_max = home_path .. '.config/awesome/themes/default/layouts/maxw.png' theme.layout_fullscreen = home_path .. '.config/awesome/themes/default/layouts/fullscreenw.png' theme.layout_tilebottom = home_path .. '.config/awesome/themes/default/layouts/tilebottomw.png' theme.layout_tileleft = home_path .. '.config/awesome/themes/default/layouts/tileleftw.png' theme.layout_tile = home_path .. '.config/awesome/themes/default/layouts/tilew.png' theme.layout_tiletop = home_path .. '.config/awesome/themes/default/layouts/tiletopw.png' theme.layout_spiral = home_path .. '.config/awesome/themes/default/layouts/spiralw.png' theme.layout_dwindle = home_path .. '.config/awesome/themes/default/layouts/dwindlew.png' theme.awesome_icon = home_path .. '.config/awesome/themes/default/icon/awesome-icon.png' theme.arch_icon = home_path .. '.config/awesome/themes/default/icon/ArchLabs.png' -- {{{ Widgets theme.widget_disk = awful.util.getdir("config") .. "/themes/default/widgets/disk.png" theme.widget_cpu = awful.util.getdir("config") .. "/themes/default/widgets/cpu.png" theme.widget_ac = awful.util.getdir("config") .. "/themes/default/widgets/ac.png" theme.widget_acblink = awful.util.getdir("config") .. "/themes/default/widgets/acblink.png" theme.widget_blank = awful.util.getdir("config") .. "/themes/default/widgets/blank.png" theme.widget_batfull = awful.util.getdir("config") .. "/themes/default/widgets/batfull.png" theme.widget_batmed = awful.util.getdir("config") .. "/themes/default/widgets/batmed.png" theme.widget_batlow = awful.util.getdir("config") .. "/themes/default/widgets/batlow.png" theme.widget_batempty = awful.util.getdir("config") .. "/themes/default/widgets/batempty.png" theme.widget_vol = awful.util.getdir("config") .. "/themes/default/widgets/vol.png" theme.widget_mute = awful.util.getdir("config") .. "/themes/default/widgets/mute.png" theme.widget_pac = awful.util.getdir("config") .. "/themes/default/widgets/pac.png" theme.widget_pacnew = awful.util.getdir("config") .. "/themes/default/widgets/pacnew.png" theme.widget_temp = awful.util.getdir("config") .. "/themes/default/widgets/temp.png" theme.widget_tempwarn = awful.util.getdir("config") .. "/themes/default/widgets/tempwarm.png" theme.widget_temphot = awful.util.getdir("config") .. "/themes/default/widgets/temphot.png" theme.widget_wifi = awful.util.getdir("config") .. "/themes/default/widgets/wifi.png" theme.widget_nowifi = awful.util.getdir("config") .. "/themes/default/widgets/nowifi.png" theme.widget_mpd = awful.util.getdir("config") .. "/themes/default/widgets/mpd.png" theme.widget_play = awful.util.getdir("config") .. "/themes/default/widgets/play.png" theme.widget_pause = awful.util.getdir("config") .. "/themes/default/widgets/pause.png" theme.widget_ram = awful.util.getdir("config") .. "/themes/default/widgets/ram.png" theme.widget_mem = awful.util.getdir("config") .. "/themes/default/tp/ram.png" theme.widget_swap = awful.util.getdir("config") .. "/themes/default/tp/swap.png" theme.widget_fs = awful.util.getdir("config") .. "/themes/default/tp/fs_01.png" theme.widget_fs2 = awful.util.getdir("config") .. "/themes/default/tp/fs_02.png" theme.widget_up = awful.util.getdir("config") .. "/themes/default/tp/up.png" theme.widget_down = awful.util.getdir("config") .. "/themes/default/tp/down.png" -- }}} return theme -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-3.0
Hosseiin138yz/sam
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
liruqi/bigfoot
Interface/AddOns/Bagnon_Config/panels.lua
1
4773
--[[ panels.lua Configuration panels --]] local L = LibStub('AceLocale-3.0'):GetLocale('Bagnon-Config') local SLOT_COLOR_TYPES = {} for id, name in pairs(Bagnon.BAG_TYPES) do tinsert(SLOT_COLOR_TYPES, name) end sort(SLOT_COLOR_TYPES) tinsert(SLOT_COLOR_TYPES, 1, 'normal') local SetProfile = function(profile) Bagnon:SetProfile(profile) Bagnon.profile = Bagnon:GetProfile() Bagnon:UpdateFrames() Bagnon.FrameOptions:Update() end StaticPopupDialogs['Bagnon_ConfirmGlobals'] = { text = 'Are you sure you want to disable specific settings for this character? All specific settings will be lost.', OnAccept = function() SetProfile(nil) end, whileDead = 1, exclusive = 1, hideOnEscape = 1, button1 = YES, button2 = NO, timeout = 0, } --[[ Panels ]]-- Bagnon.GeneralOptions = Bagnon.Options:NewPanel(nil, 'Bagnon', L.GeneralDesc, function(self) self:CreateCheck('locked') self:CreateCheck('fading') self:CreateCheck('tipCount') self:CreateCheck('flashFind') self:CreateCheck('emptySlots') self:CreateCheck('displayBlizzard', ReloadUI) end) Bagnon.FrameOptions = Bagnon.Options:NewPanel('Bagnon', L.FrameSettings, L.FrameSettingsDesc, function(self) local frames = self:Create('Dropdown') frames:SetLabel(L.Frame) frames:SetValue(self.frameID) frames:AddLine('inventory', INVENTORY_TOOLTIP) frames:AddLine('bank', BANK) frames:SetCall('OnInput', function(_, v) self.frameID = v end) if GetAddOnEnableState(UnitName('player'), 'Bagnon_GuildBank') >= 2 then frames:AddLine('guild', GUILD_BANK) end if GetAddOnEnableState(UnitName('player'), 'Bagnon_VoidStorage') >= 2 then frames:AddLine('vault', VOID_STORAGE) end local global = self:Create('Check') global:SetLabel(L.CharacterSpecific) global:SetValue(Bagnon:GetSpecificProfile()) global:SetCall('OnInput', function(_, v) if Bagnon:GetSpecificProfile() then StaticPopup_Show('Bagnon_ConfirmGlobals') else SetProfile(CopyTable(Bagnon.sets.global)) end end) self.sets = Bagnon.profile[self.frameID] self:CreateCheck('enabled'):SetDisabled(self.frameID ~= 'inventory' and self.frameID ~= 'bank') if self.sets.enabled then if self.frameID == 'bank' then self:CreateCheck('exclusiveReagent') end -- Display self:CreateHeader(DISPLAY, 'GameFontHighlight', true) self:CreateRow(70, function(row) if self.frameID ~= 'guild' then row:CreateCheck('bagFrame') row:CreateCheck('sort') end row:CreateCheck('search') row:CreateCheck('options') row:CreateCheck('broker') if self.frameID ~= 'vault' then row:CreateCheck('money') end end) -- Appearance self:CreateHeader(L.Appearance, 'GameFontHighlight', true) self:CreateRow(70, function(row) row:CreateColor('color') row:CreateColor('borderColor') row:CreateCheck('reverseBags') row:CreateCheck('reverseSlots') row:CreateCheck('bagBreak') end) self:CreateRow(162, function(row) row:CreateDropdown('strata', 'LOW',LOW, 'MEDIUM',AUCTION_TIME_LEFT2, 'HIGH',HIGH) row:CreatePercentSlider('alpha', 1, 100) row:CreatePercentSlider('scale', 20, 300):SetCall('OnInput', function(self,v) local new = v/100 local old = self.sets.scale local ratio = new / old self.sets.x = self.sets.x / ratio self.sets.y = self.sets.y / ratio self.sets.scale = new Bagnon:UpdateFrames() end) row:Break() row:CreatePercentSlider('itemScale', 20, 300) row:CreateSlider('spacing', -15, 15) row:CreateSlider('columns', 1, 50) end).bottom = -50 end end) Bagnon.DisplayOptions = Bagnon.Options:NewPanel('Bagnon', L.DisplaySettings, L.DisplaySettingsDesc, function(self) self:CreateHeader(L.DisplayInventory, 'GameFontHighlight', true) for i, event in ipairs {'Bank', 'Auction', 'Guildbank', 'Mail', 'Player', 'Trade', 'Gems', 'Craft'} do self:CreateCheck('display' .. event) end self:CreateHeader(L.CloseInventory, 'GameFontHighlight', true) for i, event in ipairs {'Bank', 'Combat', 'Vehicle', 'Vendor'} do self:CreateCheck('close' .. event) end end) Bagnon.ColorOptions = Bagnon.Options:NewPanel('Bagnon', L.ColorSettings, L.ColorSettingsDesc, function(self) self:CreateCheck('glowQuality') self:CreateCheck('glowNew') self:CreateCheck('glowQuest') self:CreateCheck('glowUnusable') self:CreateCheck('glowSets') self:CreateCheck('emptySlots') self:CreateCheck('colorSlots').bottom = 11 if self.sets.colorSlots then self:CreateRow(140, function(self) for i, name in ipairs(SLOT_COLOR_TYPES) do self:CreateColor(name .. 'Color').right = 144 end end) self:CreatePercentSlider('glowAlpha', 1, 100):SetWidth(585) end end)
mit
hashkat/hashkat
src/dependencies/lua-repl/repl/plugins/completion.lua
2
4670
-- Copyright (c) 2011-2013 Rob Hoelz <rob@hoelz.ro> -- -- 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. local getmetatable = getmetatable local pairs = pairs local sfind = string.find local sgmatch = string.gmatch local smatch = string.match local ssub = string.sub local tconcat = table.concat local tsort = table.sort local type = type local function isindexable(value) if type(value) == 'table' then return true end local mt = getmetatable(value) return mt and mt.__index end local function getcompletions(t) local union = {} while isindexable(t) do if type(t) == 'table' then -- XXX what about the pairs metamethod in 5.2? -- either we don't care, we implement a __pairs-friendly -- pairs for 5.1, or implement a 'rawpairs' for 5.2 for k, v in pairs(t) do if union[k] == nil then union[k] = v end end end local mt = getmetatable(t) t = mt and mt.__index or nil end return pairs(union) end local function split_ns(expr) if expr == '' then return { '' } end local pieces = {} -- XXX method calls too (option?) for m in sgmatch(expr, '[^.]+') do pieces[#pieces + 1] = m end -- logic for determining whether to pad the matches with the empty -- string (ugly) if ssub(expr, -1) == '.' then pieces[#pieces + 1] = '' end return pieces end local function determine_ns(expr) local ns = _G -- XXX what if the REPL lives in a special context? (option?) local pieces = split_ns(expr) for index = 1, #pieces - 1 do local key = pieces[index] -- XXX rawget? or regular access? (option?) ns = ns[key] if not isindexable(ns) then return {}, '', '' end end expr = pieces[#pieces] local prefix = '' if #pieces > 1 then prefix = tconcat(pieces, '.', 1, #pieces - 1) .. '.' end local last_piece = pieces[#pieces] local before, after = smatch(last_piece, '(.*):(.*)') if before then ns = ns[before] -- XXX rawget prefix = prefix .. before .. ':' expr = after end return ns, prefix, expr end local isidentifierchar do local ident_chars_set = {} -- XXX I think this can be done with isalpha in C... local ident_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:_0123456789' for i = 1, #ident_chars do local char = ssub(ident_chars, i, i) ident_chars_set[char] = true end function isidentifierchar(char) return ident_chars_set[char] end end local function extract_innermost_expr(expr) local index = #expr while index > 0 do local char = ssub(expr, index, index) if isidentifierchar(char) then index = index - 1 else break end end index = index + 1 return ssub(expr, 1, index - 1), ssub(expr, index) end -- XXX is this logic (namely, returning the entire line) too specific to -- linenoise? function repl:complete(expr, callback) local ns, prefix, path prefix, expr = extract_innermost_expr(expr) ns, path, expr = determine_ns(expr) prefix = prefix .. path local completions = {} for k, v in getcompletions(ns) do if sfind(k, expr, 1, true) == 1 then local suffix = '' local type = type(v) -- XXX this should be optional if type == 'function' then suffix = '(' elseif type == 'table' then suffix = '.' end completions[#completions + 1] = prefix .. k .. suffix end end tsort(completions) for _, completion in ipairs(completions) do callback(completion) end end features = 'completion'
gpl-3.0
Capibara-/cardpeek
dot_cardpeek_dir/scripts/etc/paris-rer.lua
17
11936
BANLIEUE_LIST = { [01] = { [00] = "Châtelet-Les Halles", [01] = "Châtelet-Les Halles", [07] = "Luxembourg" }, [03] = { [00] = "Saint-Michel Notre-Dame" }, [06] = { [00] = "Auber" }, [14] = { [04] = "Cité Universitaire" }, [15] = { [12] = "Port Royal", [13] = "Denfert-Rochereau" }, [16] = { [01] = "Nation", [02] = "Fontenay-sous-Bois|Vincennes", [03] = "Joinville-le-Pont|Nogent-sur-Marne", [04] = "Saint-Maur Créteil", [05] = "Le Parc de Saint-Maur", [06] = "Champigny", [07] = "La Varenne-Chennevières", [08] = "Boissy-Saint-Léger|Sucy Bonneuil" }, [17] = { [01] = "Charles de Gaulle-Etoile", [04] = "La Défense (Grande Arche)", [05] = "Nanterre-Université|Nanterre-Ville|Nanterre-Préfecture", [06] = "Rueil-Malmaison", [08] = "Chatou-Croissy", [09] = "Le Vésinet-Centre|Le Vésinet-Le Pecq|Saint-Germain-en-Laye" }, [18] = { [00] = "Denfert-Rochereau", [01] = "Gentilly", [02] = "Arcueil-Cachan|Laplace", [03] = "Bagneux|Bourg-la-Reine", [04] = "La Croix-de-Berny|Parc de Sceaux", [05] = "Antony|Fontaine-Michalon|Les Baconnets", [06] = "Massy-Palaiseau|Massy-Verrières", [07] = "Palaiseau|Palaiseau Villebon", [08] = "Lozère", [09] = "Le Guichet|Orsay-Ville", [10] = "Bures-sur-Yvette|Courcelle-sur-Yvette|Gif-sur-Yvette|La Hacquinière|Saint-Rémy-lès-Chevreuse" }, [20] = { [01] = "Gare de l'Est", [04] = "Pantin", [05] = "Noisy-le-Sec", [06] = "Bondy", [07] = "Gagny|Le Raincy Villemomble", [09] = "Chelles Gournay|Le Chênay Gagny", [10] = "Vaires Torcy", [11] = "Lagny-Thorigny", [13] = "Esbly", [14] = "Meaux", [15] = "Changis-Saint-Jean|Isles-Armentières Congis|Lizy-sur-Ourcq|Trilport", [16] = "Crouy-sur-Ourcq|La Ferté-sous-Jouarre|Nanteuil Saacy" }, [21] = { [05] = "Rosny-Bois-Perrier|Rosny-sous-Bois|Val de Fontenay", [06] = "Nogent Le-Perreux", [07] = "Les Boullereaux Champigny", [08] = "Villiers-sur-Marne", [09] = "Les Yvris Noisy-le-Grand", [10] = "Emerainville|Roissy-en-Brie", [11] = "Ozoir-la-Ferrière", [12] = "Gretz-Armainvilliers|Tournan", [15] = "Courquetaine|Faremoutiers Pommeuse|Guerard La-Celle-sur-Morin|Liverdy en Brie|Marles-en-Brie|Mormant|Mortcerf|Mouroux|Ozouer le voulgis|Verneuil-l'Etang|Villepatour - Presles|Yebles|Yebles - Guignes", [16] = "Chailly Boissy-le-Châtel|Chauffry|Coulommiers|Jouy-sur-Morin Le-Marais|Nangis|Saint-Rémy-la-Vanne|Saint-Siméon", [17] = "Champbenoist-Poigny|La Ferté-Gaucher|Longueville|Provins|Sainte-Colombe-Septveilles", [18] = "Flamboin|Meilleray|Villiers St Georges" }, [22] = { [07] = "Allée de la Tour-Rendez-Vous|La Remise-à-Jorelle|Les Coquetiers|Les Pavillons-sous-Bois", [08] = "Gargan", [09] = "Freinville Sevran|L'Abbaye|Lycée Henri Sellier|Rougemont-Chanteloup" }, [23] = { [13] = "Couilly Saint-Germain Quincy|Les Champs-Forts|Montry Condé", [14] = "Crécy-en-Brie La Chapelle|Villiers-Montbarbin" }, [26] = { [05] = "Val de Fontenay", [06] = "Bry-sur-Marne|Neuilly-Plaisance", [07] = "Noisy-le-Grand (Mont d'Est)", [08] = "Noisy-Champs", [10] = "Lognes|Noisiel|Torcy", [11] = "Bussy-Saint-Georges", [12] = "Val d'europe", [13] = "Marne-la-Vallée Chessy" }, [28] = { [04] = "Fontenay-aux-Roses|Robinson|Sceaux" }, [30] = { [01] = "Gare Saint-Lazare", [03] = "Pont Cardinet", [04] = "Asnières|Bécon-les-Bruyères|Clichy Levallois|Courbevoie|La Défense (Grande Arche)", [05] = "Puteaux|Suresnes Mont-Valérien", [07] = "Garches Marne-la-Coquette|Le Val d'Or|Saint-Cloud", [08] = "Vaucresson", [09] = "Bougival|La Celle-Saint-Cloud|Louveciennes|Marly-le-Roi", [10] = "L'Etang-la-Ville|Saint-Nom-la-Bretêche Forêt" }, [31] = { [07] = "Chaville-Rive Droite|Sèvres Ville-d'Avray|Viroflay-Rive Droite", [08] = "Montreuil|Versailles-Rive Droite" }, [32] = { [05] = "La Garenne-Colombes|Les Vallées|Nanterre-Université", [07] = "Houilles Carrières-sur-Seine|Sartrouville", [09] = "Maisons-Laffitte", [10] = "Poissy", [11] = "Médan|Villennes-sur-Seine", [12] = "Les Clairières de Verneuil|Vernouillet Verneuil", [13] = "Aubergenville-Elisabethville|Les Mureaux", [14] = "Epône Mézières", [16] = "Bonnières|Mantes-la-Jolie|Mantes-Station|Port-Villez|Rosny-sur-Seine" }, [33] = { [10] = "Achères-Grand-Cormier|Achères-Ville", [11] = "Cergy-Préfecture|Neuville-Université", [12] = "Cergy-le-Haut|Cergy-Saint-Christophe" }, [34] = { [05] = "Suresnes - Lonchamp", [06] = "Les Côteaux|Pont de Saint Cloud|Pont de Sèvres", [07] = "Bas Meudon|Bellevue funiculaire", [08] = "Les Moulineaux - Billancourt" }, [35] = { [04] = "Bois-Colombes", [05] = "Colombes|Le Stade", [06] = "Argenteuil", [08] = "Cormeilles-en-Parisis|Val d'Argenteuil", [09] = "Herblay|La Frette Montigny", [10] = "Conflans-Fin d'Oise|Conflans-Sainte-Honorine", [11] = "Andrésy|Chanteloup-lès-Vignes|Maurecourt", [12] = "Triel-sur-Seine|Vaux-sur-Seine", [13] = "Meulan Hadricourt|Thun-le-Paradis", [14] = "Gargenville|Juziers", [15] = "Issou Porcheville|Limay", [16] = "Breval|Ménerville" }, [40] = { [01] = "Gare de Lyon|Gare de Lyon (Banlieue)", [05] = "Le Vert de Maisons|Maisons-Alfort Alfortville", [06] = "Villeneuve-Prairie", [07] = "Villeneuve-Triage", [08] = "Villeneuve-Saint-Georges", [09] = "Juvisy|Vigneux-sur-Seine", [10] = "Ris-Orangis|Viry-Châtillon", [11] = "Evry Val de Seine|Grand-Bourg", [12] = "Corbeil-Essonnes|Mennecy|Moulin-Galant", [13] = "Ballancourt|Fontenay le Vicomte", [14] = "La Ferté-Alais", [16] = "Boutigny|Maisse", [17] = "Boigneville|Buno-Gironville" }, [41] = { [00] = "Saint-Michel Notre-Dame|Musée d'Orsay", [01] = "Gare d'Austerlitz", [02] = "Bibliotheque-Francois", [03] = "Boulevard Masséna", [04] = "Ivry-sur-Seine|Vitry-sur-Seine", [05] = "Choisy-le-Roi|Les Ardoines", [07] = "Villeneuve-le-Roi", [08] = "Ablon", [09] = "Athis-Mons" }, [42] = { [09] = "Epinay-sur-Orge|Savigny-sur-Orge", [10] = "Sainte-Geneviève-des-Bois", [11] = "Saint-Michel-sur-Orge", [12] = "Brétigny-sur-Orge|Marolles-en-Hurepoix", [13] = "Bouray|Lardy", [14] = "Chamarande|Etampes|Etréchy", [16] = "Saint-Martin d'Etampes", [17] = "Guillerval" }, [43] = { [09] = "Montgeron Crosne|Yerres", [10] = "Brunoy", [11] = "Boussy-Saint-Antoine|Combs-la-Ville Quincy", [12] = "Lieusaint Moissy", [13] = "Cesson|Savigny-le-Temple Nandy", [15] = "Le Mée|Melun", [16] = "Chartrettes|Fontaine-le-Port|Livry-sur-Seine", [17] = "Champagne-sur-Seine|Héricy|La Grande Paroisse|Vernou-sur-Seine|Vulaines-sur-Seine Samoreau" }, [44] = { [12] = "Essonnes-Robinson|Villabé", [13] = "Coudray-Montceaux|Le Plessis-Chenet-IBM|Saint-Fargeau", [14] = "Boissise-le-Roi|Ponthierry Pringy", [15] = "Vosves", [16] = "Bois-le-Roi", [17] = "Bagneaux-sur-Loing|Bourron-Marlotte Grez|Fontainebleau-Avon|Montereau|Montigny-sur-Loing|Moret Veneux-les-Sablons|Nemours Saint-Pierre|Saint-Mammés|Souppes|Thomery" }, [45] = { [10] = "Grigny-Centre", [11] = "Evry Courcouronnes|Orangis Bois de l'Epine", [12] = "Le Bras-de-Fer - Evry" }, [50] = { [00] = "Haussmann-Saint-Lazare", [01] = "Gare du Nord|Gare du Nord (Surface)|Magenta|Paris-Nord", [05] = "Epinay-Villetaneuse|Saint-Denis|Sèvres-Rive Gauche", [06] = "La Barre-Ormesson", [07] = "Champ de Courses d'Enghien|Enghien-les-Bains", [08] = "Ermont Eaubonne|Ermont-Eaubonne|Ermont-Halte|Gros-Noyer Saint-Prix", [09] = "Saint-Leu-La-Forêt|Taverny|Vaucelles", [10] = "Bessancourt|Frépillon|Mery", [11] = "Mériel|Valmondois", [12] = "Bruyères-sur-Oise|Champagne-sur-Oise|L'Isle-Adam Parmain|Persan Beaumont" }, [51] = { [04] = "La Courneuve-Aubervilliers|La Plaine-Stade de France", [05] = "Le Bourget", [07] = "Blanc-Mesnil|Drancy", [08] = "Aulnay-sous-Bois", [09] = "Sevran Livry|Vert-Galant", [10] = "Villeparisis", [11] = "Compans|Mitry Claye|Mitry-Claye", [12] = "Dammartin Juilly Saint-Mard|Thieux Nantouillet" }, [52] = { [05] = "Stade de France-Saint-Denis", [06] = "Pierrefitte Stains", [07] = "Garges-Sarcelles", [08] = "Villiers-le-Bel (Gonesse -", [10] = "Goussainville|Les Noues|Louvres", [11] = "La Borne-Blanche|Survilliers-Fosses" }, [53] = { [06] = "Deuil Montmagny", [07] = "Groslay", [08] = "Sarcelles Saint-Brice", [09] = "Domont|Ecouen Ezanville", [10] = "Bouffemont Moisselles|Montsoult Maffliers", [11] = "Belloy-Saint-Martin|Luzarches|Seugy|Viarmes|Villaines" }, [54] = { [08] = "Cernay", [09] = "Franconville|Montigny Beauchamp|Montigny-Beauchamp", [10] = "Pierrelaye", [11] = "Pontoise|Saint-Ouen-l'Aumône|Saint-Ouen-l'Aumone-Liesse", [12] = "Boissy-l'Aillerie|Osny", [15] = "Chars|Montgeroult Courcelles|Santeuil Le Perchay|Us" }, [55] = { [00] = "Avenue Foch|Avenue Henri-Martin|Kennedy Radio-France|Boulainvilliers|Neuilly-Porte Maillot", [01] = "Péreire-Levallois", [02] = "Porte de Clichy", [03] = "Saint-Ouen", [04] = "Les Grésillons", [05] = "Gennevilliers", [06] = "Epinay-sur-Seine", [07] = "Saint-Gratien" }, [56] = { [11] = "Auvers-sur-Oise|Chaponval|Epluches|Pont Petit" }, [57] = { [11] = "Presles Courcelles", [12] = "Nointel Mours" }, [60] = { [01] = "Gare Montparnasse|Paris Montparnasse3 Vaug.", [04] = "Clamart|Vanves Malakoff", [05] = "Bellevue|Bièvres|Meudon", [06] = "Chaville-Rive Gauche|Chaville-Vélizy|Viroflay-Rive Gauche", [07] = "Versailles-Chantiers", [10] = "Saint-Cyr", [11] = "Saint-Quentin-en-Yvelines -|Trappes", [12] = "Coignières|La Verrière", [13] = "Les Essarts-le-Roi", [14] = "Le Perray|Rambouillet", [15] = "Gazeran" }, [61] = { [10] = "Fontenay-le-Fleury", [11] = "Villepreux Les-Clayes", [12] = "Plaisir Grignon|Plaisir Les-Clayes", [13] = "Beynes|Mareil-sur-Mauldre|Maule|Nézel Aulnay", [15] = "Garancières La-Queue|Montfort-l'Amaury Méré|Orgerus Behoust|Tacoignères Richebourg|Villiers Neauphle", [16] = "Houdan" }, [63] = { [07] = "Porchefontaine|Versailles-Rive Gauche" }, [64] = { [00] = "Pont de l'alma|Invalides", [01] = "Champ de Mars-Tour Eiffel", [02] = "Javel", [03] = "Boulevard Victor - Pont du Garigliano", [04] = "Issy-Val de Seine", [05] = "Issy|Meudon-Val-Fleury" }, [65] = { [08] = "Jouy-en-Josas|Petit-Jouy-les-Loges", [09] = "Vauboyen", [10] = "Igny", [11] = "Massy-Palaiseau", [12] = "Longjumeau", [13] = "Chilly-Mazarin", [14] = "Gravigny-Balizy|Petit-Vaux" }, [70] = { [09] = "Parc des Expositions|Sevran-Beaudottes|Villepinte", [10] = "Aéroport Charles de Gaulle 1|Aéroport Charles de Gaulle 2" }, [72] = { [07] = "Sannois" }, [73] = { [11] = "Eragny Neuville|Saint-Ouen-l'Aumône (Eglise)" }, [75] = { [07] = "Les Saules|Orly-Ville", [09] = "Pont de Rungis Aéroport|Rungis-La Fraternelle", [10] = "Chemin d'Antony", [12] = "Massy-Verrières" }, [76] = { [12] = "Arpajon|Egly|La Norville", [13] = "Breuillet Bruyères-le-Châtel|Breuillet-Village|Saint-Chéron", [14] = "Sermaise", [15] = "Dourdan|Dourdan-la-Forêt" } } BANLIEUE_NET_LIST = { [1] = "RATP", [2] = "Transilien Paris Est", [3] = "Transilien Paris Saint-Lazare", [4] = "Transilien Paris Lyon", [5] = "Transilien Paris Nord", [6] = "Transilien Paris Montparnasse" }
gpl-3.0
liruqi/bigfoot
Interface/AddOns/BigFoot/AceLibs/wyLib/NetEaseGUI-2.0/Embed/Scroll.lua
1
3430
local GUI = LibStub('NetEaseGUI-2.0') local View = GUI:NewEmbed('Scroll', 4) if not View then return end local function scrollBarOnShownChanged(bar) bar:GetParent():UpdateLayout() end local function viewOnMouseWheel(self, delta) self.ScrollBar:SetValue(self.ScrollBar:GetValue() - delta * self:GetScrollStep()) end function View:GetScrollBar() if not self.ScrollBar then local ScrollBar = GUI:GetClass('ScrollBar'):New(self) local left, right, top, bot = self:GetPadding() ScrollBar:SetPoint('TOPRIGHT', -right, -16-top) ScrollBar:SetPoint('BOTTOMRIGHT', -right, 16+bot) ScrollBar:SetScript('OnShow', scrollBarOnShownChanged) ScrollBar:SetScript('OnHide', scrollBarOnShownChanged) ScrollBar.noScrollBarHidden = self.noScrollBarHidden self:SetScrollBar(ScrollBar) end return self.ScrollBar end function View:IsScrollBarShown() return self.ScrollBar and self.ScrollBar:IsShown() end function View:GetScrollBarFixedWidth() return self.ScrollBar and self.ScrollBar.GetFixedWidth and self.ScrollBar:IsShown() and self.ScrollBar:GetFixedWidth() or 0 end function View:SetScrollStep(scrollStep) self.scrollStep = scrollStep if self.ScrollBar then self.ScrollBar:SetScrollStep(scrollStep) end end function View:GetScrollStep() return self.scrollStep or 1 end function View:AtTop() return not self.ScrollBar or self.ScrollBar:AtTop() end function View:AtBottom() return not self.ScrollBar or self.ScrollBar:AtBottom() end function View:SetOffset(offset) self.offset = floor(offset + 0.5) if self.ScrollBar then self.ScrollBar:SetValue(self.offset) end self:Refresh() end function View:GetOffset() return self.offset or 1 end function View:UpdateScrollBar(position) local itemCount = self:GetItemCount() local maxCount = self:GetMaxCount() local maxValue = itemCount <= maxCount and 1 or itemCount - maxCount + 1 local value if position == 'TOP' then value = 1 elseif position == 'BOTTOM' then value = maxValue elseif self:IsHoldTop() and self:AtTop() then value = 1 elseif self:IsHoldBottom() and self:AtBottom() then value = maxValue elseif self.ScrollBar then value = self:GetOffset() elseif self.GetReverse and self:GetReverse() then value = maxValue else value = 1 end if maxValue > 1 or self.ScrollBar then local ScrollBar = self:GetScrollBar() ScrollBar:SetMinMaxValues(1, maxValue) ScrollBar:SetValue(value) end end function View:ScrollToTop() self:UpdateScrollBar('TOP') self:Refresh() end function View:ScrollToBottom() self:UpdateScrollBar('BOTTOM') self:Refresh() end function View:EnableHoldBottom(flag) self.holdBottom = flag or nil end function View:EnableHoldTop(flag) self.holdTop = flag or nil end function View:IsHoldBottom() return self.holdBottom end function View:IsHoldTop() return self.holdTop end function View:SetScrollBar(ScrollBar) if self.ScrollBar then return end self.ScrollBar = ScrollBar self.ScrollBar:SetScrollStep(self:GetScrollStep()) self:SetScript('OnMouseWheel', viewOnMouseWheel) end
mit
liruqi/bigfoot
Interface/AddOns/Bartender4/PetButton.lua
1
8604
--[[ Copyright (c) 2009-2017, Hendrik "Nevcairiel" Leppkes < h.leppkes at gmail dot com > All rights reserved. ]] --[[ Pet Button template ]] local _, Bartender4 = ... local PetButtonPrototype = CreateFrame("CheckButton") local PetButton_MT = {__index = PetButtonPrototype} local WoW80 = select(4, GetBuildInfo()) >= 80000 local LBF = LibStub("LibButtonFacade", true) local Masque = LibStub("Masque", true) local KeyBound = LibStub("LibKeyBound-1.0") -- upvalues local _G = _G local format, select, setmetatable = string.format, select, setmetatable -- GLOBALS: InCombatLockdown, CreateFrame, SetDesaturation, IsModifiedClick, GetBindingKey, GetBindingText, SetBinding -- GLOBALS: AutoCastShine_AutoCastStop, AutoCastShine_AutoCastStart, CooldownFrame_Set -- GLOBALS: PickupPetAction, , GetPetActionInfo, GetPetActionsUsable, GetPetActionCooldown local function onEnter(self, ...) if not (Bartender4.db.profile.tooltip == "nocombat" and InCombatLockdown()) and Bartender4.db.profile.tooltip ~= "disabled" then self:OnEnter(...) end KeyBound:Set(self) end local function onDragStart(self) if InCombatLockdown() then return end if not Bartender4.db.profile.buttonlock or IsModifiedClick("PICKUPACTION") then self:SetChecked(false) PickupPetAction(self.id) self:Update() end end local function onReceiveDrag(self) if InCombatLockdown() then return end self:SetChecked(false) PickupPetAction(self.id) self:Update() end Bartender4.PetButton = {} Bartender4.PetButton.prototype = PetButtonPrototype function Bartender4.PetButton:Create(id, parent) local name = "BT4PetButton" .. id local button = setmetatable(CreateFrame("CheckButton", name, parent, "PetActionButtonTemplate"), PetButton_MT) button.showgrid = 0 button.id = id button.parent = parent button:SetFrameStrata("MEDIUM") button:SetID(id) button:UnregisterAllEvents() button:SetScript("OnEvent", nil) button.OnEnter = button:GetScript("OnEnter") button:SetScript("OnEnter", onEnter) button:SetScript("OnDragStart", onDragStart) button:SetScript("OnReceiveDrag", onReceiveDrag) button.flash = _G[name .. "Flash"] button.cooldown = _G[name .. "Cooldown"] button.icon = _G[name .. "Icon"] button.autocastable = _G[name .. "AutoCastable"] button.autocast = _G[name .. "Shine"] button.hotkey = _G[name .. "HotKey"] button:SetNormalTexture("") local oldNT = button:GetNormalTexture() oldNT:Hide() button.normalTexture = button:CreateTexture(("%sBTNT"):format(name)) button.normalTexture:SetAllPoints(oldNT) button.pushedTexture = button:GetPushedTexture() button.highlightTexture = button:GetHighlightTexture() button.textureCache = {} button.textureCache.pushed = button.pushedTexture:GetTexture() button.textureCache.highlight = button.highlightTexture:GetTexture() if Masque then local group = parent.MasqueGroup button.MasqueButtonData = { Button = button, Normal = button.normalTexture, } group:AddButton(button, button.MasqueButtonData) elseif LBF then local group = parent.LBFGroup button.LBFButtonData = { Button = button, Normal = button.normalTexture, } group:AddButton(button, button.LBFButtonData) end return button end function PetButtonPrototype:Update() local name, texture, isToken, isActive, autoCastAllowed, autoCastEnabled, spellID if WoW80 then name, texture, isToken, isActive, autoCastAllowed, autoCastEnabled, spellID = GetPetActionInfo(self.id) else local _ name, _, texture, isToken, isActive, autoCastAllowed, autoCastEnabled, spellID = GetPetActionInfo(self.id) end if not isToken then self.icon:SetTexture(texture) self.tooltipName = name; else self.icon:SetTexture(_G[texture]) self.tooltipName = _G[name] end self.isToken = isToken self:SetChecked(isActive) if autoCastAllowed and not autoCastEnabled then self.autocastable:Show() AutoCastShine_AutoCastStop(self.autocast) elseif autoCastAllowed then self.autocastable:Hide() AutoCastShine_AutoCastStart(self.autocast) else self.autocastable:Hide() AutoCastShine_AutoCastStop(self.autocast) end if texture then if GetPetActionsUsable() then SetDesaturation(self.icon, nil) else SetDesaturation(self.icon, 1) end self.icon:Show() self.normalTexture:SetTexture("Interface\\Buttons\\UI-Quickslot2") self.normalTexture:SetTexCoord(0, 0, 0, 0) self:ShowButton() self.normalTexture:Show() if self.overlay then self.overlay:Show() end else self.icon:Hide() self.normalTexture:SetTexture("Interface\\Buttons\\UI-Quickslot") self.normalTexture:SetTexCoord(-0.1, 1.1, -0.1, 1.12) self:HideButton() if self.showgrid == 0 and not self.parent.config.showgrid then self.normalTexture:Hide() if self.overlay then self.overlay:Hide() end end end self:UpdateCooldown() self:UpdateHotkeys() end function PetButtonPrototype:UpdateHotkeys() local key = self:GetHotkey() or "" local hotkey = self.hotkey if key == "" or self.parent.config.hidehotkey then hotkey:Hide() else hotkey:SetText(key) hotkey:Show() end end function PetButtonPrototype:ShowButton() self.pushedTexture:SetTexture(self.textureCache.pushed) self.highlightTexture:SetTexture(self.textureCache.highlight) local backdrop, gloss if Masque then backdrop, gloss = Masque:GetBackdrop(self), Masque:GetGloss(self) elseif LBF then backdrop, gloss = LBF:GetBackdropLayer(self), LBF:GetGlossLayer(self) end -- Toggle backdrop/gloss if backdrop then backdrop:Show() end if gloss then gloss:Show() end self:SetAlpha(1.0) end function PetButtonPrototype:HideButton() self.textureCache.pushed = self.pushedTexture:GetTexture() self.textureCache.highlight = self.highlightTexture:GetTexture() self.pushedTexture:SetTexture("") self.highlightTexture:SetTexture("") local backdrop, gloss if Masque then backdrop, gloss = Masque:GetBackdrop(self), Masque:GetGloss(self) elseif LBF then backdrop, gloss = LBF:GetBackdropLayer(self), LBF:GetGlossLayer(self) end -- Toggle backdrop/gloss if backdrop then backdrop:Hide() end if gloss then gloss:Hide() end if self.showgrid == 0 and not self.parent.config.showgrid then self:SetAlpha(0.0) end end function PetButtonPrototype:ShowGrid() self.showgrid = self.showgrid + 1 self.normalTexture:Show() self:SetAlpha(1.0) end function PetButtonPrototype:HideGrid() if self.showgrid > 0 then self.showgrid = self.showgrid - 1 end if self.showgrid == 0 and not (GetPetActionInfo(self.id)) and not self.parent.config.showgrid then self.normalTexture:Hide() self:SetAlpha(0.0) end end function PetButtonPrototype:UpdateCooldown() local start, duration, enable = GetPetActionCooldown(self.id) CooldownFrame_Set(self.cooldown, start, duration, enable) end function PetButtonPrototype:GetHotkey() local key = GetBindingKey(format("BONUSACTIONBUTTON%d", self.id)) or GetBindingKey("CLICK "..self:GetName()..":LeftButton") return key and KeyBound:ToShortKey(key) end function PetButtonPrototype:GetBindings() local keys, binding = "" binding = format("BONUSACTIONBUTTON%d", self.id) for i = 1, select('#', GetBindingKey(binding)) do local hotKey = select(i, GetBindingKey(binding)) if keys ~= "" then keys = keys .. ', ' end keys = keys .. GetBindingText(hotKey,'KEY_') end binding = "CLICK "..self:GetName()..":LeftButton" for i = 1, select('#', GetBindingKey(binding)) do local hotKey = select(i, GetBindingKey(binding)) if keys ~= "" then keys = keys .. ', ' end keys = keys.. GetBindingText(hotKey,'KEY_') end return keys end function PetButtonPrototype:SetKey(key) SetBinding(key, format("BONUSACTIONBUTTON%d", self.id)) end function PetButtonPrototype:ClearBindings() local binding = format("BONUSACTIONBUTTON%d", self:GetID()) while GetBindingKey(binding) do SetBinding(GetBindingKey(binding), nil) end binding = "CLICK "..self:GetName()..":LeftButton" while GetBindingKey(binding) do SetBinding(GetBindingKey(binding), nil) end end local actionTmpl = "Pet Button %d (%s)" function PetButtonPrototype:GetActionName() local id = self.id local name, _, _, token = GetPetActionInfo(id) if token and name then name = _G[name] end return format(actionTmpl, id, name or "empty") end function PetButtonPrototype:ClearSetPoint(...) self:ClearAllPoints() self:SetPoint(...) end
mit
Capibara-/cardpeek
dot_cardpeek_dir/scripts/mifare reader.lua
16
14339
-- -- This file is part of Cardpeek, the smartcard reader utility. -- -- Copyright 2009-2013 by 'L1L1' -- -- Cardpeek is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Cardpeek 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 Cardpeek. If not, see <http://www.gnu.org/licenses/>. -- -- @description Basic Mifare reader -- @targets 0.8 require('lib.strict') require('lib.apdu') MIFARE_STD_KEYS= { ["default"] = { { 'a', "FFFFFFFFFFFF" }, { 'a', "A0A1A2A3A4A5" }, { 'b', "B0B1B2B3B4B5" }, { 'b', "FFFFFFFFFFFF" }, { 'a', "000000000000" }, { 'b', "000000000000" } } } function mifare_read_uid() return card.send(bytes.new(8,"FF CA 00 00 00")) end local USE_VOLATILE_MEM = true function mifare_load_key(keynum,keyval,options) local command, sw, resp local key = bytes.new(8,keyval) if options==nil then if USE_VOLATILE_MEM then -- first try volatile memory sw, resp = mifare_load_key(keynum,keyval,0x00) if sw==0x6986 then USE_VOLATILE_MEMORY = false return mifare_load_key(keynum,keyval,0x20) else return sw, resp end else -- volatile memory not available return mifare_load_key(keynum,keyval,0x20) end end command = bytes.new(8,"FF 82", options, keynum, #key, key) sw, resp = card.send(command) return sw,resp end function mifare_authenticate(addr,keynum,keytype) return card.send(bytes.new(8,"FF 86 00 00 05 01",bit.SHR(addr,8),bit.AND(addr,0xFF),keytype,keynum)) end function mifare_read_binary(addr,len) return card.send(bytes.new(8,"FF B0",bit.SHR(addr,8),bit.AND(addr,0xFF),len)) end function mifare_textify(node,data) local i local r = data:format("%D") .. " (" for i=0,#data-1 do if data[i]>=32 and data[i]<127 then r = r .. string.char(data[i]) else r = r .. "." end end r = r .. ")" node:set_attribute("alt",r) end function mifare_trailer(node,data) local keyA = data:sub(0,5) local perm = data:sub(6,9) local keyB = data:sub(10,15) r = "KeyA:" .. keyA:format("%D") .. " Access:" .. perm:format("%D") .. " keyB:" .. keyB:format("%D") node:set_attribute("alt",r) end MIFARE_ACC_KEY = { "--", "A-", "-B", "AB" } MIFARE_ACC_DATA = { -- C1 C2 C3 { 3, 3, 3, 3 }, -- 000 { 3, 0, 0, 3 }, -- 001 { 3, 0, 0, 0 }, -- 010 { 2, 2, 0, 0 }, -- 011 { 3, 2, 0, 0 }, -- 100 { 2, 0, 0, 0 }, -- 101 { 3, 2, 2, 3 }, -- 110 { 0, 0, 0, 0 } -- 111 } MIFARE_ACC_TAILER = { { 0, 1, 1, 0, 1, 1 }, -- 000 { 0, 1, 1, 1, 1, 1 }, -- 001 { 0, 0, 1, 0, 1, 0 }, -- 010 { 0, 2, 3, 2, 0, 2 }, -- 011 { 0, 2, 3, 0, 0, 2 }, -- 100 { 0, 0, 3, 2, 0, 0 }, -- 101 { 0, 0, 3, 0, 0, 2 }, -- 110 { 0, 0, 3, 0, 0, 0 } -- 111 } function mifare_data_access(node, block, code) local access_string = "" access_string = access_string .. "read:" .. MIFARE_ACC_KEY[MIFARE_ACC_DATA[code+1][1]+1] .. " " access_string = access_string .. "write:" .. MIFARE_ACC_KEY[MIFARE_ACC_DATA[code+1][2]+1] .. " " access_string = access_string .. "inc:" .. MIFARE_ACC_KEY[MIFARE_ACC_DATA[code+1][3]+1] .. " " access_string = access_string .. "dec:" .. MIFARE_ACC_KEY[MIFARE_ACC_DATA[code+1][4]+1] node:append{ classname = "item", label = string.format("block %i",block), val = code, alt = access_string } end function mifare_key_access(node, code) local access_string = "" subnode = node:append{ classname = "item", label = "block 3", val = code, alt = "" } access_string = "read:-- write:" .. MIFARE_ACC_KEY[MIFARE_ACC_TAILER[code+1][2]+1] subnode:append{ classname = "item", label = "key A", alt = access_string } access_string = "read:" .. MIFARE_ACC_KEY[MIFARE_ACC_TAILER[code+1][3]+1] .. " " .. "write:" .. MIFARE_ACC_KEY[MIFARE_ACC_TAILER[code+1][4]+1] subnode:append{ classname = "item", label = "Access bits", alt = access_string } access_string = "read:" .. MIFARE_ACC_KEY[MIFARE_ACC_TAILER[code+1][5]+1] .. " " .. "write:" .. MIFARE_ACC_KEY[MIFARE_ACC_TAILER[code+1][6]+1] subnode:append{ classname = "item", label = "Key B", alt = access_string } end function mifare_access_permission_get(tailer, block) local access_bits = bytes.convert(tailer:sub(6,9),1) local access local ssecca if block==0 then access = access_bits[11]*4 + access_bits[23]*2 + access_bits[19] ssecca = access_bits[7]*4 + access_bits[3]*2 + access_bits[15] elseif block==1 then access = access_bits[10]*4 + access_bits[22]*2 + access_bits[18] ssecca = access_bits[6]*4 + access_bits[2]*2 + access_bits[14] elseif block==2 then access = access_bits[9]*4 + access_bits[21]*2 + access_bits[17] ssecca = access_bits[5]*4 + access_bits[1]*2 + access_bits[13] else access = access_bits[8]*4 + access_bits[20]*2 + access_bits[16] ssecca = access_bits[4]*4 + access_bits[0]*2 + access_bits[12] end if bit.XOR(ssecca,7)~=access then return access, false end return access, true end -- -- mifare_read_card(keys) reads a mifare card using the keys specified in <keys> -- it returns 3 elements: -- * A table representing the content of the readable sectors (or nil) -- * The card UID (or nil) -- function mifare_read_card(keys) local mfdata = {} local mfuid local sector local block local sw, resp local authenticated local key, current_key local errors = 0 local atr = card.last_atr() local auth_status if atr[13]==0 and atr[14]==2 then mfdata['last_sector'] = 63 else mfdata['last_sector'] = 15 end sw, mfuid = mifare_read_uid() if sw~=0x9000 then log.print(log.ERROR,"Could not get Mifare UID.") return nil, nil end for sector=0,mfdata['last_sector'] do authenticated = false keylist = keys[sector] or keys["default"] if keylist then for block = 0,3 do if not authenticated then for _, key in ipairs(keylist) do if current_key==nil or key[2]~=current_key[2] or key[1]~=current_key[1] then mifare_load_key(0x0, key[2]) current_key = key end if key[1]=='a' then sw, resp = mifare_authenticate(sector*4,0x0,0x60) else sw, resp = mifare_authenticate(sector*4,0x0,0x61) end if sw==0x9000 then auth_status = "OK" authenticated = true else auth_status = "FAIL" authenticated = false end log.print(log.INFO,string.format("Authenticating sector %2i, block %i, with key %s=%s: %s",sector,block,key[1],key[2],auth_status)) if authenticated then break end end end--if if authenticated then log.print(log.INFO,string.format("Reading from sector %2i, Block %i:",sector,block)) sw, resp = mifare_read_binary(sector*4+block,16) if sw == 0x9000 then if block==3 then if current_key[1]=='a' then mfdata[sector*4+block] = bytes.concat(bytes.new(8,current_key[2]),bytes.sub(resp,6)) else mfdata[sector*4+block] = bytes.concat(bytes.sub(resp,0,9),bytes.new(8,current_key[2])) end else mfdata[sector*4+block] = resp end else log.print(log.ERROR,string.format("Failed to read sector %2i, block %i, status code is %04x",sector,block,sw)) authenticated = false card.disconnect() if not card.connect() then log.print(log.ERROR," Failed to reconnect to the card. Aborting.") return nil, nil end end--if sw == 0x9000 end--if authenticated end--for block end--if keylist end-- for return mfdata, mfuid end -- -- mifare_load_keys(keyfile) loads mifare keys from the file <keyfile> -- The file <keyfile> is composed of lines of the form -- n:k:hhhhhhhhhhhh -- where -- * n represents a sector number or '*' for all sectors -- * k is the letter 'a' or 'b' to describe the use of key A or B. -- * hhhhhhhhhhhh is the hexadecimal representation of the key -- The file may also contain comments, which are prefixed with the '#' -- character, as in bash and many other scripting languages. -- function mifare_load_keys(keyfile) local keys = { } local fd, emsg = io.open(keyfile) local line_count = 0 local line, comment_pos local first, last local sector, sector_n, keytype, keyvalue local key_index = 0 if not fd then log.print(log.ERROR,string.format("Failed to open key file %s",emsg)) return nil end while true do line = fd:read("*line") if not line then break end line_count=line_count+1 comment_pos = string.find(line,"#") if comment_pos~=nil then line = string.sub(line,1,comment_pos-1) end line = string.gsub(line,"[\t\r\v ]","") if string.len(line)~=0 then first, last, sector, keytype, keyvalue = string.find(line,"^([0-9*]+):([ABab]):(%x+)") keytype = string.lower(keytype) if not first then log.print(log.ERROR,string.format("%s[%d]: Syntax error in key entry format.",keyfile,line_count)) fd:close() return nil end if string.len(keyvalue)~=12 then log.print(log.ERROR,string.format("%s[%d]: Key is %d characters long, but should be 12 hexadicimal characters.",keyfile,line_count,string.len(keyvalue))) fd:close() return nil end if sector=="*" then sector_n="default" else sector_n = tonumber(sector) if not sector_n then log.print(log.ERROR,string.format("%s[%d]: Unrecognized sector number '%s.'",keyfile,line_count,sector)) fd:close() return nil end end if keys[sector_n]==nil then keys[sector_n] = { } end table.insert(keys[sector_n], { keytype, keyvalue } ) end--if line not empty end--while fd:close() return keys end function mifare_display_permissions(perms, data) access = mifare_access_permission_get(data,0) mifare_data_access(perms,0,access) access = mifare_access_permission_get(data,1) mifare_data_access(perms,1,access) access = mifare_access_permission_get(data,2) mifare_data_access(perms,2,access) access = mifare_access_permission_get(data,3) mifare_key_access(perms,access) end function mifare_display(root, mfdata, mfuid) root:append{ classname="block", label="UID", val=mfuid, alt=bytes.tonumber(mfuid) } for sector=0,mfdata['last_sector'] do SECTOR = root:append{ classname="record", label="sector", id=sector } -- SECTOR:append{ classname="item", label="access key", val=bytes.new(8,key) } for block = 0,3 do local data = mfdata[sector*4+block] if data==nil then SECTOR:append{ classname="block", label="block", id=block, alt="unaccessible" } else ITEM = SECTOR:append{ classname="block", label="block", id=block, size=#data, val=data } if block == 3 then mifare_trailer(ITEM,data) PERMS = SECTOR:append{ classname="block", label="permissions"} mifare_display_permissions(PERMS,data) else mifare_textify(ITEM,data) end end end end end -- -- START OF SCRIPT -- local resp = ui.question("Do you wish to use a key file or try default mifare keys?", {"Use default keys", "Load keys from file"}) local keys, mfdata, mfuid keys = nil if resp == 1 then keys = MIFARE_STD_KEYS elseif resp == 2 then local fpath, fname = ui.select_file("Load mifare key file",nil,nil) if fname then keys = mifare_load_keys(fname) end end if keys==nil then log.print(log.ERROR,"Aborted script: mifare key selection was cancelled.") elseif card.connect() then CARD = card.tree_startup("Mifare") mfdata, mfuid = mifare_read_card(keys) if mfdata~=nil and mfuid~=nil then mifare_display(CARD, mfdata, mfuid) end card.disconnect() end
gpl-3.0
moderna/ShivaSensorRigging
shiva/SensorRigging/Resources/Scripts/SensorRigging_Handler_onMouseWheel.lua
1
1251
-------------------------------------------------------------------------------- -- Handler.......... : onMouseWheel -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function SensorRigging.onMouseWheel( nDelta ) -------------------------------------------------------------------------------- if ( not (this.keyControlDown() or this.keyAltDown()) ) then local dx = nDelta * 0.1 this.camDist( this.camDist() + dx ) elseif( this.keyControlDown() and not this.keyAltDown() ) then this.selectionOpacity( math.clamp( this.selectionOpacity() + nDelta * 0.1, 0, 1 ) ) elseif( this.keyAltDown() and not this.keyControlDown() ) then this.animationSpeed( math.clamp( this.animationSpeed() + nDelta * 5, 0, 200 ) ) local hScene = application.getCurrentUserScene() animation.setPlaybackSpeed( this.model(), 0, this.animationSpeed() ) end -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
gpl-3.0
liruqi/bigfoot
Interface/AddOns/DBM-Scenario-MoP/BattleontheHighSeas/BattleHighSeas.lua
1
2583
local mod = DBM:NewMod("d652", "DBM-Scenario-MoP") local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 2 $"):sub(12, -3)) mod:SetZone() mod:RegisterCombat("scenario", 1099) mod:RegisterEventsInCombat( "SPELL_CAST_START 141438 141327 141187 136473", "UNIT_DIED", "UNIT_SPELLCAST_SUCCEEDED target focus" ) --Lieutenant Drak'on local warnSwashbuckling = mod:NewSpellAnnounce(141438, 4) --Lieutenant Fizzel local warnThrowBomb = mod:NewSpellAnnounce(132995, 3, nil, false) local warnVolatileConcoction = mod:NewSpellAnnounce(141327, 3) --Admiral Hagman local warnVerticalSlash = mod:NewSpellAnnounce(141187, 4) local warnCounterShot = mod:NewSpellAnnounce(136473, 2, nil, mod:IsSpellCaster()) --Lieutenant Drak'on local specWarnSwashbuckling = mod:NewSpecialWarningSpell(141438) --Lieutenant Fizzel local specWarnVolatileConcoction= mod:NewSpecialWarningSpell(141327) --Admiral Hagman local specWarnVerticalSlash = mod:NewSpecialWarningSpell(141187) local specWarnCounterShot = mod:NewSpecialWarningCast(136473, mod:IsSpellCaster()) --Lieutenant Drak'on local timerSwashbucklingCD = mod:NewNextTimer(16, 141438) --Lieutenant Fizzel local timerThrowBombCD = mod:NewNextTimer(6, 132995, nil, false) --Admiral Hagman local timerVerticalSlashCD = mod:NewCDTimer(18, 141187)--18-20 second variation local timerCounterShot = mod:NewCastTimer(1.5, 136473) mod:RemoveOption("HealthFrame") function mod:SPELL_CAST_START(args) if args.spellId == 141438 then warnSwashbuckling:Show() specWarnSwashbuckling:Show() timerSwashbucklingCD:Start() elseif args.spellId == 141327 then warnVolatileConcoction:Show() specWarnVolatileConcoction:Show() elseif args.spellId == 141187 then warnVerticalSlash:Show() specWarnVerticalSlash:Show() timerVerticalSlashCD:Start() elseif args.spellId == 136473 then warnCounterShot:Show() specWarnCounterShot:Show() timerCounterShot:Start() end end function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 70963 then--Lieutenant Fizzel timerThrowBombCD:Cancel() elseif cid == 67391 then--Lieutenant Drak'on timerSwashbucklingCD:Cancel() elseif cid == 67426 then--Admiral Hagman timerVerticalSlashCD:Cancel() end end function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId) if spellId == 132995 and self:AntiSpam() then self:SendSync("ThrowBomb") end end function mod:OnSync(msg) if msg == "ThrowBomb" then warnThrowBomb:Show() timerThrowBombCD:Start() end end
mit
codeacula/lusternia-neko
Stats/Stat.lua
1
6158
-- The stat handler Stat = {} -- All of the stats Stats = {} -- Metatables -- Lets the stats reference the main table functions Stat.__index = Stat -- Lets us quickly determine if two stats are the same Stat.__eq = function(t1, t2) return t1.name == t2.name end -- Metatable functions for better sorting Stat.__le = function(t1, t2) return t1:weight() <= t2:weight() end Stat.__lt = function(t1, t2) return t1:weight() < t2:weight() end function Stat:addCure(cure, cureLevel) table.insert(self.cures, cure) self.cureLevels[cure.name] = cureLevel end -- Does the stat need a cure? function Stat:canCure() if self.numeric == false or self.current == nil or #self.cures == nil then return false end local willCure = false for _, cure in ipairs(self.cures) do -- Automatically return false, because we're waiting to see the result if cure.sent then return false end if self:percent() <= self.cureLevels[cure.name] then willCure = true end end return willCure end function Stat:cureSent() for _, cure in ipairs(self.cures) do if cure.sent then return true end end return false end function Stat:display() if self.max == 0 then Text.display(self.prompt..":") Text.display(self.maxColor, self.current.." ") return end -- Set the default color used and find the ration local amount = self:percent() if amount == nil then return end -- Calculate the difference if amount >= 100 then color = self.maxColor elseif amount >= 80 then color = self.normalColor elseif amount >= 30 then color = self.warningColor else color = self.dangerColor end Text.display(self.prompt..":") Text.display(color, self.current.." ") end -- Process dem stats function Stat.handleStats() if Neko.paused then return end local highestStat = nil if Neko.haveFlag("noStats") or Stats.hp.current == 0 then return true end for _, stat in pairs(Stats) do if stat:canCure() then if highestStat == nil or stat:weight() < highestStat:weight() then highestStat = stat end end end if highestStat == nil then return end highestStat:send() end -- Make a new affliiction function Stat.new(statName) -- The public interface local newItem = {} setmetatable(newItem, Stat) -- Change since the last update newItem.change = 0 -- The cures for the stat newItem.cures = {} -- At what level do we send the cures? newItem.cureLevels = {} -- Current level of the stat newItem.current = 0 -- What the stat's current cure priority defaults to newItem.defaultPriority = Neko.maxPriority -- What's our default cure level? newItem.defaultCureLevel = 90 -- When printing out the stat, what color should it be when in danger? newItem.dangerColor = Text.colors.red -- The GMCP field to read from stats newItem.field = statName -- The maximum level for the stat newItem.max = 0 -- What color to show when the stat is maxed newItem.maxColor = Text.colors.green -- What field references the maximum stat newItem.maxField = nil -- The name of the stat newItem.name = statName -- Color to display the stat when it's normal newItem.normalColor = Text.colors.darkgreen -- Is it a numeric stat? newItem.numeric = true -- The prompt character newItem.prompt = string.upper(string.sub(statName, 1, 1)) -- What is the warning color of the stat? newItem.warningColor = Text.colors.yellow -- Weigh the item so it sets its default newItem:setWeight() -- Assign this to the stat Stats[statName] = newItem -- Run the file if it exists if (fileExists(BASEPATH.."stats/"..statName..".lua")) then loadFile("stats/"..statName..".lua") end return newItem end function Stat:percent(places) if places == nil then places = 2 end if places ~= false then return round(((self.current/self.max)*100), places) else return (self.current/self.max)*100 end end function Stat:send() local selectedCure = nil for _, cure in ipairs(self.cures) do if not cure:canSend() then elseif self:percent() <= self.cureLevels[cure.name] and (not selectedCure or selectedCure:weight() <= cure:weight()) then selectedCure = cure end end if selectedCure then selectedCure:send() end end function Stat:showChange() local change = self.change if change == nil or change == 0 then return end if change > 0 then Text.display(self.maxColor, "+"..change.." ") else Text.display(self.normalColor, change.." ") end end function Stat:setWeight(priority) if priority ~= nil then self.currentPriority = priority return end self.currentPriority = self.defaultPriority return end -- Forces the stat to update its data from GMCP function Stat:update() if gmcp.Char.Vitals[self.field] then if self.numeric then local gmcpCurrent = tonumber(gmcp.Char.Vitals[self.field]) self.change = tonumber(gmcpCurrent - self.current) self.current = tonumber(gmcpCurrent) else self.current = gmcp.Char.Vitals[self.field] end end if gmcp.Char.Vitals[self.maxField] then if self.numeric then self.max = tonumber(gmcp.Char.Vitals[self.maxField]) else self.max = gmcp.Char.Vitals[self.maxField] end end end -- Update all the stats function Stat.updateStats() for name, stat in pairs(Stats) do stat:update() end end Neko.addGmcp("Char.Vitals", Stat.updateStats) -- Returns the stat's current weight. -- Override for custom weighing function Stat:weight() return self.currentPriority end
mit
davideuler/lsyncd
tests/schedule.lua
13
1962
#!/usr/bin/lua require("posix") dofile("tests/testlib.lua") cwriteln("****************************************************************") cwriteln(" Testing Lsyncd scheduler ") cwriteln("****************************************************************") local tdir, srcdir, trgdir = mktemps() local logfile = tdir .. "log" local cfgfile = tdir .. "config.lua" local logs = {"-log", "all" } writefile(cfgfile, [[ settings = { logfile = "]]..logfile..[[", log = all, nodaemon = true, maxProcesses = 1 } -- continously touches a file acircuit = { delay = 0, onStartup = "sleep 3 && touch ^source/a", onCreate = "sleep 3 && touch ^source/a", } -- continously touches b file bcircuit = { delay = 0, onStartup = "sleep 3 && touch ^source/b", onCreate = "sleep 3 && touch ^source/b", } -- continously touches c file ccircuit = { delay = 0, onStartup = "sleep 3 && touch ^source/c", onCreate = "sleep 3 && touch ^source/c", } sync {acircuit, source ="]]..srcdir..[[", target = "]]..trgdir..[["} sync {bcircuit, source ="]]..srcdir..[[", target = "]]..trgdir..[["} sync {ccircuit, source ="]]..srcdir..[[", target = "]]..trgdir..[["} ]]); -- test if the filename exists, fails if this is different to expect local function testfile(filename) local stat, err = posix.stat(filename) if not stat then cwriteln("failure: ",filename," missing"); os.exit(1); end end cwriteln("starting Lsyncd"); local pid = spawn("./lsyncd", cfgfile, unpack(logs)); cwriteln("waiting for Lsyncd to do a few cycles"); posix.sleep(30) cwriteln("look if every circle got a chance to run"); testfile(srcdir.."a") testfile(srcdir.."b") testfile(srcdir.."c") cwriteln("killing started Lsyncd"); posix.kill(pid); local _, exitmsg, lexitcode = posix.wait(lpid); cwriteln("Exitcode of Lsyncd = ", exitmsg, " ", lexitcode); posix.sleep(1); if lexitcode == 0 then cwriteln("OK"); end os.exit(lexitcode); -- TODO remove temp
gpl-2.0
KamilKZ/love2d-netmap
netmap/main.lua
1
9592
local updateTime = 15 --0 or a small value will still wait for the current cycle to finish ( multithreading would help ) local width = 1920 local height = 1080 local numberOfThreads = 10 --this can eat cpu local SAVE_ALL = false --save all (timestamped) images to %APPDATA%/Love/netmap, or just the most current (overwrite) _DEBUG = false _DEBUG_VERBOSE = false _DEBUG_SKIP = false _DEBUG_QUERY_LIMIT = 0 --Includes ltc = require( "lTcpConnections") http = require( "socket.http" ) json = require( "json" ) timer = require( "timer" ) http.TIMEOUT = 5 local httpRequestTTime = timer("http requests") local drawMapTime = timer("map draw") local totalUpdateTime = timer("map update") local lastUpdate = -100 local mappedPoints = {} local threads = {} local connections = {} Debugs = {} Debugs["connection.new"] = false Debugs["connection.coordinates"] = false Debugs["response.raw"] = false Debugs["response.late"] = false Debugs["response.invalid"] = false Debugs["table.filter"] = false Debugs["table.filter.dump"] = false function Debug(id, func, ...) if Debugs[id] then func(...) end end function table.print( t, n ) n = n or "table" local str = "["..n.."]\n" for k,v in pairs( t ) do str = str .. "\t["..k.."]=>"..tostring(v).."\n" end print(str) end function table.filter( t, filter, filter_func ) filter_func = filter_func or function(k,v) return k end local t1 = {} Debug("table.filter", print, "filtering table") Debug("table.filter.dump", table.print, t, "table-before") Debug("table.filter.dump", table.print, filter, "filter") for k,v in pairs( filter ) do local i = filter_func(k,v) if t[i] then t1[i] = t[i] Debug("table.filter", print, "keeping: ["..k.."] "..i) else Debug("table.filter", print, "discarding: ["..k.."] "..i) end end Debug("table.filter.dump", table.print, t1, "table-after") return t1 end function HSL(h, s, l) if s == 0 then return l,l,l end h, s, l = h/256*6, s/255, l/255 local c = (1-math.abs(2*l-1))*s local x = (1-math.abs(h%2-1))*c local m,r,g,b = (l-.5*c), 0,0,0 if h < 1 then r,g,b = c,x,0 elseif h < 2 then r,g,b = x,c,0 elseif h < 3 then r,g,b = 0,c,x elseif h < 4 then r,g,b = 0,x,c elseif h < 5 then r,g,b = x,0,c else r,g,b = c,0,x end return math.ceil((r+m)*256),math.ceil((g+m)*256),math.ceil((b+m)*256) end function math.dist(x1,y1, x2,y2) return ((x2-x1)^2+(y2-y1)^2)^0.5 end function math.angle(x1,y1, x2,y2) return math.atan2(x2-x1, y2-y1) end function geoTo2D( longitude, latitude ) return (longitude + 180) * (width / 360), ((latitude * -1) + 90) * (height / 180); end function generateColor() local r,g,b = HSL( math.random( 0, 360 ), math.random( 0, 150 ) + 100, math.random( 0, 150 ) + 100 ) return {r, g, b} end if(_DEBUG_SKIP) then mappedPoints = {{ip="255.255.255.255", latitude="200", longitude="15"}, {ip="255.255.255.255", latitude="15", longitude="35"}} end function love.load() earth_mask_shader = love.graphics.newShader("earth_mask_shader.frag") channel_in = love.thread.getChannel("downloaders_in") channel_out = love.thread.getChannel("downloaders_out") love.filesystem.setIdentity("netmap") mapColor = { 200, 200, 200 } mapImage = love.graphics.newImage( "map.png" ) map = love.graphics.newCanvas( width, height ) font = love.graphics.newFont(12) love.graphics.setLineWidth(2) love.graphics.setPointSize(5) scale_x = width / mapImage:getWidth() scale_y = height / mapImage:getHeight() local js = http.request('http://freegeoip.net/json/') client = decode(js) client_x, client_y = geoTo2D( client["longitude"], client["latitude"] ) pathToAppdata = love.filesystem.getAppdataDirectory().."/LOVE/netmap/" createThreads( numberOfThreads ) end function drawTick() drawMapTime:reset() drawMapTime:start() map:clear() love.graphics.setCanvas( map ) love.graphics.setColor( mapColor ) love.graphics.setShader(earth_mask_shader) love.graphics.draw( mapImage, 0, 0, 0, scale_x, scale_y ) love.graphics.setShader() local count = 0 for k,v in pairs(connections) do if not v.draw and v.data then local x,y = geoTo2D( v["data"]["longitude"], v["data"]["latitude"] ) local distance = math.dist( client_x, client_y, x, y ) local direction = math.angle( client_x, client_y, x, y ) local r,g,b = generateColor() connections[k].draw = {x=x,y=y,distance=distance,direction=direction,r=r,g=g,b=b} end if not v.data then connections[k] = nil elseif v.draw then local e = v.draw --local segments = math.floor( distance / 10 )+1 --local aoa = math.sin(direction)* 2*math.pi * segments love.graphics.setColor( e.r, e.g, e.b, 150 ) love.graphics.point( e.x, e.y ) love.graphics.line( client_x, client_y, e.x, e.y ) love.graphics.setColor( e.r, e.g, e.b, 255 ) love.graphics.print( string.format("%s", v["data"]["city"] or "N/A"), e.x, e.y ) count = count + 1 end end local dateTime = os.date("%Y-%m-%d %H:%M:%S") love.graphics.setColor(255,255,255,255) love.graphics.print( dateTime, 10, 10 ) love.graphics.print( "Number of connections: "..#allConnections, 10, 24 ) love.graphics.print( "Number of external connections: "..count, 10, 38 ) love.graphics.print( "Number of http requests: "..#getURL, 10, 52 ) love.graphics.print( httpRequestTTime:tostring(), 10, 66 ) love.graphics.print( drawMapTime:tostring(), 10, 80 ) love.graphics.print( totalUpdateTime:tostring(), 10, 94 ) if totalUpdateTime:getTime() > updateTime then love.graphics.setColor( 255,50,50,255 ) love.graphics.print( string.format("Time behind: %.4f seconds", totalUpdateTime:getTime()-updateTime), 10, 108 ) end love.graphics.setCanvas() local file = string.format( "netmap %s.png", os.date("%Y-%m-%d_%H-%M-%S") ) local filedir = pathToAppdata..file if SAVE_ALL then map:getImageData():encode(file) end map:getImageData():encode("current.png") print("Setting as wallpaper") --os.execute([["netmap\setWallpaper.bat"]]) os.execute("cd") os.execute([[type NUL && "netmap\WallpaperChanger.exe" "%AppData%\LOVE\netmap/current.png" 4]]) drawMapTime:stop() end getURL = {} function get( uri ) table.insert( getURL, uri ) end function createThreads( n ) for i=1, n do local t = love.thread.newThread( "downloader.lua" ) table.insert( threads, {t,i} ) threads[i][1]:start() end end function dispatcher() httpRequestTTime:reset() httpRequestTTime:start() local time = love.timer.getTime() --The reason for using feed-receive-process over feed-receive and process --was that I thought not clearing the pipe would cause corruption, --but in actual fact, there is nothing to feed, so there would be no /more/ --data being fed and therefore no corruption. Meaning it's safer and more efficient --to use a single loop for receive-and-procces for k,v in pairs( getURL ) do --feed threads channel_in:push(v) end local received = 0 while ( not ( _DEBUG_QUERY_LIMIT > 0 and received > _DEBUG_QUERY_LIMIT ) and not ( #getURL == received )) do -- no more threads to run --take cotton from threads --master/slave right? if channel_out:getCount()>0 then local response = channel_out:pop() received = received + 1 Debug( "response.raw", print, response ) local t = (string.sub(response, 0, 1) == "{") and decode(response) or nil --json curlie, something fucks up in the decorder otherwise if ( type(t) == "table" ) then if connections[t["ip"]] then connections[t["ip"]].data=t connections[t["ip"]].update=time Debug( "connection.coordinates", print, t["latitude"], t["longitude"] ) else Debug( "response.late", print, "Response for "..t["ip"].." returned late!" ) end else Debug( "response.invalid", print, "Exception, invalid data received:\n"..response ) end end end httpRequestTTime:stop() end function getConnections() getURL = {} allConnections = ltc.getConnections() local time = love.timer.getTime() for k,v in pairs( allConnections ) do if not(string.match( v["remote"]["address"], '192%.168%.%d+%d-%d-%.%d+%d-%d-' ) or string.match( v["remote"]["address"], '127%.%d+%d-%d-%.%d+%d-%d-%.%d+%d-%d-' ) or v["remote"]["address"] == "255.255.255.255" ) then if (not connections[v["remote"]["address"]] and v["state"] == "Established") then --if not update/new connection Debug( "connection.new", print, "New connection: " .. v["remote"]["address"] ) connections[v["remote"]["address"]]=v--create table get('http://freegeoip.net/json/'..v["remote"]["address"]) --GET --elseif connections[v["remote"]["address"]["update"]] and ((connections[v["remote"]["address"]["update"]]+60) < time) then --if update -- get('http://freegeoip.net/json/'..v["remote"]["address"]) --GET, dont reset table! end else if _DEBUG then print("Discarding remote IP address: "..v["remote"]["address"]) end end end connections = table.filter( connections, allConnections, function(k,v) return v.remote.address end ) dispatcher() end function love.update(dt) if love.timer.getTime() > lastUpdate + updateTime then totalUpdateTime:reset() totalUpdateTime:start() lastUpdate = love.timer.getTime() startTime = lastUpdate if not _DEBUG_SKIP or not _DEBUG then getConnections() end drawTick() totalUpdateTime:stop() else love.timer.sleep(1) end end function love.draw() love.graphics.setColor(255,255,255) love.graphics.draw(map, 0, 0, 0, love.window.getWidth()/mapImage:getWidth(), love.window.getHeight()/mapImage:getHeight()) end
mit
BeaconNet/sPhone
src/bin/wget.lua
3
1187
--[[ wget made by dan200 ]] local function printUsage() print( "Usage:" ) print( "wget <url> <filename>" ) end local tArgs = { ... } if #tArgs < 2 then printUsage() return end if not http then printError( "wget requires http API" ) printError( "Set http_enable to true in ComputerCraft.cfg" ) return end local function get( sUrl ) write( "Connecting to " .. sUrl .. "... " ) local ok, err = http.checkURL( sUrl ) if not ok then print( "Failed." ) if err then printError( err ) end return nil end local response = http.get( sUrl ) if not response then print( "Failed." ) return nil end print( "Success." ) local sResponse = response.readAll() response.close() return sResponse end -- Determine file to download local sUrl = tArgs[1] local sFile = tArgs[2] local sPath = shell.resolve( sFile ) if fs.exists( sPath ) then print( "File already exists" ) return end -- Do the get local res = get( sUrl ) if res then local file = fs.open( sPath, "w" ) file.write( res ) file.close() print( "Downloaded as "..sFile ) end
mit
LuaDist/luaglut
macros.lua
1
6798
-- ====================================================================== -- macros.lua - Copyright (C) 2005-2006 Varol Kaptan -- see LICENSE for more information -- ====================================================================== -- vim: set ts=3 et: --[[ Function signatures are encoded as a combination of letters and numbers. The meaning of the letters is as follows: OpenGL Datatypes ---------------- B boolean Y GLbyte uY GLubyte H GLshort uH GLushort I GLint uI GLuint Z GLsizei E GLenum T GLbitfield F GLfloat, GLclampf D GLdouble, GLclampd C Datatypes ----------- i int b boolean f float d double s C style string (zero terminated) p a generic pointer (void *) v void Numbers following a letter sequence mean that there are N parameters of that particular type. --]] local ptypes = { -- OpenGL Datatypes B = { type = 'GLboolean', getf = 'check_GLboolean', putf = 'lua_pushnumber' }, Y = { type = 'GLbyte', getf = 'check_GLbyte', putf = 'lua_pushnumber' }, uY = { type = 'GLubyte', getf = 'check_GLubyte', putf = 'lua_pushnumber' }, H = { type = 'GLshort', getf = 'check_GLshort', putf = 'lua_pushnumber' }, uH = { type = 'GLushort', getf = 'check_GLushort', putf = 'lua_pushnumber' }, I = { type = 'GLint', getf = 'check_GLint', putf = 'lua_pushnumber' }, uI = { type = 'GLuint', getf = 'check_GLuint', putf = 'lua_pushnumber' }, Z = { type = 'GLsizei', getf = 'check_GLsizei', putf = 'lua_pushnumber' }, E = { type = 'GLenum', getf = 'check_GLenum', putf = 'lua_pushnumber' }, T = { type = 'GLbitfield', getf = 'check_GLbitfield', putf = 'lua_pushnumber' }, F = { type = 'GLfloat', getf = 'check_GLfloat', putf = 'lua_pushnumber' }, D = { type = 'GLdouble', getf = 'check_GLdouble', putf = 'lua_pushnumber' }, -- C Datatypes b = { type = 'int', getf = 'check_int', putf = 'lua_pushboolean'}, i = { type = 'int', getf = 'check_int', putf = 'lua_pushnumber' }, ui = { type = 'unsigned int', getf = 'check_uint', putf = 'lua_pushnumber' }, f = { type = 'float', getf = 'check_float', putf = 'lua_pushnumber' }, d = { type = 'double', getf = 'check_double', putf = 'lua_pushnumber' }, s = { type = 'const char *', getf = 'check_string', putf = 'lua_pushstring' }, p = { type = 'void *', getf = 'check_lightuserdata', putf = 'lua_pushlightuserdata' }, v = { type = 'void', getf = nil, putf = nil }, } local opengl_numeric_types = { 'B', 'Y', 'uY', 'H', 'uH', 'I', 'uI', 'Z', 'E', 'T', 'F', 'D' } local c_numeric_types = { 'i', 'ui', 'f', 'd' } if _VERSION == 'Lua 5.1' then -- here is the Lua 5.1 version printf = loadstring('return function(...) io.write(string.format(...)) end')() else -- and here is the Lua 5.0.2 version printf = loadstring('return function(...) io.write(string.format(unpack(arg))) end')() end function gen_macro(sig) local args = {} local i, imax = 1, string.len(sig) local nxt, old_nxt local prefix = '' while i <= imax do nxt, old_nxt = string.sub(sig, i, i), nxt if nxt == 'u' then prefix = nxt elseif tonumber(nxt) == nil then table.insert(args, prefix .. nxt) prefix = '' else for j = 1,tonumber(nxt)-1 do table.insert(args, prefix .. old_nxt) end prefix = '' end i = i + 1 end local n = table.getn(args) printf('\n#define FUN_%s(name)\\\n' .. 'LUA_API int L ## name (lua_State *L) {\\\n', sig) if sig == 'v' then printf(' (void) L; /* unused */ \\\n') end for i = 2, n do local k, v = i-1, ptypes[args[i]] printf(' %s a%d = (%s) %s(L, %d);\\\n', v.type, k, v.type, v.getf, k) end if ptypes[args[1]].type ~= 'void' then printf(' %s(L, (%s) ', ptypes[args[1]].putf, ptypes[args[1]].type); else printf(' ') end printf('name(') if n > 1 then printf('a1') end for i = 3, n do printf(', a%d', i-1) end printf(')') if ptypes[args[1]].type ~= 'void' then printf(');\\\n return 1;\\\n}\n') else printf(';\\\n return 0;\\\n}\n') end end local signatures = { -- signatures from luagl.c 'BE', 'BuI', 'E', 'IE', 'sE', 'uIZ', 'v', 'vB', 'vB4', 'vD', 'vD2', 'vD3', 'vD4', 'vD6', 'vE', 'vE2', 'vE2D', 'vE2F', 'vE2p', 'vE3', 'vEF', 'vEI', 'vEI2Z2IE2p', 'vEI2ZIE2p', 'vEIE2p', 'vEIEp', 'vEIp', 'vEIuI', 'vEp', 'vEuI', 'vF', 'vF2', 'vF4', 'vI', 'vI2Z2', 'vI2Z2E', 'vI2Z2E2p', 'vIuH', 'vp', 'vT', 'vuI', 'vuIE', 'vuIZ', 'vZ2E2p', 'vZ2F4p', 'vZEp', 'vZp', -- signatures from luaglut.c 'Fi2', 'i', 'iD3p6', 'iE', 'IEIZ2E2p', 'IEIZE2p', 'ip', 'ipi', 'is', 'p', 'ps', 'v', 'vD', 'vD2I2', 'vD4', 'vD4p', 'vD9', 'vDI2', 'vE', 'vi', 'vI', 'vi2', 'viF3', 'visi', 'vp', 'vpi', 'vps', 'vs', 'vsi', 'vui', } print [[ /* vim: set ts=3 et: */ /* This file is automatically generated by menus.lua */ inline const char * check_string(lua_State *L, int n) { if (lua_type(L,n) != LUA_TSTRING) luaL_typerror(L, n, lua_typename(L, LUA_TSTRING)); return (const char *) lua_tostring(L, n); } inline const void * check_lightuserdata(lua_State *L, int n) { if (lua_type(L,n) != LUA_TLIGHTUSERDATA) luaL_typerror(L, n, "lightuserdata"); return (const void *) lua_touserdata(L, n); } #define CONSTANT(name)\ lua_pushstring(L, #name);\ lua_pushnumber(L, name);\ lua_settable(L, LUA_GLOBALSINDEX); #define POINTER(name)\ lua_pushstring(L, #name);\ lua_pushlightuserdata(L, name);\ lua_settable(L, LUA_GLOBALSINDEX); #define FUN_SPEC(name) #define FUN(name)\ lua_register(L, #name, L ## name); ]] -- Generate numeric OpenGL datatype getters (check_GL*) for k, v in ipairs(opengl_numeric_types) do local tname, fname = ptypes[v].type, ptypes[v].getf printf([[ inline %s %s(lua_State *L, int n) { if (lua_type(L,n) != LUA_TNUMBER) luaL_typerror(L, n, "number(%s)"); return (%s) lua_tonumber(L, n); } ]], tname, fname, tname, tname) end -- Generate numeric C datatype getters (check_*) for k, v in ipairs(c_numeric_types) do local tname, fname = ptypes[v].type, ptypes[v].getf printf([[ inline %s %s(lua_State *L, int n) { if (lua_type(L,n) != LUA_TNUMBER) luaL_typerror(L, n, "number(%s)"); return (%s) lua_tonumber(L, n); } ]], tname, fname, tname, tname) end -- Generate macros for defined function signatures table.foreach(signatures, function(k, v) gen_macro(v) end)
mit
bb010g/otouto
otouto/plugins/starwars_crawl.lua
1
2217
--[[ starwars_crawl.lua Returns the opening "crawl" of a given Star Wars film. Based on a plugin by matthewhesketh. Copyright 2016 topkecleon <drew@otou.to> This code is licensed under the GNU AGPLv3. See /LICENSE for details. ]]-- local HTTP = require('socket.http') local JSON = require('dkjson') local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local starwars = {name = 'starwars'} function starwars:init() starwars.triggers = utilities.triggers(self.info.username, self.config.cmd_pat) :t('starwars', true):t('sw', true).table starwars.doc = self.config.cmd_pat .. [[starwars <query> Returns the opening crawl from the specified Star Wars film. Alias: ]] .. self.config.cmd_pat .. 'sw' starwars.command = 'starwars <query>' starwars.base_url = 'http://swapi.co/api/films/' end local films_by_number = { ['phantom menace'] = 4, ['attack of the clones'] = 5, ['revenge of the sith'] = 6, ['new hope'] = 1, ['empire strikes back'] = 2, ['return of the jedi'] = 3, ['force awakens'] = 7 } local corrected_numbers = { 4, 5, 6, 1, 2, 3, 7 } function starwars:action(msg) local input = utilities.input_from_msg(msg) if not input then utilities.send_reply(msg, starwars.doc, 'html') return end bindings.sendChatAction{chat_id = msg.chat.id, action = 'typing'} local film if tonumber(input) then input = tonumber(input) film = corrected_numbers[input] or input else for title, number in pairs(films_by_number) do if string.match(input, title) then film = number break end end end if not film then utilities.send_reply(msg, self.config.errors.results) return end local url = starwars.base_url .. film local jstr, code = HTTP.request(url) if code ~= 200 then utilities.send_reply(msg, self.config.errors.connection) return end local output = '*' .. JSON.decode(jstr).opening_crawl .. '*' utilities.send_message(msg.chat.id, output, true, nil, true) end return starwars
agpl-3.0
SINGLECYBER/CyberSource
bot/seedbot.lua
1
11661
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 = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Our team! SINGLE CYBER (@SINGLECYBER) Our channels: English: @SINGLECYBERCHANNEL Persian: @SINGLECYBERCHANNEL ]], 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 】 اخراج کاربر از گروه بطور موقت به طوریکه کاربر با لینک میتواند دوباره به گروه بیوندد ➤ 【 اجرا با ریپلی یا ایدی شخص 】 ➲ ban 【 username|id 】 اخراج دائمی کاربر از گروه بطوری که کاربر با لینک نیز نمیتواند به گروه بازگردد ➤ 【 اجرا با ریپلی یا ایدی شخص 】 ➲ unban 【 id 】 خارج کردن کاربر از لیست افرادی که ممنوعیت ورود به گروه را دارند ➤ 【 اجرا با ریپلی یا ایدی شخص 】 ➲ who لیست اعضای گروه ➤ ➲ modlist لیست مدیران گروه ➤ ➲ promote 【 username 】 ارتقا مقام یک کاربر به مدیر ➤ ➲ demote 【 username 】 عزل کردن یک کاربر از مقام مدیریت در گروه ➤ ➲ kickme اخراج شما توسط ربات از گروه ➤ ➲ about توضیحات گروه ➤ ➲ setphoto تنظیم کردن عکس پروفایل گروه ➤ ➲ setname 【 name 】 تنظیم کردن نام گروه ➤ ➲ rules نمایش قوانین گروه ➤ ➲ id دریافت ایدی عددی شما و گروه ➤ ➲ help نمایش دوباره راهنمای کروه ➤ ➲ lock 【 member ، name ، bots ، leave 】 قفل کردن ➤ 【 دعوت کاربران به گروه ، نام گروه ، دعوت ربات به گروه ، بازگشت دوباره به گروه پس از خروج 】 ➲ unlock 【 member ، name ، bots ، leave 】 باز کردن ➤ 【 دعوت از دوستان ، نام گروه ، دعوت ربات به گروه ، بازگشت دوباره به گروه پس از خروج】 ➲ set rules 【 text 】 تنظیم 【 متن قوانین 】 در گروه ➤ ➲ set about 【 text 】 تنظیم 【 متن توضیحات 】 در گروه ➤ ➲ settings نمایش تنظیمات گروه ➤ ➲ newlink ساخت / تعویض لینک گروه ➤ ➲ link دریافت لینک گروه ➤ ➲ owner Returns group owner ؟؟ ➲ setowner 【 username 】 Will set id as owner ➲ setflood 【 value 】 تنظیم 【 عدد تعین شده 】 به عنوان تعداد پیام محاز پشت سر هم ➤ ➲ stats پیام ها ➲ save 【 value 】 [text 】 ت ➲ 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
agpl-3.0
RUlanowicz/MyBreakout
cocos2d/external/lua/luajit/src/dynasm/dasm_mips.lua
74
28080
------------------------------------------------------------------------------ -- DynASM MIPS module. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "mips", description = "DynASM MIPS module", version = "1.3.0", vernum = 10300, release = "2012-01-23", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable = assert, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch = _s.match, _s.gmatch local concat, sort = table.concat, table.sort local bit = bit or require("bit") local band, shl, sar, tohex = bit.band, bit.lshift, bit.arshift, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(0xff000000 + w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n >= 0xff000000 then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = { sp="r29", ra="r31" } -- Ext. register name -> int. name. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) if s == "r29" then return "sp" elseif s == "r31" then return "ra" end return s end ------------------------------------------------------------------------------ -- Template strings for MIPS instructions. local map_op = { -- First-level opcodes. j_1 = "08000000J", jal_1 = "0c000000J", b_1 = "10000000B", beqz_2 = "10000000SB", beq_3 = "10000000STB", bnez_2 = "14000000SB", bne_3 = "14000000STB", blez_2 = "18000000SB", bgtz_2 = "1c000000SB", addi_3 = "20000000TSI", li_2 = "24000000TI", addiu_3 = "24000000TSI", slti_3 = "28000000TSI", sltiu_3 = "2c000000TSI", andi_3 = "30000000TSU", lu_2 = "34000000TU", ori_3 = "34000000TSU", xori_3 = "38000000TSU", lui_2 = "3c000000TU", beqzl_2 = "50000000SB", beql_3 = "50000000STB", bnezl_2 = "54000000SB", bnel_3 = "54000000STB", blezl_2 = "58000000SB", bgtzl_2 = "5c000000SB", lb_2 = "80000000TO", lh_2 = "84000000TO", lwl_2 = "88000000TO", lw_2 = "8c000000TO", lbu_2 = "90000000TO", lhu_2 = "94000000TO", lwr_2 = "98000000TO", sb_2 = "a0000000TO", sh_2 = "a4000000TO", swl_2 = "a8000000TO", sw_2 = "ac000000TO", swr_2 = "b8000000TO", cache_2 = "bc000000NO", ll_2 = "c0000000TO", lwc1_2 = "c4000000HO", pref_2 = "cc000000NO", ldc1_2 = "d4000000HO", sc_2 = "e0000000TO", swc1_2 = "e4000000HO", sdc1_2 = "f4000000HO", -- Opcode SPECIAL. nop_0 = "00000000", sll_3 = "00000000DTA", movf_2 = "00000001DS", movf_3 = "00000001DSC", movt_2 = "00010001DS", movt_3 = "00010001DSC", srl_3 = "00000002DTA", rotr_3 = "00200002DTA", sra_3 = "00000003DTA", sllv_3 = "00000004DTS", srlv_3 = "00000006DTS", rotrv_3 = "00000046DTS", srav_3 = "00000007DTS", jr_1 = "00000008S", jalr_1 = "0000f809S", jalr_2 = "00000009DS", movz_3 = "0000000aDST", movn_3 = "0000000bDST", syscall_0 = "0000000c", syscall_1 = "0000000cY", break_0 = "0000000d", break_1 = "0000000dY", sync_0 = "0000000f", mfhi_1 = "00000010D", mthi_1 = "00000011S", mflo_1 = "00000012D", mtlo_1 = "00000013S", mult_2 = "00000018ST", multu_2 = "00000019ST", div_2 = "0000001aST", divu_2 = "0000001bST", add_3 = "00000020DST", move_2 = "00000021DS", addu_3 = "00000021DST", sub_3 = "00000022DST", negu_2 = "00000023DT", subu_3 = "00000023DST", and_3 = "00000024DST", or_3 = "00000025DST", xor_3 = "00000026DST", not_2 = "00000027DS", nor_3 = "00000027DST", slt_3 = "0000002aDST", sltu_3 = "0000002bDST", tge_2 = "00000030ST", tge_3 = "00000030STZ", tgeu_2 = "00000031ST", tgeu_3 = "00000031STZ", tlt_2 = "00000032ST", tlt_3 = "00000032STZ", tltu_2 = "00000033ST", tltu_3 = "00000033STZ", teq_2 = "00000034ST", teq_3 = "00000034STZ", tne_2 = "00000036ST", tne_3 = "00000036STZ", -- Opcode REGIMM. bltz_2 = "04000000SB", bgez_2 = "04010000SB", bltzl_2 = "04020000SB", bgezl_2 = "04030000SB", tgei_2 = "04080000SI", tgeiu_2 = "04090000SI", tlti_2 = "040a0000SI", tltiu_2 = "040b0000SI", teqi_2 = "040c0000SI", tnei_2 = "040e0000SI", bltzal_2 = "04100000SB", bal_1 = "04110000B", bgezal_2 = "04110000SB", bltzall_2 = "04120000SB", bgezall_2 = "04130000SB", synci_1 = "041f0000O", -- Opcode SPECIAL2. madd_2 = "70000000ST", maddu_2 = "70000001ST", mul_3 = "70000002DST", msub_2 = "70000004ST", msubu_2 = "70000005ST", clz_2 = "70000020DS=", clo_2 = "70000021DS=", sdbbp_0 = "7000003f", sdbbp_1 = "7000003fY", -- Opcode SPECIAL3. ext_4 = "7c000000TSAM", -- Note: last arg is msbd = size-1 ins_4 = "7c000004TSAM", -- Note: last arg is msb = pos+size-1 wsbh_2 = "7c0000a0DT", seb_2 = "7c000420DT", seh_2 = "7c000620DT", rdhwr_2 = "7c00003bTD", -- Opcode COP0. mfc0_2 = "40000000TD", mfc0_3 = "40000000TDW", mtc0_2 = "40800000TD", mtc0_3 = "40800000TDW", rdpgpr_2 = "41400000DT", di_0 = "41606000", di_1 = "41606000T", ei_0 = "41606020", ei_1 = "41606020T", wrpgpr_2 = "41c00000DT", tlbr_0 = "42000001", tlbwi_0 = "42000002", tlbwr_0 = "42000006", tlbp_0 = "42000008", eret_0 = "42000018", deret_0 = "4200001f", wait_0 = "42000020", -- Opcode COP1. mfc1_2 = "44000000TG", cfc1_2 = "44400000TG", mfhc1_2 = "44600000TG", mtc1_2 = "44800000TG", ctc1_2 = "44c00000TG", mthc1_2 = "44e00000TG", bc1f_1 = "45000000B", bc1f_2 = "45000000CB", bc1t_1 = "45010000B", bc1t_2 = "45010000CB", bc1fl_1 = "45020000B", bc1fl_2 = "45020000CB", bc1tl_1 = "45030000B", bc1tl_2 = "45030000CB", ["add.s_3"] = "46000000FGH", ["sub.s_3"] = "46000001FGH", ["mul.s_3"] = "46000002FGH", ["div.s_3"] = "46000003FGH", ["sqrt.s_2"] = "46000004FG", ["abs.s_2"] = "46000005FG", ["mov.s_2"] = "46000006FG", ["neg.s_2"] = "46000007FG", ["round.l.s_2"] = "46000008FG", ["trunc.l.s_2"] = "46000009FG", ["ceil.l.s_2"] = "4600000aFG", ["floor.l.s_2"] = "4600000bFG", ["round.w.s_2"] = "4600000cFG", ["trunc.w.s_2"] = "4600000dFG", ["ceil.w.s_2"] = "4600000eFG", ["floor.w.s_2"] = "4600000fFG", ["movf.s_2"] = "46000011FG", ["movf.s_3"] = "46000011FGC", ["movt.s_2"] = "46010011FG", ["movt.s_3"] = "46010011FGC", ["movz.s_3"] = "46000012FGT", ["movn.s_3"] = "46000013FGT", ["recip.s_2"] = "46000015FG", ["rsqrt.s_2"] = "46000016FG", ["cvt.d.s_2"] = "46000021FG", ["cvt.w.s_2"] = "46000024FG", ["cvt.l.s_2"] = "46000025FG", ["cvt.ps.s_3"] = "46000026FGH", ["c.f.s_2"] = "46000030GH", ["c.f.s_3"] = "46000030VGH", ["c.un.s_2"] = "46000031GH", ["c.un.s_3"] = "46000031VGH", ["c.eq.s_2"] = "46000032GH", ["c.eq.s_3"] = "46000032VGH", ["c.ueq.s_2"] = "46000033GH", ["c.ueq.s_3"] = "46000033VGH", ["c.olt.s_2"] = "46000034GH", ["c.olt.s_3"] = "46000034VGH", ["c.ult.s_2"] = "46000035GH", ["c.ult.s_3"] = "46000035VGH", ["c.ole.s_2"] = "46000036GH", ["c.ole.s_3"] = "46000036VGH", ["c.ule.s_2"] = "46000037GH", ["c.ule.s_3"] = "46000037VGH", ["c.sf.s_2"] = "46000038GH", ["c.sf.s_3"] = "46000038VGH", ["c.ngle.s_2"] = "46000039GH", ["c.ngle.s_3"] = "46000039VGH", ["c.seq.s_2"] = "4600003aGH", ["c.seq.s_3"] = "4600003aVGH", ["c.ngl.s_2"] = "4600003bGH", ["c.ngl.s_3"] = "4600003bVGH", ["c.lt.s_2"] = "4600003cGH", ["c.lt.s_3"] = "4600003cVGH", ["c.nge.s_2"] = "4600003dGH", ["c.nge.s_3"] = "4600003dVGH", ["c.le.s_2"] = "4600003eGH", ["c.le.s_3"] = "4600003eVGH", ["c.ngt.s_2"] = "4600003fGH", ["c.ngt.s_3"] = "4600003fVGH", ["add.d_3"] = "46200000FGH", ["sub.d_3"] = "46200001FGH", ["mul.d_3"] = "46200002FGH", ["div.d_3"] = "46200003FGH", ["sqrt.d_2"] = "46200004FG", ["abs.d_2"] = "46200005FG", ["mov.d_2"] = "46200006FG", ["neg.d_2"] = "46200007FG", ["round.l.d_2"] = "46200008FG", ["trunc.l.d_2"] = "46200009FG", ["ceil.l.d_2"] = "4620000aFG", ["floor.l.d_2"] = "4620000bFG", ["round.w.d_2"] = "4620000cFG", ["trunc.w.d_2"] = "4620000dFG", ["ceil.w.d_2"] = "4620000eFG", ["floor.w.d_2"] = "4620000fFG", ["movf.d_2"] = "46200011FG", ["movf.d_3"] = "46200011FGC", ["movt.d_2"] = "46210011FG", ["movt.d_3"] = "46210011FGC", ["movz.d_3"] = "46200012FGT", ["movn.d_3"] = "46200013FGT", ["recip.d_2"] = "46200015FG", ["rsqrt.d_2"] = "46200016FG", ["cvt.s.d_2"] = "46200020FG", ["cvt.w.d_2"] = "46200024FG", ["cvt.l.d_2"] = "46200025FG", ["c.f.d_2"] = "46200030GH", ["c.f.d_3"] = "46200030VGH", ["c.un.d_2"] = "46200031GH", ["c.un.d_3"] = "46200031VGH", ["c.eq.d_2"] = "46200032GH", ["c.eq.d_3"] = "46200032VGH", ["c.ueq.d_2"] = "46200033GH", ["c.ueq.d_3"] = "46200033VGH", ["c.olt.d_2"] = "46200034GH", ["c.olt.d_3"] = "46200034VGH", ["c.ult.d_2"] = "46200035GH", ["c.ult.d_3"] = "46200035VGH", ["c.ole.d_2"] = "46200036GH", ["c.ole.d_3"] = "46200036VGH", ["c.ule.d_2"] = "46200037GH", ["c.ule.d_3"] = "46200037VGH", ["c.sf.d_2"] = "46200038GH", ["c.sf.d_3"] = "46200038VGH", ["c.ngle.d_2"] = "46200039GH", ["c.ngle.d_3"] = "46200039VGH", ["c.seq.d_2"] = "4620003aGH", ["c.seq.d_3"] = "4620003aVGH", ["c.ngl.d_2"] = "4620003bGH", ["c.ngl.d_3"] = "4620003bVGH", ["c.lt.d_2"] = "4620003cGH", ["c.lt.d_3"] = "4620003cVGH", ["c.nge.d_2"] = "4620003dGH", ["c.nge.d_3"] = "4620003dVGH", ["c.le.d_2"] = "4620003eGH", ["c.le.d_3"] = "4620003eVGH", ["c.ngt.d_2"] = "4620003fGH", ["c.ngt.d_3"] = "4620003fVGH", ["add.ps_3"] = "46c00000FGH", ["sub.ps_3"] = "46c00001FGH", ["mul.ps_3"] = "46c00002FGH", ["abs.ps_2"] = "46c00005FG", ["mov.ps_2"] = "46c00006FG", ["neg.ps_2"] = "46c00007FG", ["movf.ps_2"] = "46c00011FG", ["movf.ps_3"] = "46c00011FGC", ["movt.ps_2"] = "46c10011FG", ["movt.ps_3"] = "46c10011FGC", ["movz.ps_3"] = "46c00012FGT", ["movn.ps_3"] = "46c00013FGT", ["cvt.s.pu_2"] = "46c00020FG", ["cvt.s.pl_2"] = "46c00028FG", ["pll.ps_3"] = "46c0002cFGH", ["plu.ps_3"] = "46c0002dFGH", ["pul.ps_3"] = "46c0002eFGH", ["puu.ps_3"] = "46c0002fFGH", ["c.f.ps_2"] = "46c00030GH", ["c.f.ps_3"] = "46c00030VGH", ["c.un.ps_2"] = "46c00031GH", ["c.un.ps_3"] = "46c00031VGH", ["c.eq.ps_2"] = "46c00032GH", ["c.eq.ps_3"] = "46c00032VGH", ["c.ueq.ps_2"] = "46c00033GH", ["c.ueq.ps_3"] = "46c00033VGH", ["c.olt.ps_2"] = "46c00034GH", ["c.olt.ps_3"] = "46c00034VGH", ["c.ult.ps_2"] = "46c00035GH", ["c.ult.ps_3"] = "46c00035VGH", ["c.ole.ps_2"] = "46c00036GH", ["c.ole.ps_3"] = "46c00036VGH", ["c.ule.ps_2"] = "46c00037GH", ["c.ule.ps_3"] = "46c00037VGH", ["c.sf.ps_2"] = "46c00038GH", ["c.sf.ps_3"] = "46c00038VGH", ["c.ngle.ps_2"] = "46c00039GH", ["c.ngle.ps_3"] = "46c00039VGH", ["c.seq.ps_2"] = "46c0003aGH", ["c.seq.ps_3"] = "46c0003aVGH", ["c.ngl.ps_2"] = "46c0003bGH", ["c.ngl.ps_3"] = "46c0003bVGH", ["c.lt.ps_2"] = "46c0003cGH", ["c.lt.ps_3"] = "46c0003cVGH", ["c.nge.ps_2"] = "46c0003dGH", ["c.nge.ps_3"] = "46c0003dVGH", ["c.le.ps_2"] = "46c0003eGH", ["c.le.ps_3"] = "46c0003eVGH", ["c.ngt.ps_2"] = "46c0003fGH", ["c.ngt.ps_3"] = "46c0003fVGH", ["cvt.s.w_2"] = "46800020FG", ["cvt.d.w_2"] = "46800021FG", ["cvt.s.l_2"] = "46a00020FG", ["cvt.d.l_2"] = "46a00021FG", -- Opcode COP1X. lwxc1_2 = "4c000000FX", ldxc1_2 = "4c000001FX", luxc1_2 = "4c000005FX", swxc1_2 = "4c000008FX", sdxc1_2 = "4c000009FX", suxc1_2 = "4c00000dFX", prefx_2 = "4c00000fMX", ["alnv.ps_4"] = "4c00001eFGHS", ["madd.s_4"] = "4c000020FRGH", ["madd.d_4"] = "4c000021FRGH", ["madd.ps_4"] = "4c000026FRGH", ["msub.s_4"] = "4c000028FRGH", ["msub.d_4"] = "4c000029FRGH", ["msub.ps_4"] = "4c00002eFRGH", ["nmadd.s_4"] = "4c000030FRGH", ["nmadd.d_4"] = "4c000031FRGH", ["nmadd.ps_4"] = "4c000036FRGH", ["nmsub.s_4"] = "4c000038FRGH", ["nmsub.d_4"] = "4c000039FRGH", ["nmsub.ps_4"] = "4c00003eFRGH", } ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_fpr(expr) local r = match(expr, "^f([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r end end werror("bad register name `"..expr.."'") end local function parse_imm(imm, bits, shift, scale, signed) local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") elseif match(imm, "^[rf]([1-3]?[0-9])$") or match(imm, "^([%w_]+):([rf][1-3]?[0-9])$") then werror("expected immediate operand, got register") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_disp(disp) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = shl(parse_gpr(reg), 21) local extname = match(imm, "^extern%s+(%S+)$") if extname then waction("REL_EXT", map_extern[extname], nil, 1) return r else return r + parse_imm(imm, 16, 0, 0, true) end end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if tp then waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr)) return shl(r, 21) end end werror("bad displacement `"..disp.."'") end local function parse_index(idx) local rt, rs = match(idx, "^(.*)%(([%w_:]+)%)$") if rt then rt = parse_gpr(rt) rs = parse_gpr(rs) return shl(rt, 16) + shl(rs, 21) end werror("bad index `"..idx.."'") end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return sub(template, 9) end local op = tonumber(sub(template, 1, 8), 16) local n = 1 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 2 positions (ins/ext). if secpos+2 > maxsecpos then wflush() end local pos = wpos() -- Process each character. for p in gmatch(sub(template, 9), ".") do if p == "D" then op = op + shl(parse_gpr(params[n]), 11); n = n + 1 elseif p == "T" then op = op + shl(parse_gpr(params[n]), 16); n = n + 1 elseif p == "S" then op = op + shl(parse_gpr(params[n]), 21); n = n + 1 elseif p == "F" then op = op + shl(parse_fpr(params[n]), 6); n = n + 1 elseif p == "G" then op = op + shl(parse_fpr(params[n]), 11); n = n + 1 elseif p == "H" then op = op + shl(parse_fpr(params[n]), 16); n = n + 1 elseif p == "R" then op = op + shl(parse_fpr(params[n]), 21); n = n + 1 elseif p == "I" then op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1 elseif p == "U" then op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1 elseif p == "O" then op = op + parse_disp(params[n]); n = n + 1 elseif p == "X" then op = op + parse_index(params[n]); n = n + 1 elseif p == "B" or p == "J" then local mode, n, s = parse_label(params[n], false) if p == "B" then n = n + 2048 end waction("REL_"..mode, n, s, 1) n = n + 1 elseif p == "A" then op = op + parse_imm(params[n], 5, 6, 0, false); n = n + 1 elseif p == "M" then op = op + parse_imm(params[n], 5, 11, 0, false); n = n + 1 elseif p == "N" then op = op + parse_imm(params[n], 5, 16, 0, false); n = n + 1 elseif p == "C" then op = op + parse_imm(params[n], 3, 18, 0, false); n = n + 1 elseif p == "V" then op = op + parse_imm(params[n], 3, 8, 0, false); n = n + 1 elseif p == "W" then op = op + parse_imm(params[n], 3, 0, 0, false); n = n + 1 elseif p == "Y" then op = op + parse_imm(params[n], 20, 6, 0, false); n = n + 1 elseif p == "Z" then op = op + parse_imm(params[n], 10, 6, 0, false); n = n + 1 elseif p == "=" then op = op + shl(band(op, 0xf800), 5) -- Copy D to T for clz, clo. else assert(false) end end wputpos(pos, op) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
gpl-2.0
liruqi/bigfoot
Interface/AddOns/DBM-PvP/Battlegrounds/Warsong.lua
1
9635
-- Warsong mod v3.0 -- rewrite by Nitram and Tandanu -- -- thanks to LeoLeal, DiabloHu and Са°ЧТВ local mod = DBM:NewMod("z489", "DBM-PvP", 2) local L = mod:GetLocalizedStrings() mod:RemoveOption("HealthFrame") mod:SetRevision(("$Revision: 66 $"):sub(12, -3)) mod:SetZone(DBM_DISABLE_ZONE_DETECTION) local bgzone = false local FlagCarrier = { [1] = nil, [2] = nil } mod:RegisterEvents( "ZONE_CHANGED_NEW_AREA" ) --local startTimer = mod:NewTimer(62, "TimerStart", 2457) local flagTimer = mod:NewTimer(20, "TimerFlag", "Interface\\Icons\\INV_Banner_02") local vulnerableTimer = mod:NewNextTimer(60, 46392) mod:AddBoolOption("ShowFlagCarrier", true, nil, function() if mod.Options.ShowFlagCarrier and bgzone then mod:ShowFlagCarrier() mod:CreateFlagCarrierButton() else mod:HideFlagCarrier() end end) mod:AddBoolOption("ShowFlagCarrierErrorNote", false) do local function WSG_Initialize() if DBM:GetCurrentArea() == 489 then bgzone = true mod:RegisterShortTermEvents( "PLAYER_REGEN_ENABLED", "CHAT_MSG_BG_SYSTEM_ALLIANCE", "CHAT_MSG_BG_SYSTEM_HORDE", "CHAT_MSG_BG_SYSTEM_NEUTRAL", "CHAT_MSG_RAID_BOSS_EMOTE", "UPDATE_BATTLEFIELD_SCORE" ) if mod.Options.ShowFlagCarrier then mod:ShowFlagCarrier() mod:CreateFlagCarrierButton() mod.FlagCarrierFrame1Text:SetText("") mod.FlagCarrierFrame2Text:SetText("") end FlagCarrier[1] = nil FlagCarrier[2] = nil elseif bgzone then bgzone = false mod:UnregisterShortTermEvents() if mod.Options.ShowFlagCarrier then mod:HideFlagCarrier() end end end mod.OnInitialize = WSG_Initialize function mod:ZONE_CHANGED_NEW_AREA() self:Schedule(1, WSG_Initialize) end end function mod:CHAT_MSG_BG_SYSTEM_NEUTRAL(msg) if msg == L.Vulnerable1 or msg == L.Vulnerable2 or msg:find(L.Vulnerable1) or msg:find(L.Vulnerable2) then vulnerableTimer:Start() end end function mod:ShowFlagCarrier() if not self.Options.ShowFlagCarrier then return end if AlwaysUpFrame2DynamicIconButton and AlwaysUpFrame2DynamicIconButton then if not self.FlagCarrierFrame1 then self.FlagCarrierFrame1 = CreateFrame("Frame", nil, AlwaysUpFrame1DynamicIconButton) self.FlagCarrierFrame1:SetHeight(10) self.FlagCarrierFrame1:SetWidth(100) self.FlagCarrierFrame1:SetPoint("LEFT", "AlwaysUpFrame1DynamicIconButton", "RIGHT", 4, 0) self.FlagCarrierFrame1Text = self.FlagCarrierFrame1:CreateFontString(nil, nil, "GameFontNormalSmall") self.FlagCarrierFrame1Text:SetAllPoints(self.FlagCarrierFrame1) self.FlagCarrierFrame1Text:SetJustifyH("LEFT") end if not self.FlagCarrierFrame2 then self.FlagCarrierFrame2 = CreateFrame("Frame", nil, AlwaysUpFrame2DynamicIconButton) self.FlagCarrierFrame2:SetHeight(10) self.FlagCarrierFrame2:SetWidth(100) self.FlagCarrierFrame2:SetPoint("LEFT", "AlwaysUpFrame2DynamicIconButton", "RIGHT", 4, 0) self.FlagCarrierFrame2Text= self.FlagCarrierFrame2:CreateFontString(nil, nil, "GameFontNormalSmall") self.FlagCarrierFrame2Text:SetAllPoints(self.FlagCarrierFrame2) self.FlagCarrierFrame2Text:SetJustifyH("LEFT") end self.FlagCarrierFrame1:Show() self.FlagCarrierFrame2:Show() end end function mod:CreateFlagCarrierButton() if not self.Options.ShowFlagCarrier then return end if AlwaysUpFrame1 and not self.FlagCarrierFrame1Button then self.FlagCarrierFrame1Button = CreateFrame("Button", nil, nil, "SecureActionButtonTemplate") self.FlagCarrierFrame1Button:SetHeight(15) self.FlagCarrierFrame1Button:SetWidth(150) self.FlagCarrierFrame1Button:SetAttribute("type", "macro") self.FlagCarrierFrame1Button:SetPoint("LEFT", "AlwaysUpFrame1", "RIGHT", 28, 4) end if AlwaysUpFrame2 and not self.FlagCarrierFrame2Button then self.FlagCarrierFrame2Button = CreateFrame("Button", nil, nil, "SecureActionButtonTemplate") self.FlagCarrierFrame2Button:SetHeight(15) self.FlagCarrierFrame2Button:SetWidth(150) self.FlagCarrierFrame2Button:SetAttribute("type", "macro") self.FlagCarrierFrame2Button:SetPoint("LEFT", "AlwaysUpFrame2", "RIGHT", 28, 4) end self.FlagCarrierFrame1Button:Show() self.FlagCarrierFrame2Button:Show() end function mod:HideFlagCarrier() if self.FlagCarrierFrame1 and self.FlagCarrierFrame2 then self.FlagCarrierFrame1:Hide() self.FlagCarrierFrame2:Hide() FlagCarrier[1] = nil FlagCarrier[2] = nil end end function mod:CheckFlagCarrier() if not UnitAffectingCombat("player") then if not self.FlagCarrierFrame1Button or not self.FlagCarrierFrame2Button then self:CreateFlagCarrierButton() end if FlagCarrier[1] and self.FlagCarrierFrame1 then self.FlagCarrierFrame1Button:SetAttribute("macrotext", "/targetexact " .. FlagCarrier[1]) end if FlagCarrier[2] and self.FlagCarrierFrame2 then self.FlagCarrierFrame2Button:SetAttribute("macrotext", "/targetexact " .. FlagCarrier[2]) end end end do local lastCarrier function mod:ColorFlagCarrier(carrier) local found = false for i = 1, GetNumBattlefieldScores() do local name, _, _, _, _, faction, _, _, classToken = GetBattlefieldScore(i) if (name and faction and classToken and RAID_CLASS_COLORS[classToken]) then if string.match( name, "-" ) then name = string.match(name, "([^%-]+)%-.+") end if name == carrier then if faction == 0 then self.FlagCarrierFrame2Text:SetTextColor(RAID_CLASS_COLORS[classToken].r, RAID_CLASS_COLORS[classToken].g, RAID_CLASS_COLORS[classToken].b) elseif faction == 1 then self.FlagCarrierFrame1Text:SetTextColor(RAID_CLASS_COLORS[classToken].r, RAID_CLASS_COLORS[classToken].g, RAID_CLASS_COLORS[classToken].b) end found = true end end end if not found then RequestBattlefieldScoreData() lastCarrier = carrier end end function mod:UPDATE_BATTLEFIELD_SCORE() if lastCarrier then self:ColorFlagCarrier(lastCarrier) lastCarrier = nil end end end function mod:PLAYER_REGEN_ENABLED() if bgzone then self:CheckFlagCarrier() end end do local function updateflagcarrier(self, event, arg1) if not self.Options.ShowFlagCarrier then return end if self.FlagCarrierFrame1 and self.FlagCarrierFrame2 then if string.match(arg1, L.ExprFlagPickUp) or (GetLocale() == "ruRU" and string.match(arg1, L.ExprFlagPickUp2)) then local sArg1, sArg2 local mSide, mNick, nickLong if ( GetLocale() == "ruRU" and string.match(arg1, L.ExprFlagPickUp2) ) then sArg2, sArg1 = string.match(arg1, L.ExprFlagPickUp2) else sArg1, sArg2 = string.match(arg1, L.ExprFlagPickUp) end if GetLocale() == "deDE" or GetLocale() == "koKR" or GetLocale() == "ptBR" then mSide = sArg2 mNick = sArg1 else mSide = sArg1 mNick = sArg2 end for i = 1, GetNumBattlefieldScores() do local name = GetBattlefieldScore(i) -- check if the player is really the player we are looking for (include the "-" separator in the check to avoid players with matching prefixes) if name and name:sub(0, mNick:len() + 1) == mNick .. "-" then nickLong = name break end end if not nickLong then nickLong = mNick end if mSide == (L.Alliance or FACTION_ALLIANCE) then FlagCarrier[2] = nickLong self.FlagCarrierFrame2Text:SetText(mNick) self.FlagCarrierFrame2:Show() self:ColorFlagCarrier(mNick) if UnitAffectingCombat("player") then if self.Options.ShowFlagCarrierErrorNote then self:AddMsg(L.InfoErrorText) end else self.FlagCarrierFrame2Button:SetAttribute( "macrotext", "/targetexact " .. nickLong ) end elseif mSide == (L.Horde or FACTION_HORDE) then FlagCarrier[1] = nickLong self.FlagCarrierFrame1Text:SetText(mNick) self.FlagCarrierFrame1:Show() self:ColorFlagCarrier(mNick) if UnitAffectingCombat("player") then if self.Options.ShowFlagCarrierErrorNote then self:AddMsg(L.InfoErrorText) end else self.FlagCarrierFrame1Button:SetAttribute( "macrotext", "/targetexact " .. nickLong ) end end if FlagCarrier[1] and FlagCarrier[2] and not vulnerableTimer:IsStarted() then vulnerableTimer:Start() end elseif string.match(arg1, L.ExprFlagReturn) then local _, mSide if( GetLocale() == "ruRU") then _, _, _, mSide = string.find(arg1, L.ExprFlagReturn) else _, _, mSide = string.find(arg1, L.ExprFlagReturn) end if mSide == (L.Alliance or FACTION_ALLIANCE) then self.FlagCarrierFrame2:Hide() FlagCarrier[2] = nil elseif mSide == (L.Horde or FACTION_HORDE) then self.FlagCarrierFrame1:Hide() FlagCarrier[1] = nil end end end if string.match(arg1, L.ExprFlagCaptured) then flagTimer:Start() vulnerableTimer:Cancel() if self.FlagCarrierFrame1 and self.FlagCarrierFrame2 then self.FlagCarrierFrame1:Hide() self.FlagCarrierFrame2:Hide() FlagCarrier[1] = nil FlagCarrier[2] = nil end end end function mod:CHAT_MSG_BG_SYSTEM_ALLIANCE(...) updateflagcarrier(self, "CHAT_MSG_BG_SYSTEM_ALLIANCE", ...) end function mod:CHAT_MSG_BG_SYSTEM_HORDE(...) updateflagcarrier(self, "CHAT_MSG_BG_SYSTEM_HORDE", ...) end function mod:CHAT_MSG_RAID_BOSS_EMOTE(...) updateflagcarrier(self, "CHAT_MSG_RAID_BOSS_EMOTE", ...) end end
mit
shiprabehera/kong
spec/03-plugins/18-ip-restriction/02-access_spec.lua
2
9260
local helpers = require "spec.helpers" local cjson = require "cjson" describe("Plugin: ip-restriction (access)", function() local plugin_config local client, admin_client setup(function() helpers.run_migrations() local api1 = assert(helpers.dao.apis:insert { name = "api-1", hosts = { "ip-restriction1.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "ip-restriction", api_id = api1.id, config = { blacklist = {"127.0.0.1", "127.0.0.2"} } }) local api2 = assert(helpers.dao.apis:insert { name = "api-2", hosts = { "ip-restriction2.com" }, upstream_url = "http://mockbin.com" }) plugin_config = assert(helpers.dao.plugins:insert { name = "ip-restriction", api_id = api2.id, config = { blacklist = {"127.0.0.2"} } }) local api3 = assert(helpers.dao.apis:insert { name = "api-3", hosts = { "ip-restriction3.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "ip-restriction", api_id = api3.id, config = { whitelist = {"127.0.0.2"} } }) local api4 = assert(helpers.dao.apis:insert { name = "api-4", hosts = { "ip-restriction4.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "ip-restriction", api_id = api4.id, config = { whitelist = {"127.0.0.1"} } }) local api5 = assert(helpers.dao.apis:insert { name = "api-5", hosts = { "ip-restriction5.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "ip-restriction", api_id = api5.id, config = { blacklist = {"127.0.0.0/24"} } }) local api6 = assert(helpers.dao.apis:insert { name = "api-6", hosts = { "ip-restriction6.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "ip-restriction", api_id = api6.id, config = { whitelist = {"127.0.0.4"} } }) local api7 = assert(helpers.dao.apis:insert { name = "api-7", hosts = { "ip-restriction7.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "ip-restriction", api_id = api7.id, config = { blacklist = {"127.0.0.4"} } }) assert(helpers.start_kong { real_ip_header = "X-Forwarded-For", real_ip_recursive = "on", trusted_ips = "0.0.0.0/0, ::/0", }) client = helpers.proxy_client() admin_client = helpers.admin_client() end) teardown(function() if client and admin_client then client:close() admin_client:close() end helpers.stop_kong() end) describe("blacklist", function() it("blocks a request when the IP is blacklisted", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction1.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Your IP address is not allowed" }, json) end) it("allows a request when the IP is not blacklisted", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "ip-restriction2.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("127.0.0.1", json.clientIPAddress) end) it("blocks IP with CIDR", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction5.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Your IP address is not allowed" }, json) end) describe("X-Forwarded-For", function() it("allows without any X-Forwarded-For and allowed IP", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "ip-restriction7.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("127.0.0.1", json.clientIPAddress) end) it("allows with allowed X-Forwarded-For header", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "ip-restriction7.com", ["X-Forwarded-For"] = "127.0.0.3" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("127.0.0.3", json.clientIPAddress) end) it("blocks with not allowed X-Forwarded-For header", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction7.com", ["X-Forwarded-For"] = "127.0.0.4" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Your IP address is not allowed" }, json) end) end) end) describe("whitelist", function() it("blocks a request when the IP is not whitelisted", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction3.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Your IP address is not allowed" }, json) end) it("allows a whitelisted IP", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction4.com" } }) assert.res_status(200, res) end) describe("X-Forwarded-For", function() it("blocks without any X-Forwarded-For and not allowed IP", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction6.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Your IP address is not allowed" }, json) end) it("block with not allowed X-Forwarded-For header", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction6.com", ["X-Forwarded-For"] = "127.0.0.3" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Your IP address is not allowed" }, json) end) it("allows with allowed X-Forwarded-For header", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction6.com", ["X-Forwarded-For"] = "127.0.0.4" } }) assert.res_status(200, res) end) it("allows with allowed complex X-Forwarded-For header", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "ip-restriction6.com", ["X-Forwarded-For"] = "127.0.0.4, 127.0.0.3" } }) assert.res_status(200, res) end) end) end) it("supports config changes without restarting", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "ip-restriction2.com" } }) assert.res_status(200, res) res = assert(admin_client:send { method = "PATCH", path = "/apis/api-2/plugins/" .. plugin_config.id, body = { ["config.blacklist"] = "127.0.0.1,127.0.0.2" }, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(200, res) local cache_key = helpers.dao.plugins:cache_key(plugin_config.name, plugin_config.api_id, plugin_config.consumer_id) helpers.wait_until(function() res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache_key }) res:read_body() return res.status ~= 200 end) local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "ip-restriction2.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Your IP address is not allowed" }, json) end) end)
apache-2.0
br-lemes/stuff
smartlan/socket/url.lua
148
10529
----------------------------------------------------------------------------- -- URI parsing, composition and relative URL resolution -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local base = _G local table = require("table") module("socket.url") ----------------------------------------------------------------------------- -- Module version ----------------------------------------------------------------------------- _VERSION = "URL 1.0.1" ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- function 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 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 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 stringing 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 parsed.host = 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 build(parsed) local ppath = parse_path(parsed.path or "") local url = 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 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 absolute(base_url, relative_url) if base.type(base_url) == "table" then base_parsed = base_url base_url = build(base_parsed) else base_parsed = parse(base_url) end local relative_parsed = 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 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 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, table.getn(parsed) do parsed[i] = 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 build_path(parsed, unsafe) local path = "" local n = table.getn(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
mit
alijoooon/Psycho
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
mahdib9/3
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
UB12/GAMEOVER
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
aqasaeed/x
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
Steelcap/NSL-CompMod
NSLCompMod/source/lua/DPR/Replace/Door.lua
1
7763
-- ======= Copyright (c) 2003-2014, Unknown Worlds Entertainment, Inc. All rights reserved. ======= -- -- lua\Door.lua -- -- Created by: Charlie Cleveland (charlie@unknownworlds.com) and -- Max McGuire (max@unknownworlds.com) -- -- ========= For more information, visit us at http://www.unknownworlds.com ===================== Script.Load("lua/ScriptActor.lua") Script.Load("lua/Mixins/ModelMixin.lua") Script.Load("lua/PathingMixin.lua") Script.Load("lua/MapBlipMixin.lua") Script.Load("lua/DPR/Predict/PredictAdjustments.lua") class 'Door' (ScriptActor) Door.kMapName = "door" Door.kInoperableSound = PrecacheAsset("sound/NS2.fev/common/door_inoperable") Door.kOpenSound = PrecacheAsset("sound/NS2.fev/common/door_open") Door.kCloseSound = PrecacheAsset("sound/NS2.fev/common/door_close") Door.kLockSound = PrecacheAsset("sound/NS2.fev/common/door_lock") Door.kUnlockSound = PrecacheAsset("sound/NS2.fev/common/door_unlock") Door.kState = enum( {'Open', 'Close', 'Locked', 'DestroyedFront', 'DestroyedBack', 'Welded'} ) Door.kStateSound = { [Door.kState.Open] = Door.kOpenSound, [Door.kState.Close] = Door.kCloseSound, [Door.kState.Locked] = Door.kLockSound, [Door.kState.DestroyedFront] = "", [Door.kState.DestroyedBack] = "", [Door.kState.Welded] = Door.kLockSound, } local kUpdateAutoUnlockRate = 1 local kUpdateAutoOpenRate = 0.3 local kPredictUpdateAutoOpenRate = 0.1 local kWeldPercentagePerSecond = 1 / kDoorWeldTime local kHealthPercentagePerSecond = 0.9 / kDoorWeldTime local kModelNameDefault = PrecacheAsset("models/misc/door/door.model") local kModelNameClean = PrecacheAsset("models/misc/door/door_clean.model") local kModelNameDestroyed = PrecacheAsset("models/misc/door/door_destroyed.model") local kDoorAnimationGraph = PrecacheAsset("models/misc/door/door.animation_graph") local networkVars = { weldedPercentage = "float", -- Stores current state (kState ) state = "enum Door.kState", damageFrontPose = "float (0 to 100 by 0.1)", damageBackPose = "float (0 to 100 by 0.1)" } AddMixinNetworkVars(BaseModelMixin, networkVars) AddMixinNetworkVars(ModelMixin, networkVars) local kDoorLockTimeout = 6 local kDoorLockDuration = 4 local function UpdateAutoUnlock(self, timePassed) -- auto open the door after kDoorLockDuration time has passed local state = self:GetState() if state == Door.kState.Locked and self.timeLastLockTrigger + kDoorLockDuration < Shared.GetTime() then self:SetState(Door.kState.Open) self.lockTimeOut = Shared.GetTime() + kDoorLockTimeout end return true end local function UpdateAutoOpen(self, timePassed) -- If any players are around, have door open if possible, otherwise close it local state = self:GetState() -- reimplement the long forgotten predicted doors from dragon's cmod local player if Client then player = Client.GetLocalPlayer() elseif Predict then player = Predict.GetLocalPlayer() end if state == Door.kState.Open or state == Door.kState.Close then local desiredOpenState = false local entities = Shared.GetEntitiesWithTagInRange("Door", self:GetOrigin(), DoorMixin.kMaxOpenDistance) for index = 1, #entities do local entity = entities[index] local opensForEntity, openDistance = entity:GetCanDoorInteract(self) if opensForEntity then local distSquared = self:GetDistanceSquared(entity) if (not HasMixin(entity, "Live") or entity:GetIsAlive()) and entity:GetIsVisible() and distSquared < (openDistance * openDistance) then desiredOpenState = true break end end end if desiredOpenState and self:GetState() == Door.kState.Close then self:SetState(Door.kState.Open) elseif not desiredOpenState and self:GetState() == Door.kState.Open then self:SetState(Door.kState.Close) end end return true end local function InitModel(self) local modelName = kModelNameDefault if self.clean then modelName = kModelNameClean end self:SetModel(modelName, kDoorAnimationGraph) end function Door:OnCreate() ScriptActor.OnCreate(self) InitMixin(self, BaseModelMixin) InitMixin(self, ModelMixin) InitMixin(self, PathingMixin) if Server then self:AddTimedCallback(UpdateAutoUnlock, kUpdateAutoUnlockRate) self:AddTimedCallback(UpdateAutoOpen, kUpdateAutoOpenRate) end self.state = Door.kState.Open end function Door:OnInitialized() ScriptActor.OnInitialized(self) if Server then InitModel(self) self:SetPhysicsType(PhysicsType.Kinematic) self:SetPhysicsGroup(PhysicsGroup.CommanderUnitGroup) -- This Mixin must be inited inside this OnInitialized() function. if not HasMixin(self, "MapBlip") then InitMixin(self, MapBlipMixin) end end end function Door:Reset() self:SetPhysicsType(PhysicsType.Kinematic) self:SetPhysicsGroup(0) self:SetState(Door.kState.Close) InitModel(self) end function Door:GetShowHealthFor(player) return false end function Door:GetReceivesStructuralDamage() return false end function Door:GetIsWeldedShut() return self:GetState() == Door.kState.Welded end function Door:GetDescription() local doorName = GetDisplayNameForTechId(self:GetTechId()) local doorDescription = doorName local state = self:GetState() if state == Door.kState.Welded then doorDescription = string.format("Welded %s", doorName) end return doorDescription end function Door:SetState(state, commander) if self.state ~= state then self.state = state if Server then local sound = Door.kStateSound[self.state] if sound ~= "" then self:PlaySound(sound) if commander ~= nil then Server.PlayPrivateSound(commander, sound, nil, 1.0, commander:GetOrigin()) end end end end end function Door:GetState() return self.state end function Door:GetCanBeUsed(player, useSuccessTable) useSuccessTable.useSuccess = false end function Door:OnUpdateAnimationInput(modelMixin) PROFILE("Door:OnUpdateAnimationInput") local open = self.state == Door.kState.Open if Predict then open = true end -- local lock = self.state == Door.kState.Locked or self.state == Door.kState.Welded modelMixin:SetAnimationInput("open", open) modelMixin:SetAnimationInput("lock", false) end if Client then function Door:OnUpdate(deltaTime) ScriptActor.OnUpdate(self, deltaTime) if not self.lastUpdatedClient or self.lastUpdatedClient + kPredictUpdateAutoOpenRate < Shared.GetTime() then UpdateAutoOpen(self) self.lastUpdatedClient = Shared.GetTime() end end end if Predict then function Door:OnUpdate(deltaTime) ScriptActor.OnUpdate(self, deltaTime) end AddClassToPredictionUpdate("Door", function(ent) return true end) end Shared.LinkClassToMap("Door", Door.kMapName, networkVars)
mit
liruqi/bigfoot
Interface/AddOns/WorldQuestTracker/libs/DF/pictureedit.lua
1
20430
local DF = _G ["DetailsFramework"] if (not DF or not DetailsFrameworkCanLoad) then return end local _ local window = DF:NewPanel (UIParent, nil, "DetailsFrameworkImageEdit", nil, 100, 100, false) window:SetPoint ("center", UIParent, "center") window:SetResizable (true) window:SetMovable (true) tinsert (UISpecialFrames, "DetailsFrameworkImageEdit") window:SetFrameStrata ("TOOLTIP") window:SetMaxResize (650, 500) window.hooks = {} local background = DF:NewImage (window, nil, nil, nil, "background", nil, nil, "$parentBackground") background:SetAllPoints() background:SetTexture (0, 0, 0, .8) local edit_texture = DF:NewImage (window, nil, 650, 500, "artwork", nil, nil, "$parentImage") edit_texture:SetAllPoints() local background_frame = CreateFrame ("frame", "DetailsFrameworkImageEditBackground", DetailsFrameworkImageEdit) background_frame:SetPoint ("topleft", DetailsFrameworkImageEdit, "topleft", -10, 12) background_frame:SetFrameStrata ("DIALOG") background_frame:SetSize (800, 540) background_frame:SetResizable (true) background_frame:SetMovable (true) background_frame:SetScript ("OnMouseDown", function() window:StartMoving() end) background_frame:SetScript ("OnMouseUp", function() window:StopMovingOrSizing() end) background_frame:SetBackdrop ({edgeFile = [[Interface\Buttons\WHITE8X8]], edgeSize = 1, bgFile = [[Interface\Tooltips\UI-Tooltip-Background]], tileSize = 64, tile = true}) background_frame:SetBackdropColor (0, 0, 0, 0.9) background_frame:SetBackdropBorderColor (0, 0, 0, 1) local haveHFlip = false local haveVFlip = false --> Top Slider local topCoordTexture = DF:NewImage (window, nil, nil, nil, "overlay", nil, nil, "$parentImageTopCoord") topCoordTexture:SetPoint ("topleft", window, "topleft") topCoordTexture:SetPoint ("topright", window, "topright") topCoordTexture:SetColorTexture (1, 0, 0) topCoordTexture.height = 1 topCoordTexture.alpha = .2 local topSlider = DF:NewSlider (window, nil, "$parentTopSlider", "topSlider", 100, 100, 0.1, 100, 0.1, 0) topSlider:SetAllPoints (window.widget) topSlider:SetOrientation ("VERTICAL") topSlider.backdrop = nil topSlider.fractional = true topSlider:SetHook ("OnEnter", function() return true end) topSlider:SetHook ("OnLeave", function() return true end) local topSliderThumpTexture = topSlider:CreateTexture (nil, "overlay") topSliderThumpTexture:SetColorTexture (1, 1, 1) topSliderThumpTexture:SetWidth (512) topSliderThumpTexture:SetHeight (1) topSlider:SetThumbTexture (topSliderThumpTexture) topSlider:SetHook ("OnValueChange", function (_, _, value) topCoordTexture.image:SetHeight (window.frame:GetHeight()/100*value) if (window.callback_func) then window.accept (nil, nil, true) end end) topSlider:Hide() --> Bottom Slider local bottomCoordTexture = DF:NewImage (window, nil, nil, nil, "overlay", nil, nil, "$parentImageBottomCoord") bottomCoordTexture:SetPoint ("bottomleft", window, "bottomleft", 0, 0) bottomCoordTexture:SetPoint ("bottomright", window, "bottomright", 0, 0) bottomCoordTexture:SetColorTexture (1, 0, 0) bottomCoordTexture.height = 1 bottomCoordTexture.alpha = .2 local bottomSlider= DF:NewSlider (window, nil, "$parentBottomSlider", "bottomSlider", 100, 100, 0.1, 100, 0.1, 100) bottomSlider:SetAllPoints (window.widget) bottomSlider:SetOrientation ("VERTICAL") bottomSlider.backdrop = nil bottomSlider.fractional = true bottomSlider:SetHook ("OnEnter", function() return true end) bottomSlider:SetHook ("OnLeave", function() return true end) local bottomSliderThumpTexture = bottomSlider:CreateTexture (nil, "overlay") bottomSliderThumpTexture:SetColorTexture (1, 1, 1) bottomSliderThumpTexture:SetWidth (512) bottomSliderThumpTexture:SetHeight (1) bottomSlider:SetThumbTexture (bottomSliderThumpTexture) bottomSlider:SetHook ("OnValueChange", function (_, _, value) value = math.abs (value-100) bottomCoordTexture.image:SetHeight (math.max (window.frame:GetHeight()/100*value, 1)) if (window.callback_func) then window.accept (nil, nil, true) end end) bottomSlider:Hide() --> Left Slider local leftCoordTexture = DF:NewImage (window, nil, nil, nil, "overlay", nil, nil, "$parentImageLeftCoord") leftCoordTexture:SetPoint ("topleft", window, "topleft", 0, 0) leftCoordTexture:SetPoint ("bottomleft", window, "bottomleft", 0, 0) leftCoordTexture:SetColorTexture (1, 0, 0) leftCoordTexture.width = 1 leftCoordTexture.alpha = .2 local leftSlider = DF:NewSlider (window, nil, "$parentLeftSlider", "leftSlider", 100, 100, 0.1, 100, 0.1, 0.1) leftSlider:SetAllPoints (window.widget) leftSlider.backdrop = nil leftSlider.fractional = true leftSlider:SetHook ("OnEnter", function() return true end) leftSlider:SetHook ("OnLeave", function() return true end) local leftSliderThumpTexture = leftSlider:CreateTexture (nil, "overlay") leftSliderThumpTexture:SetColorTexture (1, 1, 1) leftSliderThumpTexture:SetWidth (1) leftSliderThumpTexture:SetHeight (512) leftSlider:SetThumbTexture (leftSliderThumpTexture) leftSlider:SetHook ("OnValueChange", function (_, _, value) leftCoordTexture.image:SetWidth (window.frame:GetWidth()/100*value) if (window.callback_func) then window.accept (nil, nil, true) end end) leftSlider:Hide() --> Right Slider local rightCoordTexture = DF:NewImage (window, nil, nil, nil, "overlay", nil, nil, "$parentImageRightCoord") rightCoordTexture:SetPoint ("topright", window, "topright", 0, 0) rightCoordTexture:SetPoint ("bottomright", window, "bottomright", 0, 0) rightCoordTexture:SetColorTexture (1, 0, 0) rightCoordTexture.width = 1 rightCoordTexture.alpha = .2 local rightSlider = DF:NewSlider (window, nil, "$parentRightSlider", "rightSlider", 100, 100, 0.1, 100, 0.1, 100) rightSlider:SetAllPoints (window.widget) rightSlider.backdrop = nil rightSlider.fractional = true rightSlider:SetHook ("OnEnter", function() return true end) rightSlider:SetHook ("OnLeave", function() return true end) --[ local rightSliderThumpTexture = rightSlider:CreateTexture (nil, "overlay") rightSliderThumpTexture:SetColorTexture (1, 1, 1) rightSliderThumpTexture:SetWidth (1) rightSliderThumpTexture:SetHeight (512) rightSlider:SetThumbTexture (rightSliderThumpTexture) --]] rightSlider:SetHook ("OnValueChange", function (_, _, value) value = math.abs (value-100) rightCoordTexture.image:SetWidth (math.max (window.frame:GetWidth()/100*value, 1)) if (window.callback_func) then window.accept (nil, nil, true) end end) rightSlider:Hide() --> Edit Buttons local buttonsBackground = DF:NewPanel (UIParent, nil, "DetailsFrameworkImageEditButtonsBg", nil, 115, 230) --buttonsBackground:SetPoint ("topleft", window, "topright", 2, 0) buttonsBackground:SetPoint ("topright", background_frame, "topright", -8, -10) buttonsBackground:Hide() --buttonsBackground:SetMovable (true) tinsert (UISpecialFrames, "DetailsFrameworkImageEditButtonsBg") buttonsBackground:SetFrameStrata ("TOOLTIP") local alphaFrameShown = false local editingSide = nil local lastButton = nil local alphaFrame local originalColor = {0.9999, 0.8196, 0} local enableTexEdit = function (button, b, side) if (alphaFrameShown) then alphaFrame:Hide() alphaFrameShown = false button.text:SetTextColor (unpack (originalColor)) end if (ColorPickerFrame:IsShown()) then ColorPickerFrame:Hide() end if (lastButton) then lastButton.text:SetTextColor (unpack (originalColor)) end if (editingSide == side) then window [editingSide.."Slider"]:Hide() editingSide = nil return elseif (editingSide) then window [editingSide.."Slider"]:Hide() end editingSide = side button.text:SetTextColor (1, 1, 1) lastButton = button window [side.."Slider"]:Show() end local leftTexCoordButton = DF:NewButton (buttonsBackground, nil, "$parentLeftTexButton", nil, 100, 20, enableTexEdit, "left", nil, nil, "Crop Left", 1) leftTexCoordButton:SetPoint ("topright", buttonsBackground, "topright", -8, -10) local rightTexCoordButton = DF:NewButton (buttonsBackground, nil, "$parentRightTexButton", nil, 100, 20, enableTexEdit, "right", nil, nil, "Crop Right", 1) rightTexCoordButton:SetPoint ("topright", buttonsBackground, "topright", -8, -30) local topTexCoordButton = DF:NewButton (buttonsBackground, nil, "$parentTopTexButton", nil, 100, 20, enableTexEdit, "top", nil, nil, "Crop Top", 1) topTexCoordButton:SetPoint ("topright", buttonsBackground, "topright", -8, -50) local bottomTexCoordButton = DF:NewButton (buttonsBackground, nil, "$parentBottomTexButton", nil, 100, 20, enableTexEdit, "bottom", nil, nil, "Crop Bottom", 1) bottomTexCoordButton:SetPoint ("topright", buttonsBackground, "topright", -8, -70) leftTexCoordButton:InstallCustomTexture() rightTexCoordButton:InstallCustomTexture() topTexCoordButton:InstallCustomTexture() bottomTexCoordButton:InstallCustomTexture() local Alpha = DF:NewButton (buttonsBackground, nil, "$parentBottomAlphaButton", nil, 100, 20, alpha, nil, nil, nil, "Alpha", 1) Alpha:SetPoint ("topright", buttonsBackground, "topright", -8, -115) Alpha:InstallCustomTexture() --> overlay color local selectedColor = function (default) if (default) then edit_texture:SetVertexColor (unpack (default)) if (window.callback_func) then window.accept (nil, nil, true) end else edit_texture:SetVertexColor (ColorPickerFrame:GetColorRGB()) if (window.callback_func) then window.accept (nil, nil, true) end end end local changeColor = function() ColorPickerFrame.func = nil ColorPickerFrame.opacityFunc = nil ColorPickerFrame.cancelFunc = nil ColorPickerFrame.previousValues = nil local r, g, b = edit_texture:GetVertexColor() ColorPickerFrame:SetColorRGB (r, g, b) ColorPickerFrame:SetParent (buttonsBackground.widget) ColorPickerFrame.hasOpacity = false ColorPickerFrame.previousValues = {r, g, b} ColorPickerFrame.func = selectedColor ColorPickerFrame.cancelFunc = selectedColor ColorPickerFrame:ClearAllPoints() ColorPickerFrame:SetPoint ("left", buttonsBackground.widget, "right") ColorPickerFrame:Show() if (alphaFrameShown) then alphaFrame:Hide() alphaFrameShown = false Alpha.button.text:SetTextColor (unpack (originalColor)) end if (lastButton) then lastButton.text:SetTextColor (unpack (originalColor)) if (editingSide) then window [editingSide.."Slider"]:Hide() end end end local changeColorButton = DF:NewButton (buttonsBackground, nil, "$parentOverlayColorButton", nil, 100, 20, changeColor, nil, nil, nil, "Color", 1) changeColorButton:SetPoint ("topright", buttonsBackground, "topright", -8, -95) changeColorButton:InstallCustomTexture() alphaFrame = DF:NewPanel (buttonsBackground, nil, "DetailsFrameworkImageEditAlphaBg", nil, 40, 225) alphaFrame:SetPoint ("topleft", buttonsBackground, "topright", 2, 0) alphaFrame:Hide() local alphaSlider = DF:NewSlider (alphaFrame, nil, "$parentAlphaSlider", "alphaSlider", 30, 220, 1, 100, 1, edit_texture:GetAlpha()*100) alphaSlider:SetPoint ("top", alphaFrame, "top", 0, -5) alphaSlider:SetOrientation ("VERTICAL") alphaSlider.thumb:SetSize (40, 30) --leftSlider.backdrop = nil --leftSlider.fractional = true local alpha = function (button) if (ColorPickerFrame:IsShown()) then ColorPickerFrame:Hide() end if (lastButton) then lastButton.text:SetTextColor (unpack (originalColor)) if (editingSide) then window [editingSide.."Slider"]:Hide() end end if (not alphaFrameShown) then alphaFrame:Show() alphaSlider:SetValue (edit_texture:GetAlpha()*100) alphaFrameShown = true button.text:SetTextColor (1, 1, 1) else alphaFrame:Hide() alphaFrameShown = false button.text:SetTextColor (unpack (originalColor)) end end Alpha.clickfunction = alpha alphaSlider:SetHook ("OnValueChange", function (_, _, value) edit_texture:SetAlpha (value/100) if (window.callback_func) then window.accept (nil, nil, true) end end) local resizer = CreateFrame ("Button", nil, window.widget) resizer:SetNormalTexture ([[Interface\AddOns\WorldQuestTracker\images\default_skin]]) resizer:SetHighlightTexture ([[Interface\AddOns\WorldQuestTracker\images\default_skin]]) resizer:GetNormalTexture():SetTexCoord (0.00146484375, 0.01513671875, 0.24560546875, 0.25927734375) resizer:GetHighlightTexture():SetTexCoord (0.00146484375, 0.01513671875, 0.24560546875, 0.25927734375) resizer:SetWidth (16) resizer:SetHeight (16) resizer:SetPoint ("BOTTOMRIGHT", window.widget, "BOTTOMRIGHT", 0, 0) resizer:EnableMouse (true) resizer:SetFrameLevel (window.widget:GetFrameLevel() + 2) resizer:SetScript ("OnMouseDown", function (self, button) window.widget:StartSizing ("BOTTOMRIGHT") end) resizer:SetScript ("OnMouseUp", function (self, button) window.widget:StopMovingOrSizing() end) window.widget:SetScript ("OnMouseDown", function() window.widget:StartMoving() end) window.widget:SetScript ("OnMouseUp", function() window.widget:StopMovingOrSizing() end) window.widget:SetScript ("OnSizeChanged", function() edit_texture.width = window.width edit_texture.height = window.height leftSliderThumpTexture:SetHeight (window.height) rightSliderThumpTexture:SetHeight (window.height) topSliderThumpTexture:SetWidth (window.width) bottomSliderThumpTexture:SetWidth (window.width) rightCoordTexture.image:SetWidth (math.max ( (window.frame:GetWidth() / 100 * math.abs (rightSlider:GetValue()-100)), 1)) leftCoordTexture.image:SetWidth (window.frame:GetWidth()/100*leftSlider:GetValue()) bottomCoordTexture:SetHeight (math.max ( (window.frame:GetHeight() / 100 * math.abs (bottomSlider:GetValue()-100)), 1)) topCoordTexture:SetHeight (window.frame:GetHeight()/100*topSlider:GetValue()) if (window.callback_func) then window.accept (nil, nil, true) end end) --> flip local flip = function (button, b, side) if (side == 1) then haveHFlip = not haveHFlip if (window.callback_func) then window.accept (nil, nil, true) end elseif (side == 2) then haveVFlip = not haveVFlip if (window.callback_func) then window.accept (nil, nil, true) end end end local flipButtonH = DF:NewButton (buttonsBackground, nil, "$parentFlipButton", nil, 100, 20, flip, 1, nil, nil, "Flip H", 1) flipButtonH:SetPoint ("topright", buttonsBackground, "topright", -8, -140) flipButtonH:InstallCustomTexture() -- --> select area to crop local DragFrame = CreateFrame ("frame", nil, background_frame) DragFrame:EnableMouse (false) DragFrame:SetFrameStrata ("TOOLTIP") DragFrame:SetPoint ("topleft", edit_texture.widget, "topleft") DragFrame:SetPoint ("bottomright", edit_texture.widget, "bottomright") DragFrame:SetBackdrop ({edgeFile = [[Interface\Buttons\WHITE8X8]], edgeSize = 1, bgFile = [[Interface\Worldmap\UI-QuestBlob-Inside]], tileSize = 256, tile = true}) DragFrame:SetBackdropColor (1, 1, 1, .2) DragFrame:Hide() local SelectionBox_Up = DragFrame:CreateTexture (nil, "overlay") SelectionBox_Up:SetHeight (1) SelectionBox_Up:SetColorTexture (1, 1, 1) local SelectionBox_Down = DragFrame:CreateTexture (nil, "overlay") SelectionBox_Down:SetHeight (1) SelectionBox_Down:SetColorTexture (1, 1, 1) local SelectionBox_Left = DragFrame:CreateTexture (nil, "overlay") SelectionBox_Left:SetWidth (1) SelectionBox_Left:SetColorTexture (1, 1, 1) local SelectionBox_Right = DragFrame:CreateTexture (nil, "overlay") SelectionBox_Right:SetWidth (1) SelectionBox_Right:SetColorTexture (1, 1, 1) function DragFrame.ClearSelectionBoxPoints() SelectionBox_Up:ClearAllPoints() SelectionBox_Down:ClearAllPoints() SelectionBox_Left:ClearAllPoints() SelectionBox_Right:ClearAllPoints() end local StartCrop = function() DragFrame:Show() DragFrame:EnableMouse (true) end local CropSelection = DF:NewButton (buttonsBackground, nil, "$parentCropSelection", nil, 100, 20, StartCrop, 2, nil, nil, "Crop Selection", 1) --CropSelection:SetPoint ("topright", buttonsBackground, "topright", -8, -260) CropSelection:InstallCustomTexture() DragFrame.OnTick = function (self, deltaTime) local x1, y1 = unpack (self.ClickedAt) local x2, y2 = GetCursorPosition() DragFrame.ClearSelectionBoxPoints() print (x1, y1, x2, y2) if (x2 > x1) then --right if (y1 > y2) then --top SelectionBox_Up:SetPoint ("topleft", UIParent, "bottomleft", x1, y1) SelectionBox_Up:SetPoint ("topright", UIParent, "bottomleft", x2, y1) SelectionBox_Left:SetPoint ("topleft", UIParent, "bottomleft", x1, y1) SelectionBox_Left:SetPoint ("bottomleft", UIParent, "bottomleft", x1, y2) print (1) else --bottom end else --left if (y2 > y1) then --top else --bottom end end end DragFrame:SetScript ("OnMouseDown", function (self, MouseButton) if (MouseButton == "LeftButton") then self.ClickedAt = {GetCursorPosition()} DragFrame:SetScript ("OnUpdate", DragFrame.OnTick) end end) DragFrame:SetScript ("OnMouseUp", function (self, MouseButton) if (MouseButton == "LeftButton") then self.ReleaseAt = {GetCursorPosition()} DragFrame:EnableMouse (false) DragFrame:Hide() DragFrame:SetScript ("OnUpdate", nil) print (self.ClickedAt[1], self.ClickedAt[2], self.ReleaseAt[1], self.ReleaseAt[2]) end end) --> accept window.accept = function (self, b, keep_editing) if (not keep_editing) then buttonsBackground:Hide() window:Hide() alphaFrame:Hide() ColorPickerFrame:Hide() end local coords = {} local l, r, t, b = leftSlider.value/100, rightSlider.value/100, topSlider.value/100, bottomSlider.value/100 if (haveHFlip) then coords [1] = r coords [2] = l else coords [1] = l coords [2] = r end if (haveVFlip) then coords [3] = b coords [4] = t else coords [3] = t coords [4] = b end return window.callback_func (edit_texture.width, edit_texture.height, {edit_texture:GetVertexColor()}, edit_texture:GetAlpha(), coords, window.extra_param) end local acceptButton = DF:NewButton (buttonsBackground, nil, "$parentAcceptButton", nil, 100, 20, window.accept, nil, nil, nil, "Done", 1) acceptButton:SetPoint ("topright", buttonsBackground, "topright", -8, -200) acceptButton:InstallCustomTexture() window:Hide() ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local ttexcoord function DF:ImageEditor (callback, texture, texcoord, colors, width, height, extraParam, alpha, maximize) texcoord = texcoord or {0, 1, 0, 1} ttexcoord = texcoord colors = colors or {1, 1, 1, 1} alpha = alpha or 1 edit_texture:SetTexture (texture) edit_texture.width = width edit_texture.height = height edit_texture.maximize = maximize edit_texture:SetVertexColor (colors [1], colors [2], colors [3]) edit_texture:SetAlpha (alpha) DF:ScheduleTimer ("RefreshImageEditor", 0.2) window:Show() window.callback_func = callback window.extra_param = extraParam buttonsBackground:Show() buttonsBackground.widget:SetBackdrop (nil) table.wipe (window.hooks) end function DF:RefreshImageEditor() if (edit_texture.maximize) then DetailsFrameworkImageEdit:SetSize (266, 226) else DetailsFrameworkImageEdit:SetSize (edit_texture.width, edit_texture.height) end local l, r, t, b = unpack (ttexcoord) if (l > r) then haveHFlip = true leftSlider:SetValue (r * 100) rightSlider:SetValue (l * 100) else haveHFlip = false leftSlider:SetValue (l * 100) rightSlider:SetValue (r * 100) end if (t > b) then haveVFlip = true topSlider:SetValue (b * 100) bottomSlider:SetValue (t * 100) else haveVFlip = false topSlider:SetValue (t * 100) bottomSlider:SetValue (b * 100) end if (window.callback_func) then window.accept (nil, nil, true) end end
mit
SIDN/spin
src/tools/profile-util/util_validate.lua
1
1289
-- -- Copyright (c) 2018 Caspar Schutijser <caspar.schutijser@sidn.nl> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- local util_validate = {} -- Assert that specified string somewhat looks like an IP address function util_validate.somewhat_validate_ip(ip) assert(string.match(ip, "^[%x%.:/]+$"), "does not sufficiently look like an IP address: " .. ip) end -- Asserts that specified string looks like a MAC address function util_validate.validate_mac(mac) assert(string.match(mac, "^%x%x:%x%x:%x%x:%x%x:%x%x:%x%x$"), "invalid MAC address: " .. mac) end return util_validate
gpl-2.0
geanux/darkstar
scripts/zones/Southern_San_dOria/npcs/Helbort.lua
17
2420
----------------------------------- -- Area: Southern San d'Oria -- NPC: Helbort -- Starts and Finished Quest: A purchase of Arms -- @zone 230 -- @pos 71 -1 65 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) quest_fas = player:getQuestStatus(SANDORIA,FATHER_AND_SON); -- 1st Quest in Series quest_poa = player:getQuestStatus(SANDORIA,A_PURCHASE_OF_ARMS); -- 2nd Quest in Series if (player:getFameLevel(SANDORIA) >= 2 and quest_fas == QUEST_COMPLETED and quest_poa == QUEST_AVAILABLE) then player:startEvent(0x0252); -- Start quest A Purchase of Arms elseif (quest_poa == QUEST_ACCEPTED and player:hasKeyItem(WEAPONS_RECEIPT) == true) then player:startEvent(0x025f); -- Finish A Purchase of Arms quest else player:startEvent(0x0251); -- Standard Dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0252 and option == 0) then player:addQuest(SANDORIA, A_PURCHASE_OF_ARMS); player:addKeyItem(WEAPONS_ORDER); player:messageSpecial(KEYITEM_OBTAINED,WEAPONS_ORDER); elseif (csid == 0x025f) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17090); -- Elm Staff else player:addTitle(ARMS_TRADER); player:delKeyItem(WEAPONS_RECEIPT); player:addItem(17090); player:messageSpecial(ITEM_OBTAINED,17090); -- Elm Staff player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA, A_PURCHASE_OF_ARMS); end end end;
gpl-3.0
geanux/darkstar
scripts/globals/mobskills/Bai_Wing.lua
25
1095
--------------------------------------------- -- Bai Wing -- -- Description: A hot wind deals Fire damage to enemies within a very wide area of effect. Additional effect: Plague -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 30' radial. -- Notes: Used only by Ouryu and Cuelebre while flying. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:AnimationSub() ~= 1) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_SLOW; MobStatusEffectMove(mob, target, typeEffect, 300, 0, 120); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_EARTH,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_EARTH,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
kaen/Zero-K
LuaUI/Widgets/chili_new/headers/util.lua
7
10080
--//============================================================================= function IsTweakMode() return widgetHandler.tweakMode end --//============================================================================= --// some needed gl constants GL_DEPTH24_STENCIL8 = 0x88F0 GL_KEEP = 0x1E00 GL_INCR_WRAP = 0x8507 GL_DECR_WRAP = 0x8508 --//============================================================================= function unpack4(t) return t[1], t[2], t[3], t[4] end function clamp(min,max,num) if (num<min) then return min elseif (num>max) then return max end return num end function ExpandRect(rect,margin) return { rect[1] - margin[1], --//left rect[2] - margin[2], --//top rect[3] + margin[1] + margin[3], --//width rect[4] + margin[2] + margin[4], --//height } end function InRect(rect,x,y) return x>=rect[1] and y>=rect[2] and x<=rect[1]+rect[3] and y<=rect[2]+rect[4] end function ProcessRelativeCoord(code, total) local num = tonumber(code) if (type(code) == "string") then local percent = tonumber(code:sub(1,-2)) or 0 if (percent<0) then percent = 0 elseif (percent>100) then percent = 100 end return math.floor(total * percent/100) elseif (num)and((1/num)<0) then return math.floor(total + num) else return math.floor(num or 0) end end function IsRelativeCoord(code) local num = tonumber(code) if (type(code) == "string") then return true elseif (num)and((1/num)<0) then return true else return false end end function IsRelativeCoordType(code) local num = tonumber(code) if (type(code) == "string") then return "relative" elseif (num)and((1/num)<0) then return "negative" else return "default" end end --//============================================================================= function IsObject(v) return ((type(v)=="metatable")or(type(v)=="userdata")) and(v.classname) end function IsNumber(v) return (type(v)=="number") end function isnumber(v) return (type(v)=="number") end function istable(v) return (type(v)=="table") end function isstring(v) return (type(v)=="string") end function isindexable(v) local t = type(v) return (t=="table")or(t=="metatable")or(t=="userdata") end function isfunc(v) return (type(v)=="function") end --//============================================================================= local curScissor = {1,1,1e9,1e9} local stack = {curScissor} local stackN = 1 local pool = {} local function GetVector4() if not pool[1] then return {0,0,0,0} end local t = pool[#pool] pool[#pool] = nil return t end local function FreeVector4(t) pool[#pool + 1] = t end local function PushScissor(_,x,y,w,h) local right = x + w local bottom = y + h if (right > curScissor[3]) then right = curScissor[3] end if (bottom > curScissor[4]) then bottom = curScissor[4] end if (x < curScissor[1]) then x = curScissor[1] end if (y < curScissor[2]) then y = curScissor[2] end w = right - x h = bottom - y if (w < 0) or (h < 0) then --// scissor is null space -> don't render at all return false end --curScissor = {x,y,right,bottom} curScissor = GetVector4() curScissor[1] = x; curScissor[2] = y; curScissor[3] = right; curScissor[4] = bottom; stackN = stackN + 1 stack[stackN] = curScissor gl.Scissor(x,y,w,h) return true end local function PopScissor() FreeVector4(curScissor) stack[stackN] = nil stackN = stackN - 1 curScissor = stack[stackN] assert(stackN >= 1) if (stackN == 1) then gl.Scissor(false) else local x,y, right,bottom = unpack4(curScissor) local w = right - x local h = bottom - y if w >= 0 and h >= 0 then gl.Scissor(x,y,w,h) end end end local function PushStencilMask(obj, x,y,w,h) obj._stencilMask = (obj.parent._stencilMask or 0) + 1 if (obj._stencilMask > 255) then obj._stencilMask = 0 end gl.ColorMask(false) gl.StencilFunc(GL.ALWAYS, 0, 0xFF) gl.StencilOp(GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP) if not obj.scrollPosY then gl.Rect(0, 0, w, h) else local contentX,contentY,contentWidth,contentHeight = unpack4(obj.contentArea) gl.Rect(0, 0, contentWidth,contentHeight) end gl.ColorMask(true) gl.StencilFunc(GL.EQUAL, obj._stencilMask, 0xFF) gl.StencilOp(GL_KEEP, GL_KEEP, GL_KEEP) return true end local function PopStencilMask(obj, x,y,w,h) gl.ColorMask(false) gl.StencilFunc(GL.ALWAYS, 0, 0xFF) gl.StencilOp(GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP) if not obj.scrollPosY then gl.Rect(0, 0, w, h) else local contentX,contentY,contentWidth,contentHeight = unpack4(obj.contentArea) gl.Rect(0, 0, contentWidth,contentHeight) end gl.ColorMask(true) gl.StencilFunc(GL.EQUAL, obj.parent._stencilMask or 0, 0xFF) gl.StencilOp(GL_KEEP, GL_KEEP, GL_KEEP) --gl.StencilTest(false) obj._stencilMask = nil end local inRTT = false function EnterRTT() inRTT = true end function LeaveRTT() inRTT = false end function AreInRTT() return inRTT end function PushLimitRenderRegion(...) if inRTT then return PushStencilMask(...) else return PushScissor(...) end end function PopLimitRenderRegion(...) if inRTT then PopStencilMask(...) else PopScissor(...) end end --//============================================================================= function AreRectsOverlapping(rect1,rect2) return (rect1[1] <= rect2[1] + rect2[3]) and (rect1[1] + rect1[3] >= rect2[1]) and (rect1[2] <= rect2[2] + rect2[4]) and (rect1[2] + rect1[4] >= rect2[2]) end --//============================================================================= local oldPrint = print function print(...) oldPrint(...) io.flush() end --//============================================================================= function _ParseColorArgs(r,g,b,a) local t = type(r) if (t == "table") then return r else return {r,g,b,a} end end --//============================================================================= function string:findlast(str) local i local j = 0 repeat i = j j = self:find(str,i+1,true) until (not j) return i end function string:GetExt() local i = self:findlast('.') if (i) then return self:sub(i) end end --//============================================================================= local type = type local pairs = pairs function table:clear() for i,_ in pairs(self) do self[i] = nil end end function table:map(fun) local newTable = {} for key, value in pairs(self) do newTable[key] = fun(key, value) end return newTable end function table:shallowcopy() local newTable = {} for k, v in pairs(self) do newTable[k] = v end return newTable end function table:arrayshallowcopy() local newArray = {} for i=1, #self do newArray[i] = self[i] end return newTable end function table:arrayappend(t) for i=1, #t do self[#self+1] = t[i] end end function table:arraymap(fun) for i=1, #self do newTable[i] = fun(self[i]) end end function table:fold(fun, state) for key, value in pairs(self) do fun(state, key, value) end end function table:arrayreduce(fun) local state = self[1] for i=2, #self do state = fun(state , self[i]) end return state end -- removes and returns element from array -- array, T element -> T element function table:arrayremovefirst(element) for i=1, #self do if self[i] == element then return self:remove(i) end end end function table:ifind(element) for i=1, #self do if self[i] == element then return i end end return false end function table:sum() local r = 0 for i=1, #self do r = r + self[i] end return r end function table:merge(table2) for i,v in pairs(table2) do if (type(v)=='table') then local sv = type(self[i]) if (sv == 'table')or(sv == 'nil') then if (sv == 'nil') then self[i] = {} end table.merge(self[i],v) end elseif (self[i] == nil) then self[i] = v end end end function table:iequal(table2) for i,v in pairs(self) do if (table2[i] ~= v) then return false end end for i,v in pairs(table2) do if (self[i] ~= v) then return false end end return true end function table:iequal(table2) local length = #self if (length ~= #table2) then return false end for i=1,length do if (self[i] ~= table2[i]) then return false end end return true end function table:size() local cnt = 0 for _ in pairs(self) do cnt = cnt + 1 end return cnt end --//============================================================================= local weak_meta = {__mode='v'} function CreateWeakTable() local m = {} setmetatable(m, weak_meta) return m end --//============================================================================= function math.round(num,idp) if (not idp) then return math.floor(num+.5) else return ("%." .. idp .. "f"):format(num) --local mult = 10^(idp or 0) --return math.floor(num * mult + 0.5) / mult end end --//============================================================================= function InvertColor(c) return {1 - c[1], 1 - c[2], 1 - c[3], c[4]} end function math.mix(x, y, a) return y * a + x * (1 - a) end function mulColor(c, s) return {s * c[1], s * c[2], s * c[3], c[4]} end function mulColors(c1, c2) return {c1[1] * c2[1], c1[2] * c2[2], c1[3] * c2[3], c1[4] * c2[4]} end function mixColors(c1, c2, a) return { math.mix(c1[1], c2[1], a), math.mix(c1[2], c2[2], a), math.mix(c1[3], c2[3], a), math.mix(c1[4], c2[4], a) } end function color2incolor(r,g,b,a) if type(r) == 'table' then r,g,b,a = unpack4(r) end local inColor = '\255\255\255\255' if r then inColor = string.char(255, r*255, g*255, b*255) end return inColor end function incolor2color(inColor) local a = 255 local r,g,b = inColor:sub(2,4):byte(1,3) return r/255, g/255, b/255, a/255 end --//=============================================================================
gpl-2.0
tonylauCN/tutorials
openresty/debugger/lualibs/metalua/compiler/parser/annot/generator.lua
7
1618
-------------------------------------------------------------------------------- -- Copyright (c) 2006-2013 Fabien Fleutot and others. -- -- All rights reserved. -- -- This program and the accompanying materials are made available -- under the terms of the Eclipse Public License v1.0 which -- accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- This program and the accompanying materials are also made available -- under the terms of the MIT public license which accompanies this -- distribution, and is available at http://www.lua.org/license.html -- -- Contributors: -- Fabien Fleutot - API and implementation -- -------------------------------------------------------------------------------- require 'checks' local gg = require 'metalua.grammar.generator' local M = { } function M.opt(mlc, primary, a_type) checks('table', 'table|function', 'string') return gg.sequence{ primary, gg.onkeyword{ "#", function() return assert(mlc.annot[a_type]) end }, builder = function(x) local t, annot = unpack(x) return annot and { tag='Annot', t, annot } or t end } end -- split a list of "foo" and "`Annot{foo, annot}" into a list of "foo" -- and a list of "annot". -- No annot list is returned if none of the elements were annotated. function M.split(lst) local x, a, some = { }, { }, false for i, p in ipairs(lst) do if p.tag=='Annot' then some, x[i], a[i] = true, unpack(p) else x[i] = p end end if some then return x, a else return lst end end return M
apache-2.0
omidtarh/wizard
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
serl/vlc
share/lua/playlist/metachannels.lua
92
2096
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Rémi Duraffort <ivoire at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] require "simplexml" function probe() return vlc.access == 'http' and string.match( vlc.path, 'metachannels.com' ) end function parse() local webpage = '' while true do local line = vlc.readline() if line == nil then break end webpage = webpage .. line end local feed = simplexml.parse_string( webpage ) local channel = feed.children[1] -- list all children that are items local tracks = {} for _,item in ipairs( channel.children ) do if( item.name == 'item' ) then simplexml.add_name_maps( item ) local url = vlc.strings.resolve_xml_special_chars( item.children_map['link'][1].children[1] ) local title = vlc.strings.resolve_xml_special_chars( item.children_map['title'][1].children[1] ) local arturl = nil if item.children_map['media:thumbnail'] then arturl = vlc.strings.resolve_xml_special_chars( item.children_map['media:thumbnail'][1].attributes['url'] ) end table.insert( tracks, { path = url, title = title, arturl = arturl, options = {':play-and-pause'} } ) end end return tracks end
gpl-2.0
bungle/lua-resty-nettle
lib/resty/nettle/types/nettle-types.lua
1
1173
local ffi = require "ffi" local ffi_cdef = ffi.cdef ffi_cdef [[ union nettle_block16 { uint8_t b[16]; unsigned long w[16 / sizeof(unsigned long)]; uint64_t u64[2]; }; union nettle_block8 { uint8_t b[8]; uint64_t u64; }; typedef void nettle_random_func(void *ctx, size_t length, uint8_t *dst); typedef void nettle_progress_func(void *ctx, int c); typedef void *nettle_realloc_func(void *ctx, void *p, size_t length); typedef void nettle_set_key_func(void *ctx, const uint8_t *key); typedef void nettle_cipher_func(const void *ctx, size_t length, uint8_t *dst, const uint8_t *src); typedef void nettle_crypt_func(void *ctx, size_t length, uint8_t *dst, const uint8_t *src); typedef void nettle_hash_init_func(void *ctx); typedef void nettle_hash_update_func(void *ctx, size_t length, const uint8_t *src); typedef void nettle_hash_digest_func(void *ctx, size_t length, uint8_t *dst); ]]
bsd-2-clause
famellad/oldschool-scroller
deps-main.lua
1
4732
-- Load libs require("libs.AnAL") -- Library for animations (is there another one?) -- Base classes require("game") -- Basic game handling require("static") -- Static functions and variables require("console") -- Game console TODO require("debug-print") -- Debug output functions require("entity") -- Generic entity that may appear in the game area -- Load Controller classes require("lua-ctl.controller") -- General controller class require("lua-ctl.controller-keyboard") -- Keyboard compatibility require("lua-ctl.controller-xbox") -- Xbox gamepad compat -- States and scenes require("game-state") -- Class holding the game state (everything after starting new game) require("lua-scenes.scene") -- Base scene class require("lua-scenes.scene-menu") -- Parent scene for screens that are handled as menus require("lua-scenes.scene-gamearea") -- Parent scene for screens that are handled as playable require("lua-scenes.lua-menus.scene-title") -- Scene for the titles and the "press start" require("lua-scenes.lua-menus.scene-mainmenu") -- Main menu scene (new, cont, opts etc) -- Direction and staging require("lua-staging.director") -- The director that controls the waves :) require("lua-staging.stage") -- Stage class require("lua-staging.challenge") -- Challenge prototype require("lua-staging.wave") -- Wave prototype require("deps-challenge") -- Challenges for stages require("deps-waves") -- Waves for challenges -- Load Player require("lua-player.player") -- Player class require("lua-player.player-weapons") -- Player weapons system require("lua-player.player-movement") -- Player movement -- Load Entities require("lua-actors.enemy") -- Generic enemy require("lua-actors.enemies.enemy-asteroid") -- Medium Asteroid require("lua-actors.enemies.enemy-asteroid-small") -- Small Asteroid require("lua-actors.enemies.enemy-medium") -- Medium shooty enemy require("lua-actors.enemies.enemy-simu-med") -- Medium simu shooty enemy require("lua-actors.enemies.enemy-mine") -- Mine enemy require("lua-actors.powerup") -- Generic powerup that may be picked up require("lua-actors.powerups.powerup-hp") -- Health powerup require("lua-actors.powerups.powerup-hp-full") -- Full Health powerup require("lua-actors.powerups.powerup-sp") -- Shield powerup require("lua-actors.powerups.powerup-sp-full") -- Full Shield powerup require("lua-actors.powerups.powerup-pp") -- Energy powerup require("lua-actors.powerups.powerup-pp-full") -- Full Energy powerup -- Load Ships require("lua-actors.ship") -- Prototype ship class require("lua-actors.ships.arrow") -- The main ship in the game require("lua-actors.ships.dart") -- PIECES OF UTTER require("lua-actors.ships.javelin") -- MEGA USELESSNESS -- Load Particle Systems require("lua-part.bullet-system") -- Bullet system class, for all your bullet needs require("lua-part.bullet") -- A single individual bullet (Prototype) require("lua-part.bullets.bullet-hammer") -- Hammer bullets require("lua-part.explosion") -- Prototype explosion require("lua-part.explosions.explosion-hit") -- Bullet hit require("lua-part.explosions.explosion-med") -- Medium sized explosion require("lua-part.emitter") -- Particle emitter require("lua-part.particle") -- A single particle (prototype) -- Load Emitters require("lua-part.emitters.emitter-exhaust") -- Fire-like emitter require("lua-part.emitters.emitter-explosion") -- Hot red debris flying off in every direction -- Load Particles require("lua-part.particles.particle-small-fire") -- A small particle that goes from bright orange to dim red -- Aditional Visual Elements require("lua-bg.background") -- The backdrop (prototype) require("lua-bg.back-space-proto") -- Prototypical backdrop for space scenes require("lua-bg.back-nebula") -- Green nebula backdrop require("lua-bg.back-eagle") -- Red nebula backdrop require("lua-bg.back-simu") -- Simulation backdrop require("deps-gui") --require("shader") -- Weapons require("lua-we.weapon") -- Prototype weapon require("lua-we.weapon-hammer") -- Hammer weapon -- Load sounds require("lua-snd.TEsound") -- Class for controlling once-sounds --require("lua-snd.msm") require("lua-snd.music") -- Class for musics require("lua-snd.sound") -- I don't know what this does TODO -- Class system and post processing Class = require "libs.hump.class" -- I don't think these do anything shine = require "libs.shine"
gpl-2.0
geanux/darkstar
scripts/zones/Windurst_Woods/npcs/HomePoint#2.lua
17
1251
----------------------------------- -- Area: Windurst Woods -- NPC: HomePoint#2 -- @pos 107 -5 -56 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Windurst_Woods/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 26); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
geanux/darkstar
scripts/globals/mobskills/PW_Groundburst.lua
25
1068
--------------------------------------------- -- Groundburst -- -- Description: Expels a fireball on targets in an area of effect. -- Type: Physical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown radial -- Notes: Only used by notorious monsters, and from any Mamool Ja in besieged. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 1863) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 3; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
geanux/darkstar
scripts/zones/Apollyon/mobs/Ice_Elemental.lua
112
2441
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [1] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [2] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead()==true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
geanux/darkstar
scripts/zones/Apollyon/mobs/Light_Elemental.lua
112
2441
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [1] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [2] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead()==true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
eamosov/thrift
lib/lua/TBinaryProtocol.lua
90
6141
-- -- 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 'TProtocol' require 'libluabpack' require 'libluabitwise' TBinaryProtocol = __TObject.new(TProtocolBase, { __type = 'TBinaryProtocol', VERSION_MASK = -65536, -- 0xffff0000 VERSION_1 = -2147418112, -- 0x80010000 TYPE_MASK = 0x000000ff, strictRead = false, strictWrite = true }) function TBinaryProtocol:writeMessageBegin(name, ttype, seqid) if self.strictWrite then self:writeI32(libluabitwise.bor(TBinaryProtocol.VERSION_1, ttype)) self:writeString(name) self:writeI32(seqid) else self:writeString(name) self:writeByte(ttype) self:writeI32(seqid) end end function TBinaryProtocol:writeMessageEnd() end function TBinaryProtocol:writeStructBegin(name) end function TBinaryProtocol:writeStructEnd() end function TBinaryProtocol:writeFieldBegin(name, ttype, id) self:writeByte(ttype) self:writeI16(id) end function TBinaryProtocol:writeFieldEnd() end function TBinaryProtocol:writeFieldStop() self:writeByte(TType.STOP); end function TBinaryProtocol:writeMapBegin(ktype, vtype, size) self:writeByte(ktype) self:writeByte(vtype) self:writeI32(size) end function TBinaryProtocol:writeMapEnd() end function TBinaryProtocol:writeListBegin(etype, size) self:writeByte(etype) self:writeI32(size) end function TBinaryProtocol:writeListEnd() end function TBinaryProtocol:writeSetBegin(etype, size) self:writeByte(etype) self:writeI32(size) end function TBinaryProtocol:writeSetEnd() end function TBinaryProtocol:writeBool(bool) if bool then self:writeByte(1) else self:writeByte(0) end end function TBinaryProtocol:writeByte(byte) local buff = libluabpack.bpack('c', byte) self.trans:write(buff) end function TBinaryProtocol:writeI16(i16) local buff = libluabpack.bpack('s', i16) self.trans:write(buff) end function TBinaryProtocol:writeI32(i32) local buff = libluabpack.bpack('i', i32) self.trans:write(buff) end function TBinaryProtocol:writeI64(i64) local buff = libluabpack.bpack('l', i64) self.trans:write(buff) end function TBinaryProtocol:writeDouble(dub) local buff = libluabpack.bpack('d', dub) self.trans:write(buff) end function TBinaryProtocol:writeString(str) -- Should be utf-8 self:writeI32(string.len(str)) self.trans:write(str) end function TBinaryProtocol:readMessageBegin() local sz, ttype, name, seqid = self:readI32() if sz < 0 then local version = libluabitwise.band(sz, TBinaryProtocol.VERSION_MASK) if version ~= TBinaryProtocol.VERSION_1 then terror(TProtocolException:new{ message = 'Bad version in readMessageBegin: ' .. sz }) end ttype = libluabitwise.band(sz, TBinaryProtocol.TYPE_MASK) name = self:readString() seqid = self:readI32() else if self.strictRead then terror(TProtocolException:new{message = 'No protocol version header'}) end name = self.trans:readAll(sz) ttype = self:readByte() seqid = self:readI32() end return name, ttype, seqid end function TBinaryProtocol:readMessageEnd() end function TBinaryProtocol:readStructBegin() return nil end function TBinaryProtocol:readStructEnd() end function TBinaryProtocol:readFieldBegin() local ttype = self:readByte() if ttype == TType.STOP then return nil, ttype, 0 end local id = self:readI16() return nil, ttype, id end function TBinaryProtocol:readFieldEnd() end function TBinaryProtocol:readMapBegin() local ktype = self:readByte() local vtype = self:readByte() local size = self:readI32() return ktype, vtype, size end function TBinaryProtocol:readMapEnd() end function TBinaryProtocol:readListBegin() local etype = self:readByte() local size = self:readI32() return etype, size end function TBinaryProtocol:readListEnd() end function TBinaryProtocol:readSetBegin() local etype = self:readByte() local size = self:readI32() return etype, size end function TBinaryProtocol:readSetEnd() end function TBinaryProtocol:readBool() local byte = self:readByte() if byte == 0 then return false end return true end function TBinaryProtocol:readByte() local buff = self.trans:readAll(1) local val = libluabpack.bunpack('c', buff) return val end function TBinaryProtocol:readI16() local buff = self.trans:readAll(2) local val = libluabpack.bunpack('s', buff) return val end function TBinaryProtocol:readI32() local buff = self.trans:readAll(4) local val = libluabpack.bunpack('i', buff) return val end function TBinaryProtocol:readI64() local buff = self.trans:readAll(8) local val = libluabpack.bunpack('l', buff) return val end function TBinaryProtocol:readDouble() local buff = self.trans:readAll(8) local val = libluabpack.bunpack('d', buff) return val end function TBinaryProtocol:readString() local len = self:readI32() local str = self.trans:readAll(len) return str end TBinaryProtocolFactory = TProtocolFactory:new{ __type = 'TBinaryProtocolFactory', strictRead = false } function TBinaryProtocolFactory:getProtocol(trans) -- TODO Enforce that this must be a transport class (ie not a bool) if not trans then terror(TProtocolException:new{ message = 'Must supply a transport to ' .. ttype(self) }) end return TBinaryProtocol:new{ trans = trans, strictRead = self.strictRead, strictWrite = true } end
apache-2.0
geanux/darkstar
scripts/zones/Behemoths_Dominion/mobs/King_Behemoth.lua
23
1825
----------------------------------- -- Area: Behemoth's Dominion -- HNM: King Behemoth ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_MAGIC_COOL, 60); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) killer:addTitle(BEHEMOTH_DETHRONER); if (math.random((1),(100)) <= 5) then -- Hardcoded "this or this item" drop rate until implemented. SetDropRate(1936,13566,1000); -- Defending Ring SetDropRate(1936,13415,0); else SetDropRate(1936,13566,0); SetDropRate(1936,13415,1000); -- Pixie Earring end -- Set King_Behemoth's Window Open Time if (LandKingSystem_HQ == 0 or LandKingSystem_HQ == 2) then local wait = 72 * 3600 SetServerVariable("[POP]King_Behemoth", os.time(t) + wait); -- 3 days DeterMob(mob:getID(), true); end -- Set Behemoth's spawnpoint and respawn time (21-24 hours) if (LandKingSystem_NQ == 0 or LandKingSystem_NQ == 2) then SetServerVariable("[PH]King_Behemoth", 0); local Behemoth = 17297440; DeterMob(Behemoth, false); UpdateNMSpawnPoint(Behemoth); GetMobByID(Behemoth):setRespawnTime(math.random((75600),(86400))); end end; function onSpellPrecast(mob, spell) if (spell:getID() == 218) then spell:setAoE(SPELLAOE_RADIAL); spell:setFlag(SPELLFLAG_HIT_ALL); spell:setRadius(30); spell:setAnimation(280); spell:setMPCost(1); end end;
gpl-3.0
h0tw1r3/mame
3rdparty/genie/tests/base/test_config_bug.lua
9
3732
T.config_bug_report = { } local config_bug = T.config_bug_report local vs10_helpers = premake.vstudio.vs10_helpers local sln, prjA,prjB,prjC,prjD function config_bug.teardown() sln = nil prjA = nil prjB = nil prjC = nil prjD = nil end function config_bug.setup() end local config_bug_updated = function () local setCommonLibraryConfig = function() configuration "Debug or Release" kind "StaticLib" configuration "DebugDLL or ReleaseDLL" kind "SharedLib" end sln = solution "Test" configurations { "Debug", "Release", "DebugDLL", "ReleaseDLL" } language "C++" prjA = project "A" files { "a.cpp" } setCommonLibraryConfig() prjB = project "B" files { "b.cpp" } setCommonLibraryConfig() configuration "SharedLib" links { "A" } prjC = project "C" files { "c.cpp" } setCommonLibraryConfig() configuration "SharedLib" links { "A", "B" } prjD = project "Executable" kind "WindowedApp" links { "A", "B", "C" } end local kindSetOnConfiguration_and_linkSetOnSharedLibProjB = function (config_kind) sln = solution "DontCare" configurations { "DebugDLL"} configuration "DebugDLL" kind(config_kind) prjA = project "A" prjB = project "B" configuration { config_kind } links { "A" } end local sharedLibKindSetOnProject_and_linkSetOnSharedLibProjB = function () sln = solution "DontCare" configurations { "DebugDLL" } project "A" prjB = project "B" configuration "DebugDLL" kind "SharedLib" configuration "SharedLib" links { "A" } defines {"defineSet"} end function kind_set_on_project_config_block() sln = solution "DontCare" configurations { "DebugDLL" } local A = project "A" configuration "DebugDLL" kind "SharedLib" defines {"defineSet"} return A end function config_bug.bugUpdated_prjBLinksContainsA() config_bug_updated() premake.bake.buildconfigs() local conf = premake.getconfig(prjB,"DebugDLL","Native") test.isnotnil(conf.links.A) end function config_bug.kindSetOnProjectConfigBlock_projKindEqualsSharedLib() local proj = kind_set_on_project_config_block() premake.bake.buildconfigs() local conf = premake.getconfig(proj,"DebugDLL","Native") test.isequal("SharedLib",conf.kind) end function config_bug.defineSetOnProjectConfigBlock_projDefineSetIsNotNil() local proj = kind_set_on_project_config_block() premake.bake.buildconfigs() local conf = premake.getconfig(proj,"DebugDLL","Native") test.isnotnil(conf.defines.defineSet) end function config_bug.defineSetInBlockInsideProject () sharedLibKindSetOnProject_and_linkSetOnSharedLibProjB() premake.bake.buildconfigs() local conf = premake.getconfig(prjB,"DebugDLL","Native") test.isnotnil(conf.defines.defineSet) end function config_bug.whenKindSetOnProject_PrjBLinksContainsA() sharedLibKindSetOnProject_and_linkSetOnSharedLibProjB() premake.bake.buildconfigs() local conf = premake.getconfig(prjB,"DebugDLL","Native") test.isnotnil(conf.links.A) end function config_bug.whenKindSetOnConfiguration_prjBLinksContainsA_StaticLib() -- sharedLibKindSetOnConfiguration_and_linkSetOnSharedLibProjB() kindSetOnConfiguration_and_linkSetOnSharedLibProjB("StaticLib") premake.bake.buildconfigs() local config = premake.getconfig(prjB,"DebugDLL","Native") test.isnotnil(config.links.A) end function config_bug.whenKindSetOnConfiguration_prjBLinksContainsA() -- sharedLibKindSetOnConfiguration_and_linkSetOnSharedLibProjB() kindSetOnConfiguration_and_linkSetOnSharedLibProjB("SharedLib") premake.bake.buildconfigs() local config = premake.getconfig(prjB,"DebugDLL","Native") test.isnotnil(config.links.A) end
gpl-2.0
geanux/darkstar
scripts/zones/Metalworks/npcs/Grohm.lua
19
2699
----------------------------------- -- Area: Metalworks -- NPC: Grohm -- Involved In Mission: Journey Abroad -- @pos -18 -11 -27 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK) then if (player:getVar("notReceivePickaxe") == 1) then player:startEvent(0x01a9); elseif (player:getVar("MissionStatus") == 4) then player:startEvent(0x01a7); elseif (player:getVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(0x01a8); else player:startEvent(0x01a6); end elseif (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2) then if (player:getVar("MissionStatus") == 9) then player:startEvent(0x01aa); else player:startEvent(0x01ab); end elseif (player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK) then if (player:getVar("notReceivePickaxe") == 1) then player:startEvent(0x01a9,1); elseif (player:getVar("MissionStatus") == 4) then player:startEvent(0x01a7,1); elseif (player:getVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(0x01a8,1); else player:startEvent(0x01a6); end elseif (player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) then if (player:getVar("MissionStatus") == 9) then player:startEvent(0x01aa,1); else player:startEvent(0x01ab,1); end else player:startEvent(0x01ab);--0x01a6 end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x01a7 or csid == 0x01a9) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,605); -- Pickaxes player:setVar("notReceivePickaxe",1); else player:addItem(605,5); player:messageSpecial(ITEM_OBTAINED,605); -- Pickaxes player:setVar("MissionStatus",5); player:setVar("notReceivePickaxe",0); end elseif (csid == 0x01aa) then player:setVar("MissionStatus",10); end end;
gpl-3.0