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/Bagnon_GuildBank/components/logToggle.lua
1
1789
--[[ logToggle.lua A guild log toggle widget --]] local L = LibStub('AceLocale-3.0'):GetLocale('Bagnon-GuildBank') local LogToggle = Bagnon:NewClass('LogToggle', 'CheckButton') LogToggle.Icons = { [[Interface\Icons\INV_Crate_03]], [[Interface\Icons\INV_Misc_Coin_01]], [[Interface\Icons\INV_Letter_20]] } --[[ Constructor ]]-- function LogToggle:New(parent, type) local b = self:Bind(CreateFrame('CheckButton', nil, parent)) b:SetSize(20, 20) b:RegisterForClicks('anyUp') local nt = b:CreateTexture() nt:SetTexture([[Interface\Buttons\UI-Quickslot2]]) nt:SetSize(35, 35) nt:SetPoint('CENTER', 0, -1) b:SetNormalTexture(nt) local pt = b:CreateTexture() pt:SetTexture([[Interface\Buttons\UI-Quickslot-Depress]]) pt:SetAllPoints(b) b:SetPushedTexture(pt) local ht = b:CreateTexture() ht:SetTexture([[Interface\Buttons\ButtonHilight-Square]]) ht:SetAllPoints(b) b:SetHighlightTexture(ht) local ct = b:CreateTexture() ct:SetTexture([[Interface\Buttons\CheckButtonHilight]]) ct:SetAllPoints(b) ct:SetBlendMode('ADD') b:SetCheckedTexture(ct) local icon = b:CreateTexture() icon:SetTexture(self.Icons[type]) icon:SetAllPoints(b) b:SetScript('OnClick', b.OnClick) b:SetScript('OnEnter', b.OnEnter) b:SetScript('OnLeave', b.OnLeave) b:SetScript('OnHide', b.OnHide) b.type = type return b end --[[ Interaction ]]-- function LogToggle:OnClick() self:GetParent():ShowPanel(self:GetChecked() and self.type) end function LogToggle:OnEnter() if self:GetRight() > (GetScreenWidth() / 2) then GameTooltip:SetOwner(self, 'ANCHOR_LEFT') else GameTooltip:SetOwner(self, 'ANCHOR_RIGHT') end GameTooltip:SetText(L['Log' .. self.type]) end function LogToggle:OnLeave() GameTooltip:Hide() end function LogToggle:OnHide() self:SetChecked(false) end
mit
liruqi/bigfoot
Interface/AddOns/Bagnon_Forever/db.lua
1
10968
--[[ Database.lua BagnonForever's implementation of BagnonDB --]] BagnonDB = CreateFrame('GameTooltip', 'BagnonDB', nil, 'GameTooltipTemplate') BagnonDB:SetScript('OnEvent', function(self, event, arg1) if arg1 == 'Bagnon_Forever' then self:UnregisterEvent('ADDON_LOADED') self:Initialize() end end) BagnonDB:RegisterEvent('ADDON_LOADED') --constants local CURRENT_VERSION = GetAddOnMetadata('Bagnon_Forever', 'Version') local NUM_EQUIPMENT_SLOTS = 19 --locals local currentPlayer = UnitName('player') --the name of the current player that's logged on local currentRealm = GetRealmName() --what currentRealm we're on local playerList --a sorted list of players --[[ Local Functions ]]-- local function ToIndex(bag, slot) if tonumber(bag) then return (bag < 0 and bag*100 - slot) or bag*100 + slot end return bag .. slot end local function ToBagIndex(bag) return (tonumber(bag) and bag*100) or bag end --returns the full item link only for items that have enchants/suffixes, otherwise returns the item's ID local function ToShortLink(link) if link then local a,b,c,d,e,f,g,h -- if string.find(link,"\124Hbattlepet")then -- a,b,c,d,e,f,g,h= link:match(':(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+)') -- if not h then -- h = 0 -- end -- else -- a,b,c,d,e,f,g,h = link:match('(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+)') -- end -- if(b == '0' and b == c and c == d and d == e and e == f and f == g) then -- return a -- end -- if not a then -- a = link:match('item:(%d+)') -- return a -- end -- return format('item:%s:%s:%s:%s:%s:%s:%s:%s', a, b, c, d, e, f, g, h) a = link:match('item:(%d+)') return a end end local function GetBagSize(bag) if bag == 'e' then return NUM_EQUIPMENT_SLOTS end return GetContainerNumSlots(bag) end --[[ Addon Loading ]]-- function BagnonDB:Initialize() self:LoadSettings() self:SetScript('OnEvent', function(self, event, ...) if self[event] then self[event](self, event, ...) end end) if IsLoggedIn() then self:PLAYER_LOGIN() else self:RegisterEvent('PLAYER_LOGIN') end end function BagnonDB:LoadSettings() if not(BagnonForeverDB and BagnonForeverDB.version) then BagnonForeverDB = {version = CURRENT_VERSION} else if CURRENT_VERSION ~= BagnonForeverDB.version then BagnonForeverDB = {version = CURRENT_VERSION} end end self.db = BagnonForeverDB if not self.db[currentRealm] then self.db[currentRealm] = {} end self.rdb = self.db[currentRealm] if not self.rdb[currentPlayer] then self.rdb[currentPlayer] = {} end self.pdb = self.rdb[currentPlayer] end --[[ Events ]]-- function BagnonDB:PLAYER_LOGIN() self:SaveMoney() self:UpdateBag(BACKPACK_CONTAINER) -- self:UpdateBag(KEYRING_CONTAINER) self:SaveEquipment() self:SaveNumBankSlots() self:RegisterEvent('BANKFRAME_OPENED') self:RegisterEvent('BANKFRAME_CLOSED') self:RegisterEvent('PLAYER_MONEY') self:RegisterEvent('BAG_UPDATE') self:RegisterEvent('PLAYERBANKSLOTS_CHANGED') self:RegisterEvent('PLAYERREAGENTBANKSLOTS_CHANGED') self:RegisterEvent('UNIT_INVENTORY_CHANGED') self:RegisterEvent('PLAYERBANKBAGSLOTS_CHANGED') bf_LoadBagnonDB() end function BagnonDB:PLAYER_MONEY() self:SaveMoney() end function BagnonDB:BAG_UPDATE(event, bag) if not(bag == BANK_CONTAINER or bag > NUM_BAG_SLOTS or bag == REAGENTBANK_CONTAINER) or self.atBank then self:OnBagUpdate(bag) end end function BagnonDB:PLAYERBANKSLOTS_CHANGED() self:UpdateBag(BANK_CONTAINER) end function BagnonDB:PLAYERREAGENTBANKSLOTS_CHANGED() self:UpdateBag(REAGENTBANK_CONTAINER) end function BagnonDB:PLAYERBANKBAGSLOTS_CHANGED() self:SaveNumBankSlots() end function BagnonDB:BANKFRAME_OPENED() self.atBank = true self:UpdateBag(BANK_CONTAINER) self:UpdateBag(REAGENTBANK_CONTAINER) for i = 1, GetNumBankSlots() do self:UpdateBag(i + 4) end end function BagnonDB:BANKFRAME_CLOSED() self.atBank = nil end function BagnonDB:UNIT_INVENTORY_CHANGED(event, unit) if unit == 'player' then self:SaveEquipment() end end --[[ BagnonDB:GetPlayerList() returns: iterator of all players on this realm with data usage: for playerName, data in BagnonDB:GetPlayers() --]] function BagnonDB:GetPlayerList() if(not playerList) then playerList = {} for player in self:GetPlayers() do table.insert(playerList, player) end --sort by currentPlayer first, then alphabetically table.sort(playerList, function(a, b) if(a == currentPlayer) then return true elseif(b == currentPlayer) then return false end return a < b end) end return playerList end function BagnonDB:GetPlayers() return pairs(self.rdb or {}) end --[[ BagnonDB:GetMoney(player) args: player (string) the name of the player we're looking at. This is specific to the current realm we're on returns: (number) How much money, in copper, the given player has --]] function BagnonDB:GetMoney(player) local playerData = self.rdb[player] if playerData then return playerData.g or 0 end return 0 end --[[ BagnonDB:GetNumBankSlots(player) args: player (string) the name of the player we're looking at. This is specific to the current realm we're on returns: (number or nil) How many bank slots the current player has purchased --]] function BagnonDB:GetNumBankSlots(player) local playerData = self.rdb[player] if playerData then return playerData.numBankSlots end end --[[ BagnonDB:GetBagData(bag, player) args: player (string) the name of the player we're looking at. This is specific to the current realm we're on bag (number) the number of the bag we're looking at. returns: size (number) How many items the bag can hold (number) hyperlink (string) The hyperlink of the bag count (number) How many items are in the bag. This is used by ammo and soul shard bags --]] function BagnonDB:GetBagData(bag, player) local playerDB = self.rdb[player] if playerDB then local bagInfo = playerDB[ToBagIndex(bag)] if bagInfo then local size, link, count = strsplit(',', bagInfo) local hyperLink = (link and select(2, GetItemInfo(link))) or nil return tonumber(size), hyperLink, tonumber(count) or 1, GetItemIcon(link) end end end --[[ BagnonDB:GetItemData(bag, slot, player) args: player (string) the name of the player we're looking at. This is specific to the current realm we're on bag (number) the number of the bag we're looking at. itemSlot (number) the specific item slot we're looking at returns: hyperLink (string) The hyperLink of the item count (number) How many of there are of the specific item texture (string) The filepath of the item's texture quality (number) The numeric representaiton of the item's quality: from 0 (poor) to 7 (artifcat) --]] function BagnonDB:GetItemData(bag, slot, player) local playerDB = self.rdb[player] if playerDB then local itemInfo = playerDB[ToIndex(bag, slot)] if itemInfo then local link, count = strsplit(',', itemInfo) if link then local hyperLink, quality = select(2, GetItemInfo(link)) return hyperLink, tonumber(count) or 1, GetItemIcon(link), tonumber(quality) end end end end --[[ Returns how many of the specific item id the given player has in the given bag --]] function BagnonDB:GetItemCount(itemLink, bag, player) local total = 0 local itemLink = select(2, GetItemInfo(ToShortLink(itemLink))) local size = (self:GetBagData(bag, player)) or 0 for slot = 1, size do local link, count = self:GetItemData(bag, slot, player) if link == itemLink then total = total + (count or 1) end end return total end --[[ Storage Functions How we store the data (duh) --]] --[[ Storage Functions ]]-- function BagnonDB:SaveMoney() self.pdb.g = GetMoney() end function BagnonDB:SaveNumBankSlots() self.pdb.numBankSlots = GetNumBankSlots() end --saves all the player's equipment data information function BagnonDB:SaveEquipment() for slot = 0, NUM_EQUIPMENT_SLOTS do local link = GetInventoryItemLink('player', slot) local index = ToIndex('e', slot) if link then local link = ToShortLink(link) local count = GetInventoryItemCount('player', slot) count = count > 1 and count or nil if(link and count) then self.pdb[index] = format('%s,%d', link, count) else self.pdb[index] = link end else self.pdb[index] = nil end end end --saves data about a specific item the current player has function BagnonDB:SaveItem(bag, slot) local texture, count = GetContainerItemInfo(bag, slot) local index = ToIndex(bag, slot) if texture then local link = ToShortLink(GetContainerItemLink(bag, slot)) count = count > 1 and count or nil if(link and count) then self.pdb[index] = format('%s,%d', link, count) else self.pdb[index] = link end else self.pdb[index] = nil end end --saves all information about the given bag, EXCEPT the bag's contents function BagnonDB:SaveBag(bag) local data = self.pdb local size = GetBagSize(bag) local index = ToBagIndex(bag) if size > 0 then local equipSlot = bag > 0 and ContainerIDToInventoryID(bag) local link = ToShortLink(GetInventoryItemLink('player', equipSlot)) local count = GetInventoryItemCount('player', equipSlot) if count < 1 then count = nil end if(size and link and count) then self.pdb[index] = format('%d,%s,%d', size, link, count) elseif(size and link) then self.pdb[index] = format('%d,%s', size, link) else self.pdb[index] = size end else self.pdb[index] = nil end end --saves both relevant information about the given bag, and all information about items in the given bag function BagnonDB:UpdateBag(bag) self:SaveBag(bag) for slot = 1, GetBagSize(bag) do self:SaveItem(bag, slot) end end function BagnonDB:OnBagUpdate(bag) if self.atBank then for i = 1, (NUM_BAG_SLOTS + GetNumBankSlots()) do self:SaveBag(i) end else for i = 1, NUM_BAG_SLOTS do self:SaveBag(i) end end for slot = 1, GetBagSize(bag) do self:SaveItem(bag, slot) end end --[[ Removal Functions ]]-- --removes all saved data about the given player function BagnonDB:RemovePlayer(player, realm) local realm = realm or currentRealm local rdb = self.db[realm] if rdb then rdb[player] = nil end if realm == currentRealm and playerList then for i,character in pairs(playerList) do if(character == player) then table.remove(playerList, i) break end end end end
mit
liruqi/bigfoot
Interface/AddOns/Recount/TrackerModules/TrackerModule_Interrupts.lua
1
4296
local Recount = _G.Recount local AceLocale = LibStub("AceLocale-3.0") local L = AceLocale:GetLocale( "Recount" ) local revision = tonumber(string.sub("$Revision: 1311 $", 12, -3)) if Recount.Version < revision then Recount.Version = revision end local GameTooltip = GameTooltip local dbCombatants local srcRetention local dstRetention local DetailTitles = { } DetailTitles.Interrupts = { TopNames = L["Interrupted Who"], TopCount = "", TopAmount = L["Interrupts"], BotNames = L["Interrupted"], BotMin = "", BotAvg = "", BotMax = "", BotAmount = L["Count"] } function Recount:SpellInterrupt(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, spellId, spellName, spellSchool, extraSpellId, extraSpellName, extraSpellSchool) if not spellName then spellName = "Melee" end local ability = extraSpellName .. " (" .. spellName .. ")" Recount:AddInterruptData(srcName, dstName, ability, srcGUID, srcFlags, dstGUID, dstFlags, extraSpellId) -- Elsia: Keep both interrupting spell and interrupted spell end function Recount:AddInterruptData(source, victim, ability, srcGUID, srcFlags, dstGUID, dstFlags, spellId) -- Friendly fire interrupt? (Duels) local FriendlyFire = Recount:IsFriendlyFire(srcFlags, dstFlags) -- Before any further processing need to check if we are going to be placed in combat or in combat if not Recount.InCombat and Recount.db.profile.RecordCombatOnly then if (not FriendlyFire) and (Recount:InGroup(srcFlags) or Recount:InGroup(dstFlags)) then Recount:PutInCombat() else return end end -- Need to add events for potential deaths Recount.cleventtext = source.." interrupts "..victim.." "..ability -- Name and ID of pet owners local sourceowner local sourceownerID local victimowner local victimownerID source, sourceowner, sourceownerID = Recount:DetectPet(source, srcGUID, srcFlags) victim, victimowner, victimownerID = Recount:DetectPet(victim, dstGUID, dstFlags) srcRetention = Recount.srcRetention if srcRetention then if not dbCombatants[source] then Recount:AddCombatant(source, sourceowner, srcGUID, srcFlags, sourceownerID) end -- Elsia: Until here is if pets interupts anybody. local sourceData = dbCombatants[source] if sourceData then Recount:SetActive(sourceData) Recount:AddCurrentEvent(sourceData, "MISC", false, nil, Recount.cleventtext) -- Fight tracking purposes to speed up leaving combat sourceData.LastFightIn = Recount.db2.FightNum Recount:AddAmount(sourceData, "Interrupts", 1) Recount:AddTableDataSum(sourceData,"InterruptData",victim,ability,1) end end dstRetention = Recount.dstRetention if dstRetention then if not dbCombatants[victim] then Recount:AddCombatant(victim, victimowner, dstGUID, dstFlags, victimownerID) -- Elsia: Bug, owner missing here end local victimData = dbCombatants[victim] if victimData then Recount:SetActive(victimData) Recount:AddCurrentEvent(victimData, "MISC", true, nil, Recount.cleventtext) -- Fight tracking purposes to speed up leaving combat victimData.LastFightIn = Recount.db2.FightNum end end end local DataModes = { } function DataModes:InterruptReturner(data, num) if not data then return 0 end if num == 1 then return (data.Fights[Recount.db.profile.CurDataSet].Interrupts or 0) end return (data.Fights[Recount.db.profile.CurDataSet].Interrupts or 0), {{data.Fights[Recount.db.profile.CurDataSet].InterruptData, L["'s Interrupts"], DetailTitles.Interrupts}} end local TooltipFuncs = { } function TooltipFuncs:Interrupts(name, data) --local SortedData, total GameTooltip:ClearLines() GameTooltip:AddLine(name) Recount:AddSortedTooltipData(L["Top 3"].." "..L["Interrupted"],data and data.Fights[Recount.db.profile.CurDataSet] and data.Fights[Recount.db.profile.CurDataSet].InterruptData, 3) GameTooltip:AddLine("<"..L["Click for more Details"]..">", 0, 0.9, 0) end Recount:AddModeTooltip(L["Interrupts"], DataModes.InterruptReturner, TooltipFuncs.Interrupts, nil, nil, nil, nil) local oldlocalizer = Recount.LocalizeCombatants function Recount.LocalizeCombatants() dbCombatants = Recount.db2.combatants oldlocalizer() end
mit
ingran/balzac
custom_feeds/teltonika_luci/applications/luci-diag-devinfo/luasrc/controller/luci_diag/netdiscover_common.lua
14
3181
--[[ Luci diag - Diagnostics controller module (c) 2009 Daniel Dickinson 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.controller.luci_diag.netdiscover_common", package.seeall) require("luci.i18n") require("luci.util") require("luci.sys") require("luci.cbi") require("luci.model.uci") local translate = luci.i18n.translate local DummyValue = luci.cbi.DummyValue local SimpleSection = luci.cbi.SimpleSection function index() return -- no-op end function get_params() local netdiscover_uci = luci.model.uci.cursor() netdiscover_uci:load("luci_devinfo") local nettable = netdiscover_uci:get_all("luci_devinfo") local i local subnet local netdout local outnets = {} i = next(nettable, nil) while (i) do if (netdiscover_uci:get("luci_devinfo", i) == "netdiscover_scannet") then local scannet = netdiscover_uci:get_all("luci_devinfo", i) if scannet["subnet"] and (scannet["subnet"] ~= "") and scannet["enable"] and ( scannet["enable"] == "1") then local output = "" local outrow = {} outrow["interface"] = scannet["interface"] outrow["timeout"] = 10 local timeout = tonumber(scannet["timeout"]) if timeout and ( timeout > 0 ) then outrow["timeout"] = scannet["timeout"] end outrow["repeat_count"] = 1 local repcount = tonumber(scannet["repeat_count"]) if repcount and ( repcount > 0 ) then outrow["repeat_count"] = scannet["repeat_count"] end outrow["sleepreq"] = 100 local repcount = tonumber(scannet["sleepreq"]) if repcount and ( repcount > 0 ) then outrow["sleepreq"] = scannet["sleepreq"] end outrow["subnet"] = scannet["subnet"] outrow["output"] = output outnets[i] = outrow end end i = next(nettable, i) end return outnets end function command_function(outnets, i) local interface = luci.controller.luci_diag.devinfo_common.get_network_device(outnets[i]["interface"]) return "/usr/bin/netdiscover-to-devinfo " .. outnets[i]["subnet"] .. " " .. interface .. " " .. outnets[i]["timeout"] .. " -r " .. outnets[i]["repeat_count"] .. " -s " .. outnets[i]["sleepreq"] .. " </dev/null" end function action_links(netdiscovermap, mini) luci.i18n.loadc("diag_devinfo") s = netdiscovermap:section(SimpleSection, "", translate("Actions")) b = s:option(DummyValue, "_config", translate("Configure Scans")) b.value = "" if (mini) then b.titleref = luci.dispatcher.build_url("mini", "network", "netdiscover_devinfo_config") else b.titleref = luci.dispatcher.build_url("admin", "network", "diag_config", "netdiscover_devinfo_config") end b = s:option(DummyValue, "_scans", translate("Repeat Scans (this can take a few minutes)")) b.value = "" if (mini) then b.titleref = luci.dispatcher.build_url("mini", "diag", "netdiscover_devinfo") else b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo") end end
gpl-2.0
gonku/awesome-wm-pabucolor
lain/widgets/net.lua
1
3150
--[[ Licensed under GNU General Public License v2 * (c) 2013, Luke Bonham * (c) 2010-2012, Peter Hofmann --]] local helpers = require("lain.helpers") local notify_fg = require("beautiful").fg_focus local naughty = require("naughty") local wibox = require("wibox") local io = io local tostring = tostring local string = { format = string.format, gsub = string.gsub } local setmetatable = setmetatable -- Network infos -- lain.widgets.net local net = { last_t = 0, last_r = 0 } function net.get_device() f = io.popen("ip link show | cut -d' ' -f2,9") ws = f:read("*all") f:close() ws = ws:match("%w+: UP") if ws ~= nil then return ws:gsub(": UP", "") else return "network off" end end local function worker(args) local args = args or {} local timeout = args.timeout or 2 local iface = args.iface or net.get_device() local units = args.units or 1024 --kb local notify = args.notify or "on" local settings = args.settings or function() end net.widget = wibox.widget.textbox('') helpers.set_map(iface, true) function update() net_now = {} if iface == "" then iface = net.get_device() end net_now.carrier = helpers.first_line('/sys/class/net/' .. iface .. '/carrier') or "0" net_now.state = helpers.first_line('/sys/class/net/' .. iface .. '/operstate') or "down" local now_t = helpers.first_line('/sys/class/net/' .. iface .. '/statistics/tx_bytes') or 0 local now_r = helpers.first_line('/sys/class/net/' .. iface .. '/statistics/rx_bytes') or 0 net_now.sent = tostring((now_t - net.last_t) / timeout / units) net_now.sent = string.gsub(string.format('%.1f', net_now.sent), ",", ".") net_now.received = tostring((now_r - net.last_r) / timeout / units) net_now.received = string.gsub(string.format('%.1f', net_now.received), ",", ".") widget = net.widget settings() net.last_t = now_t net.last_r = now_r if net_now.carrier ~= "1" and notify == "on" then if helpers.get_map(iface) then naughty.notify({ title = iface, text = "no carrier", timeout = 7, position = "top_left", icon = helpers.icons_dir .. "no_net.png", fg = notify_fg or "#FFFFFF" }) helpers.set_map(iface, false) end else helpers.set_map(iface, true) end end helpers.newtimer(iface, timeout, update) return net.widget end return setmetatable(net, { __call = function(_, ...) return worker(...) end })
gpl-2.0
shiprabehera/kong
spec/03-plugins/17-jwt/02-api_spec.lua
4
9852
local helpers = require "spec.helpers" local cjson = require "cjson" local jwt_secrets = helpers.dao.jwt_secrets local fixtures = require "spec.03-plugins.17-jwt.fixtures" describe("Plugin: jwt (API)", function() local admin_client, consumer, jwt_secret setup(function() helpers.run_migrations() assert(helpers.start_kong()) admin_client = helpers.admin_client() end) teardown(function() if admin_client then admin_client:close() end helpers.stop_kong() end) describe("/consumers/:consumer/jwt/", function() setup(function() consumer = assert(helpers.dao.consumers:insert { username = "bob" }) assert(helpers.dao.consumers:insert { username = "alice" }) end) describe("POST", function() local jwt1, jwt2 teardown(function() if jwt1 == nil then return end jwt_secrets:delete(jwt1) jwt_secrets:delete(jwt2) end) it("creates a jwt secret", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = {}, headers = { ["Content-Type"] = "application/json" } }) local body = cjson.decode(assert.res_status(201, res)) assert.equal(consumer.id, body.consumer_id) jwt1 = body end) it("accepts any given `secret` and `key` parameters", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = { key = "bob2", secret = "tooshort" }, headers = { ["Content-Type"] = "application/json" } }) local body = cjson.decode(assert.res_status(201, res)) assert.equal("bob2", body.key) assert.equal("tooshort", body.secret) jwt2 = body end) it("accepts duplicate `secret` parameters across jwt_secrets", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/alice/jwt/", body = { key = "alice", secret = "foobarbaz" }, headers = { ["Content-Type"] = "application/json" } }) local body = cjson.decode(assert.res_status(201, res)) assert.equal("alice", body.key) assert.equal("foobarbaz", body.secret) jwt1 = body res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = { key = "bobsyouruncle", secret = "foobarbaz" }, headers = { ["Content-Type"] = "application/json" } }) body = cjson.decode(assert.res_status(201, res)) assert.equal("bobsyouruncle", body.key) assert.equal("foobarbaz", body.secret) jwt2 = body assert.equals(jwt1.secret, jwt2.secret) end) it("accepts a valid public key for RS256 when posted urlencoded", function() local rsa_public_key = fixtures.rs256_public_key rsa_public_key = rsa_public_key:gsub("\n", "\r\n") rsa_public_key = rsa_public_key:gsub("([^%w %-%_%.%~])", function(c) return string.format ("%%%02X", string.byte(c)) end) rsa_public_key = rsa_public_key:gsub(" ", "+") local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = { key = "bob3", algorithm = "RS256", rsa_public_key = rsa_public_key }, headers = { ["Content-Type"] = "application/x-www-form-urlencoded" } }) assert.response(res).has.status(201) local json = assert.response(res).has.jsonbody() assert.equal("bob3", json.key) end) it("accepts a valid public key for RS256 when posted as json", function() local rsa_public_key = fixtures.rs256_public_key local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = { key = "bob4", algorithm = "RS256", rsa_public_key = rsa_public_key }, headers = { ["Content-Type"] = "application/json" } }) assert.response(res).has.status(201) local json = assert.response(res).has.jsonbody() assert.equal("bob4", json.key) end) it("fails with missing `rsa_public_key` parameter for RS256 algorithms", function () local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = { key = "bob5", algorithm = "RS256" }, headers = { ["Content-Type"] = "application/json" } }) assert.response(res).has.status(400) local json = assert.response(res).has.jsonbody() assert.equal("no mandatory 'rsa_public_key'", json.message) end) it("fails with an invalid rsa_public_key for RS256 algorithms", function () local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = { key = "bob5", algorithm = "RS256", rsa_public_key = "test", }, headers = { ["Content-Type"] = "application/json" } }) assert.response(res).has.status(400) local json = assert.response(res).has.jsonbody() assert.equal("'rsa_public_key' format is invalid", json.message) end) it("does not fail when `secret` parameter for HS256 algorithms is missing", function () local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = { key = "bob5", algorithm = "HS256", }, headers = { ["Content-Type"] = "application/json" } }) assert.response(res).has.status(201) local json = assert.response(res).has.jsonbody() assert.string(json.secret) assert.equals(32, #json.secret) assert.matches("^[%a%d]+$", json.secret) end) end) describe("PUT", function() it("creates and update", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/jwt/", body = {}, headers = { ["Content-Type"] = "application/json" } }) local body = cjson.decode(assert.res_status(201, res)) assert.equal(consumer.id, body.consumer_id) -- For GET tests jwt_secret = body end) end) describe("GET", function() it("retrieves all", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/jwt/", }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(6, #(body.data)) end) end) end) describe("/consumers/:consumer/jwt/:id", function() describe("GET", function() it("retrieves by id", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/jwt/" .. jwt_secret.id, }) assert.res_status(200, res) end) it("retrieves by key", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/jwt/" .. jwt_secret.key, }) assert.res_status(200, res) end) end) describe("PATCH", function() it("updates a credential by id", function() local res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/jwt/" .. jwt_secret.id, body = { key = "alice", secret = "newsecret" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(200, res) jwt_secret = cjson.decode(body) assert.equal("newsecret", jwt_secret.secret) end) it("updates a credential by key", function() local res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/jwt/" .. jwt_secret.key, body = { key = "alice", secret = "newsecret2" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(200, res) jwt_secret = cjson.decode(body) assert.equal("newsecret2", jwt_secret.secret) end) end) describe("DELETE", function() it("deletes a credential", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/jwt/" .. jwt_secret.id, body = {}, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(204, res) end) it("returns proper errors", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/jwt/" .. "blah", body = {}, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(404, res) local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/jwt/" .. "00000000-0000-0000-0000-000000000000", body = {}, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(404, res) end) end) end) end)
apache-2.0
TechAtNYU/wiki
extensions/Scribunto/tests/engines/LuaStandalone/StandaloneTests.lua
9
1406
local testframework = require( 'Module:TestFramework' ) local function setfenv1() local ok, err = pcall( function() setfenv( 2, {} ) end ) if not ok then err = string.gsub( err, '^%S+:%d+: ', '' ) error( err ) end end local function getfenv1() local env pcall( function() env = getfenv( 2 ) end ) return env end return testframework.getTestProvider( { { name = 'setfenv on a C function', func = setfenv1, expect = "'setfenv' cannot set the requested environment, it is protected", }, { name = 'getfenv on a C function', func = getfenv1, expect = { nil }, }, { name = 'Invalid array key (table)', func = mw.var_export, args = { { [{}] = 1 } }, expect = 'Cannot use table as an array key when passing data from Lua to PHP', }, { name = 'Invalid array key (boolean)', func = mw.var_export, args = { { [true] = 1 } }, expect = 'Cannot use boolean as an array key when passing data from Lua to PHP', }, { name = 'Invalid array key (function)', func = mw.var_export, args = { { [tostring] = 1 } }, expect = 'Cannot use function as an array key when passing data from Lua to PHP', }, { name = 'Unusual array key (float)', func = mw.var_export, args = { { [1.5] = 1 } }, expect = { "array ( '1.5' => 1, )" } }, { name = 'Unusual array key (inf)', func = mw.var_export, args = { { [math.huge] = 1 } }, expect = { "array ( 'inf' => 1, )" } }, } )
gpl-2.0
JohnPeacockMessageSystems/lxc
src/lua-lxc/lxc.lua
26
10159
-- -- lua lxc module -- -- Copyright © 2012 Oracle. -- -- Authors: -- Dwight Engen <dwight.engen@oracle.com> -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -- local core = require("lxc.core") local lfs = require("lfs") local table = require("table") local string = require("string") local io = require("io") module("lxc", package.seeall) local lxc_path local log_level = 3 -- lua 5.1 compat if table.unpack == nil then table.unpack = unpack end -- the following two functions can be useful for debugging function printf(...) local function wrapper(...) io.write(string.format(...)) end local status, result = pcall(wrapper, ...) if not status then error(result, 2) end end function log(level, ...) if (log_level >= level) then printf(os.date("%Y-%m-%d %T ")) printf(...) end end function string:split(delim, max_cols) local cols = {} local start = 1 local nextc repeat nextc = string.find(self, delim, start) if (nextc and #cols ~= max_cols - 1) then table.insert(cols, string.sub(self, start, nextc-1)) start = nextc + #delim else table.insert(cols, string.sub(self, start, string.len(self))) nextc = nil end until nextc == nil or start > #self return cols end -- container class container = {} container_mt = {} container_mt.__index = container function container:new(lname, config) local lcore local lnetcfg = {} local lstats = {} if lname then if config then lcore = core.container_new(lname, config) else lcore = core.container_new(lname) end end return setmetatable({ctname = lname, core = lcore, netcfg = lnetcfg, stats = lstats}, container_mt) end -- methods interfacing to core functionality function container:attach(what, ...) return self.core:attach(what, ...) end function container:config_file_name() return self.core:config_file_name() end function container:defined() return self.core:defined() end function container:init_pid() return self.core:init_pid() end function container:name() return self.core:name() end function container:start() return self.core:start() end function container:stop() return self.core:stop() end function container:shutdown(timeout) return self.core:shutdown(timeout) end function container:wait(state, timeout) return self.core:wait(state, timeout) end function container:freeze() return self.core:freeze() end function container:unfreeze() return self.core:unfreeze() end function container:running() return self.core:running() end function container:state() return self.core:state() end function container:create(template, ...) return self.core:create(template, ...) end function container:destroy() return self.core:destroy() end function container:get_config_path() return self.core:get_config_path() end function container:set_config_path(path) return self.core:set_config_path(path) end function container:append_config_item(key, value) return self.core:set_config_item(key, value) end function container:clear_config_item(key) return self.core:clear_config_item(key) end function container:get_cgroup_item(key) return self.core:get_cgroup_item(key) end function container:get_config_item(key) local value local vals = {} value = self.core:get_config_item(key) -- check if it is a single item if (not value or not string.find(value, "\n")) then return value end -- it must be a list type item, make a table of it vals = value:split("\n", 1000) -- make it a "mixed" table, ie both dictionary and list for ease of use for _,v in ipairs(vals) do vals[v] = true end return vals end function container:set_cgroup_item(key, value) return self.core:set_cgroup_item(key, value) end function container:set_config_item(key, value) return self.core:set_config_item(key, value) end function container:get_keys(base) local ktab = {} local keys if (base) then keys = self.core:get_keys(base) base = base .. "." else keys = self.core:get_keys() base = "" end if (keys == nil) then return nil end keys = keys:split("\n", 1000) for _,v in ipairs(keys) do local config_item = base .. v ktab[v] = self.core:get_config_item(config_item) end return ktab end function container:load_config(alt_path) if (alt_path) then return self.core:load_config(alt_path) else return self.core:load_config() end end function container:save_config(alt_path) if (alt_path) then return self.core:save_config(alt_path) else return self.core:save_config() end end -- methods for stats collection from various cgroup files -- read integers at given coordinates from a cgroup file function container:stat_get_ints(item, coords) local lines = {} local result = {} local flines = self:get_cgroup_item(item) if (flines == nil) then for k,c in ipairs(coords) do table.insert(result, 0) end else for line in flines:gmatch("[^\r\n]+") do table.insert(lines, line) end for k,c in ipairs(coords) do local col col = lines[c[1]]:split(" ", 80) local val = tonumber(col[c[2]]) table.insert(result, val) end end return table.unpack(result) end -- read an integer from a cgroup file function container:stat_get_int(item) local line = self:get_cgroup_item(item) -- if line is nil (on an error like Operation not supported because -- CONFIG_MEMCG_SWAP_ENABLED isn't enabled) return 0 return tonumber(line) or 0 end function container:stat_match_get_int(item, match, column) local val local lines = self:get_cgroup_item(item) if (lines == nil) then return 0 end for line in lines:gmatch("[^\r\n]+") do if (string.find(line, match)) then local col col = line:split(" ", 80) val = tonumber(col[column]) or 0 end end return val end function container:stats_get(total) local stat = {} stat.mem_used = self:stat_get_int("memory.usage_in_bytes") stat.mem_limit = self:stat_get_int("memory.limit_in_bytes") stat.memsw_used = self:stat_get_int("memory.memsw.usage_in_bytes") stat.memsw_limit = self:stat_get_int("memory.memsw.limit_in_bytes") stat.kmem_used = self:stat_get_int("memory.kmem.usage_in_bytes") stat.kmem_limit = self:stat_get_int("memory.kmem.limit_in_bytes") stat.cpu_use_nanos = self:stat_get_int("cpuacct.usage") stat.cpu_use_user, stat.cpu_use_sys = self:stat_get_ints("cpuacct.stat", {{1, 2}, {2, 2}}) stat.blkio = self:stat_match_get_int("blkio.throttle.io_service_bytes", "Total", 2) if (total) then total.mem_used = total.mem_used + stat.mem_used total.mem_limit = total.mem_limit + stat.mem_limit total.memsw_used = total.memsw_used + stat.memsw_used total.memsw_limit = total.memsw_limit + stat.memsw_limit total.kmem_used = total.kmem_used + stat.kmem_used total.kmem_limit = total.kmem_limit + stat.kmem_limit total.cpu_use_nanos = total.cpu_use_nanos + stat.cpu_use_nanos total.cpu_use_user = total.cpu_use_user + stat.cpu_use_user total.cpu_use_sys = total.cpu_use_sys + stat.cpu_use_sys total.blkio = total.blkio + stat.blkio end return stat end local M = { container = container } function M.stats_clear(stat) stat.mem_used = 0 stat.mem_limit = 0 stat.memsw_used = 0 stat.memsw_limit = 0 stat.kmem_used = 0 stat.kmem_limit = 0 stat.cpu_use_nanos = 0 stat.cpu_use_user = 0 stat.cpu_use_sys = 0 stat.blkio = 0 end -- return configured containers found in LXC_PATH directory function M.containers_configured(names_only) local containers = {} for dir in lfs.dir(lxc_path) do if (dir ~= "." and dir ~= "..") then local cfgfile = lxc_path .. "/" .. dir .. "/config" local cfgattr = lfs.attributes(cfgfile) if (cfgattr and cfgattr.mode == "file") then if (names_only) then -- note, this is a "mixed" table, ie both dictionary and list containers[dir] = true table.insert(containers, dir) else local ct = container:new(dir) -- note, this is a "mixed" table, ie both dictionary and list containers[dir] = ct table.insert(containers, dir) end end end end table.sort(containers, function (a,b) return (a < b) end) return containers end -- return running containers found in cgroup fs function M.containers_running(names_only) local containers = {} local names = M.containers_configured(true) for _,name in ipairs(names) do local ct = container:new(name) if ct:running() then -- note, this is a "mixed" table, ie both dictionary and list table.insert(containers, name) if (names_only) then containers[name] = true ct = nil else containers[name] = ct end end end table.sort(containers, function (a,b) return (a < b) end) return containers end function M.version_get() return core.version_get() end function M.default_config_path_get() return core.default_config_path_get() end function M.cmd_get_config_item(name, item, lxcpath) if (lxcpath) then return core.cmd_get_config_item(name, item, lxcpath) else return core.cmd_get_config_item(name, item) end end lxc_path = core.default_config_path_get() return M
lgpl-2.1
topameng/tolua_runtime
luajit-2.1/src/host/genminilua.lua
47
12039
---------------------------------------------------------------------------- -- Lua script to generate a customized, minified version of Lua. -- The resulting 'minilua' is used for the build process of LuaJIT. ---------------------------------------------------------------------------- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- local sub, match, gsub = string.sub, string.match, string.gsub local LUA_VERSION = "5.1.5" local LUA_SOURCE local function usage() io.stderr:write("Usage: ", arg and arg[0] or "genminilua", " lua-", LUA_VERSION, "-source-dir\n") os.exit(1) end local function find_sources() LUA_SOURCE = arg and arg[1] if not LUA_SOURCE then usage() end if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end local fp = io.open(LUA_SOURCE .. "lua.h") if not fp then LUA_SOURCE = LUA_SOURCE.."src/" fp = io.open(LUA_SOURCE .. "lua.h") if not fp then usage() end end local all = fp:read("*a") fp:close() if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then io.stderr:write("Error: version mismatch\n") usage() end end local LUA_FILES = { "lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c", "lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c", "llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c", "lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c", } local REMOVE_LIB = {} gsub([[ collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset select tostring xpcall foreach foreachi getn maxn setn popen tmpfile seek setvbuf __tostring clock date difftime execute getenv rename setlocale time tmpname dump gfind len reverse LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME ]], "%S+", function(name) REMOVE_LIB[name] = true end) local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, } local CUSTOM_MAIN = [[ typedef unsigned int UB; static UB barg(lua_State *L,int idx){ union{lua_Number n;U64 b;}bn; bn.n=lua_tonumber(L,idx)+6755399441055744.0; if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number"); return(UB)bn.b; } #define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1; static int tobit(lua_State *L){ BRET(barg(L,1))} static int bnot(lua_State *L){ BRET(~barg(L,1))} static int band(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)} static int bor(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)} static int bxor(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)} static int lshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)} static int rshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)} static int arshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)} static int rol(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))} static int ror(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))} static int bswap(lua_State *L){ UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)} static int tohex(lua_State *L){ UB b=barg(L,1); int n=lua_isnone(L,2)?8:(int)barg(L,2); const char *hexdigits="0123456789abcdef"; char buf[8]; int i; if(n<0){n=-n;hexdigits="0123456789ABCDEF";} if(n>8)n=8; for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;} lua_pushlstring(L,buf,(size_t)n); return 1; } static const struct luaL_Reg bitlib[] = { {"tobit",tobit}, {"bnot",bnot}, {"band",band}, {"bor",bor}, {"bxor",bxor}, {"lshift",lshift}, {"rshift",rshift}, {"arshift",arshift}, {"rol",rol}, {"ror",ror}, {"bswap",bswap}, {"tohex",tohex}, {NULL,NULL} }; int main(int argc, char **argv){ lua_State *L = luaL_newstate(); int i; luaL_openlibs(L); luaL_register(L, "bit", bitlib); if (argc < 2) return sizeof(void *); lua_createtable(L, 0, 1); lua_pushstring(L, argv[1]); lua_rawseti(L, -2, 0); lua_setglobal(L, "arg"); if (luaL_loadfile(L, argv[1])) goto err; for (i = 2; i < argc; i++) lua_pushstring(L, argv[i]); if (lua_pcall(L, argc - 2, 0, 0)) { err: fprintf(stderr, "Error: %s\n", lua_tostring(L, -1)); return 1; } lua_close(L); return 0; } ]] local function read_sources() local t = {} for i, name in ipairs(LUA_FILES) do local fp = assert(io.open(LUA_SOURCE..name, "r")) t[i] = fp:read("*a") assert(fp:close()) end t[#t+1] = CUSTOM_MAIN return table.concat(t) end local includes = {} local function merge_includes(src) return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name) if includes[name] then return "" end includes[name] = true local fp = assert(io.open(LUA_SOURCE..name, "r")) local inc = fp:read("*a") assert(fp:close()) inc = gsub(inc, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "") inc = gsub(inc, "#endif%s*$", "") return merge_includes(inc) end) end local function get_license(src) return match(src, "/%*+\n%* Copyright %(.-%*/\n") end local function fold_lines(src) return gsub(src, "\\\n", " ") end local strings = {} local function save_str(str) local n = #strings+1 strings[n] = str return "\1"..n.."\2" end local function save_strings(src) src = gsub(src, '"[^"\n]*"', save_str) return gsub(src, "'[^'\n]*'", save_str) end local function restore_strings(src) return gsub(src, "\1(%d+)\2", function(numstr) return strings[tonumber(numstr)] end) end local function def_istrue(def) return def == "INT_MAX > 2147483640L" or def == "LUAI_BITSINT >= 32" or def == "SIZE_Bx < LUAI_BITSINT-1" or def == "cast" or def == "defined(LUA_CORE)" or def == "MINSTRTABSIZE" or def == "LUA_MINBUFFER" or def == "HARDSTACKTESTS" or def == "UNUSED" end local head, defs = {[[ #ifdef _MSC_VER typedef unsigned __int64 U64; #else typedef unsigned long long U64; #endif int _CRT_glob = 0; ]]}, {} local function preprocess(src) local t = { match(src, "^(.-)#") } local lvl, on, oldon = 0, true, {} for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do if pp == "if" or pp == "ifdef" or pp == "ifndef" then lvl = lvl + 1 oldon[lvl] = on on = def_istrue(def) elseif pp == "else" then if oldon[lvl] then if on == false then on = true else on = false end end elseif pp == "elif" then if oldon[lvl] then on = def_istrue(def) end elseif pp == "endif" then on = oldon[lvl] lvl = lvl - 1 elseif on then if pp == "include" then if not head[def] and not REMOVE_EXTINC[def] then head[def] = true head[#head+1] = "#include "..def.."\n" end elseif pp == "define" then local k, sp, v = match(def, "([%w_]+)(%s*)(.*)") if k and not (sp == "" and sub(v, 1, 1) == "(") then defs[k] = gsub(v, "%a[%w_]*", function(tok) return defs[tok] or tok end) else t[#t+1] = "#define "..def.."\n" end elseif pp ~= "undef" then error("unexpected directive: "..pp.." "..def) end end if on then t[#t+1] = txt end end return gsub(table.concat(t), "%a[%w_]*", function(tok) return defs[tok] or tok end) end local function merge_header(src, license) local hdr = string.format([[ /* This is a heavily customized and minimized copy of Lua %s. */ /* It's only used to build LuaJIT. It does NOT have all standard functions! */ ]], LUA_VERSION) return hdr..license..table.concat(head)..src end local function strip_unused1(src) return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func) return REMOVE_LIB[func] and "" or line end) end local function strip_unused2(src) return gsub(src, "Symbolic Execution.-}=", "") end local function strip_unused3(src) src = gsub(src, "extern", "static") src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(") src = gsub(src, "#define lua_assert[^\n]*\n", "") src = gsub(src, "lua_assert%b();?", "") src = gsub(src, "default:\n}", "default:;\n}") src = gsub(src, "lua_lock%b();", "") src = gsub(src, "lua_unlock%b();", "") src = gsub(src, "luai_threadyield%b();", "") src = gsub(src, "luai_userstateopen%b();", "{}") src = gsub(src, "luai_userstate%w+%b();", "") src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser") src = gsub(src, "trydecpoint%(ls,seminfo%)", "luaX_lexerror(ls,\"malformed number\",TK_NUMBER)") src = gsub(src, "int c=luaZ_lookahead%b();", "") src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;", "return 1;") src = gsub(src, "getfuncname%b():", "NULL:") src = gsub(src, "getobjname%b():", "NULL:") src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "") src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "") src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "") src = gsub(src, "(twoto%b()%()", "%1(size_t)") src = gsub(src, "i<sizenode", "i<(int)sizenode") src = gsub(src, "cast%(unsigned int,key%-1%)", "cast(unsigned int,key)-1") return gsub(src, "\n\n+", "\n") end local function strip_comments(src) return gsub(src, "/%*.-%*/", " ") end local function strip_whitespace(src) src = gsub(src, "^%s+", "") src = gsub(src, "%s*\n%s*", "\n") src = gsub(src, "[ \t]+", " ") src = gsub(src, "(%W) ", "%1") return gsub(src, " (%W)", "%1") end local function rename_tokens1(src) src = gsub(src, "getline", "getline_") src = gsub(src, "struct ([%w_]+)", "ZX%1") return gsub(src, "union ([%w_]+)", "ZY%1") end local function rename_tokens2(src) src = gsub(src, "ZX([%w_]+)", "struct %1") return gsub(src, "ZY([%w_]+)", "union %1") end local function func_gather(src) local nodes, list = {}, {} local pos, len = 1, #src while pos < len do local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos) if d then local n = #list+1 list[n] = d nodes[w] = n else local s d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos) if not d then d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos) if not d then d = match(src, "^[^\n]*\n", pos) end end if s == "{" then d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3) if sub(d, -2) == "{\n" then d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3) end end local k, v = nil, d if w == "typedef" then if match(d, "^typedef enum") then head[#head+1] = d else k = match(d, "([%w_]+);\n$") if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end end elseif w == "enum" then head[#head+1] = v elseif w ~= nil then k = match(d, "^[^\n]-([%w_]+)[(%[=]") if k then if w ~= "static" and k ~= "main" then v = "static "..d end else k = w end end if w and k then local o = nodes[k] if o then nodes["*"..k] = o end local n = #list+1 list[n] = v nodes[k] = n end end pos = pos + #d end return nodes, list end local function func_visit(nodes, list, used, n) local i = nodes[n] for m in string.gmatch(list[i], "[%w_]+") do if nodes[m] then local j = used[m] if not j then used[m] = i func_visit(nodes, list, used, m) elseif i < j then used[m] = i end end end end local function func_collect(src) local nodes, list = func_gather(src) local used = {} func_visit(nodes, list, used, "main") for n,i in pairs(nodes) do local j = used[n] if j and j < i then used["*"..n] = j end end for n,i in pairs(nodes) do if not used[n] then list[i] = "" end end return table.concat(list) end find_sources() local src = read_sources() src = merge_includes(src) local license = get_license(src) src = fold_lines(src) src = strip_unused1(src) src = save_strings(src) src = strip_unused2(src) src = strip_comments(src) src = preprocess(src) src = strip_whitespace(src) src = strip_unused3(src) src = rename_tokens1(src) src = func_collect(src) src = rename_tokens2(src) src = restore_strings(src) src = merge_header(src, license) io.write(src)
mit
inTact700/VLCHotkey
share/lua/playlist/mpora.lua
97
2565
--[[ $Id$ Copyright © 2009 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.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. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "video%.mpora%.com/watch/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.*)\" />" ) end if string.match( line, "image_src" ) then _,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" ) end if string.match( line, "video_src" ) then _,_,video = string.find( line, 'href="http://video%.mpora%.com/ep/(.*)%.swf" />' ) end end if not name or not arturl or not video then return nil end -- Try and get URL for SD video. sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/") if not sd then return nil end page = sd:read( 65653 ) sdurl = string.match( page, "url=\"(.*)\" />") page = nil table.insert( p, { path = sdurl; name = name; arturl = arturl; } ) -- Try and check if HD video is available. checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" ) if not checkhd then return nil end page = checkhd:read( 65653 ) hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) ) page = nil if hashd then hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/") page = hd:read( 65653 ) hdurl = string.match( page, "url=\"(.*)\" />") table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl; } ) end return p end
gpl-2.0
Capibara-/cardpeek
dot_cardpeek_dir/scripts/vitale_2.lua
17
5057
-- -- 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 The French health card (Version 2) -- @targets 0.8 require('lib.tlv') function ui_parse_asciidate(node,data) local d = bytes.format(data,"%P") local t = os.time( { ['year'] = string.sub(d,1,4), ['month'] = string.sub(d,5,6), ['day'] = string.sub(d,7,8) } ) nodes.set_attribute(node,"val",data) nodes.set_attribute(node,"alt",os.date("%x",t)) return true end VITALE_IDO = { ['65'] = { "Bénéficiaire" }, ['65/90'] = { "Nationalité", ui_parse_printable }, ['65/93'] = { "Numéro de sécurité sociale", ui_parse_printable }, ['65/80'] = { "Nom", ui_parse_printable }, ['65/81'] = { "Prénom", ui_parse_printable }, ['65/82'] = { "Date de naissance", ui_parse_asciidate }, ['66'] = { "Carte vitale" }, ['66/80'] = { "Date de début de validité", ui_parse_asciidate }, ['7F21'] = { "Certificat" }, ['5F37'] = { "Signature de l'AC" }, ['5F38'] = { "Résidu de la clé publique" }, } function read_bin() local total, sw, resp, r total = bytes.new(8) r = 0 repeat sw, resp = card.read_binary(".",r) total = bytes.concat(total,resp) r = r + 256 until #resp~=256 or sw~=0x9000 if #total>0 then return 0x9000, total end return sw, total end AID_VITALE = "#D250000002564954414C45" AID_VITALE_MF = "#D2500000024D465F564954414C45" function create_card_map() local resp, sw local map = {} local tag,val,rest local tag2,val2,rest2 local entry, aid, file, name sw,resp = card.select(AID_VITALE) if sw~=0x9000 then return nil end sw,resp = card.select(".2001") if sw~=0x9000 then return nil end sw,resp = read_bin() if sw~=0x9000 then return nil end tag,val = asn1.split(resp) -- E0,DATA,nil tag,rest2,rest = asn1.split(val) -- A0,DATA,DATA repeat tag2,val2,rest2 = asn1.split(rest2) if tag2==0x82 then entry = tostring(bytes.sub(val2,0,1)) aid = "#"..tostring(bytes.sub(val2,4,-1)) map[entry]={ ['aid'] = aid, ['files'] = {} } end until rest2==nil or tag==0 repeat tag,val,rest = asn1.split(rest) if tag==0x80 then entry = tostring(bytes.sub(val,8,9)) file = "."..tostring(bytes.sub(val,10,11)) name = bytes.format(bytes.sub(val,0,7),"%P") table.insert(map[entry]['files'],{ ['name']=name, ['ef']=file }) end until rest==nil or tag==0 for entry in pairs(map) do if map[entry]['aid']==AID_VITALE_MF then table.insert(map[entry]['files'],{ ['name']="DIR", ['ef']=".2F00" }) table.insert(map[entry]['files'],{ ['name']="PAN", ['ef']=".2F02" }) elseif map[entry]['aid']==AID_VITALE then table.insert(map[entry]['files'],{ ['name']="POINTERS", ['ef']=".2001" }) end end return map end --[[ AID = { "D2500000024D465F564954414C45", "E828BD080FD2500000044164E86C65", "D2500000044164E86C650101" } --]] local header if card.connect() then CARD = card.tree_startup("VITALE 2") map = create_card_map() if map then for app in pairs(map) do sw,resp = card.select(map[app]['aid']) if sw==0x9000 then APP = CARD:append({ classname="application", label="Application", id=map[app]['aid'] }) header = APP:append({ classname="header", label="answer to select", size=#resp }) tlv_parse(header,resp) end for i in pairs(map[app]['files']) do EF = APP:append({ classname="file", label=map[app]['files'][i]['name'], id=map[app]['files'][i]['ef'] }) sw,resp = card.select(map[app]['files'][i]['ef']) header = EF:append({ classname="header", label="answer to select", size=#resp }) tlv_parse(header,resp) if sw==0x9000 then sw,resp = read_bin() CONTENT = EF:append({ classname="body", label="content", size=#resp }) if sw==0x9000 then if resp:get(0)==0 or (resp:get(0)==0x04 and resp:get(1)==0x00) then nodes.set_attribute(CONTENT,"val",resp) else tlv_parse(CONTENT,resp,VITALE_IDO) end else nodes.set_attribute(CONTENT,"alt",string.format("data not accessible (code %04X)",sw)) end end end end end card.disconnect() else ui.question("No card detected",{"OK"}) end
gpl-3.0
liruqi/bigfoot
Interface/AddOns/MasterPlan/C_Garrison_cache.lua
1
1729
if IsAddOnLoaded('GarrisonMissionManager') then return; end --bf@178.com local addon_name, addon_env = ... -- [AUTOLOCAL START] local C_Garrison = C_Garrison local LE_FOLLOWER_TYPE_GARRISON_6_0 = LE_FOLLOWER_TYPE_GARRISON_6_0 local LE_GARRISON_TYPE_6_0 = LE_GARRISON_TYPE_6_0 local wipe = wipe -- [AUTOLOCAL END] local getters = {} local cache = setmetatable({}, { __index = function(t, key) local result = getters[key]() t[key] = result return result end}) addon_env.c_garrison_cache = cache local GetBuildings = C_Garrison.GetBuildings getters.GetBuildings = function() return GetBuildings(LE_GARRISON_TYPE_6_0) end local salvage_yard_level_building_id = { [52] = 1, [140] = 2, [141] = 3 } getters.salvage_yard_level = function() local buildings = cache.GetBuildings for idx = 1, #buildings do local buildingID = buildings[idx].buildingID local possible_salvage_yard_level = salvage_yard_level_building_id[buildingID] if possible_salvage_yard_level then return possible_salvage_yard_level end end return false end local GetPossibleFollowersForBuilding = C_Garrison.GetPossibleFollowersForBuilding local cache_GetPossibleFollowersForBuilding = setmetatable({}, { __index = function(t, key) local result = GetPossibleFollowersForBuilding(LE_FOLLOWER_TYPE_GARRISON_6_0, key) t[key] = result return result end}) getters.GetPossibleFollowersForBuilding = function() wipe(cache_GetPossibleFollowersForBuilding) return cache_GetPossibleFollowersForBuilding end -- wipe removes all entries, but leaves MT alone, as this test shows -- WIPE_META_TEST = setmetatable({}, { __index = function(t, key) return "test" end})
mit
MocoNinja/LinuxConfs
Archlabs/.config/awesome/vicious/widgets/mboxc.lua
14
1841
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Adrian C. <anrxc@sysphere.org> --------------------------------------------------- -- {{{ Grab environment local io = { open = io.open } local setmetatable = setmetatable local string = { find = string.find } -- }}} -- Mboxc: provides the count of total, old and new messages in mbox files -- vicious.widgets.mboxc local mboxc = {} -- {{{ Mbox count widget type local function worker(format, warg) if not warg then return end -- Initialize counters local count = { old = 0, total = 0, new = 0 } -- Get data from mbox files for i=1, #warg do local f = io.open(warg[i]) while true do -- Read the mbox line by line, if we are going to read -- some *HUGE* folders then switch to reading chunks local lines = f:read("*line") if not lines then break end -- Find all messages -- * http://www.jwz.org/doc/content-length.html local _, from = string.find(lines, "^From[%s]") if from ~= nil then count.total = count.total + 1 end -- Read messages have the Status header local _, status = string.find(lines, "^Status:[%s]RO$") if status ~= nil then count.old = count.old + 1 end -- Skip the folder internal data local _, int = string.find(lines, "^Subject:[%s].*FOLDER[%s]INTERNAL[%s]DATA") if int ~= nil then count.total = count.total - 1 end end f:close() end -- Substract total from old to get the new count count.new = count.total - count.old return {count.total, count.old, count.new} end -- }}} return setmetatable(mboxc, { __call = function(_, ...) return worker(...) end })
gpl-3.0
shiprabehera/kong
kong/dao/migrations/cassandra.lua
3
12988
return { { name = "2015-01-12-175310_skeleton", up = function(db, kong_config) local keyspace_name = kong_config.cassandra_keyspace local strategy, strategy_properties = kong_config.cassandra_repl_strategy, "" -- Format strategy options if strategy == "SimpleStrategy" then strategy_properties = string.format(", 'replication_factor': %s", kong_config.cassandra_repl_factor) elseif strategy == "NetworkTopologyStrategy" then local dcs = {} for _, dc_conf in ipairs(kong_config.cassandra_data_centers) do local dc_name, dc_repl = string.match(dc_conf, "([^:]+):(%d+)") if dc_name and dc_repl then table.insert(dcs, string.format("'%s': %s", dc_name, dc_repl)) else return "invalid cassandra_data_centers configuration" end end if #dcs > 0 then strategy_properties = string.format(", %s", table.concat(dcs, ", ")) end else -- Strategy unknown return "invalid replication_strategy class" end -- Format final keyspace creation query local keyspace_str = string.format([[ CREATE KEYSPACE IF NOT EXISTS "%s" WITH REPLICATION = {'class': '%s'%s}; ]], keyspace_name, strategy, strategy_properties) local res, err = db:query(keyspace_str, nil, nil, nil, true) if not res then return err end local ok, err = db:coordinator_change_keyspace(keyspace_name) if not ok then return err end local res, err = db:query [[ CREATE TABLE IF NOT EXISTS schema_migrations( id text PRIMARY KEY, migrations list<text> ); ]] if not res then return err end end, down = [[ DROP TABLE schema_migrations; ]] }, { name = "2015-01-12-175310_init_schema", up = [[ CREATE TABLE IF NOT EXISTS consumers( id uuid, custom_id text, username text, created_at timestamp, PRIMARY KEY (id) ); CREATE INDEX IF NOT EXISTS ON consumers(custom_id); CREATE INDEX IF NOT EXISTS ON consumers(username); CREATE TABLE IF NOT EXISTS apis( id uuid, name text, request_host text, request_path text, strip_request_path boolean, upstream_url text, preserve_host boolean, created_at timestamp, PRIMARY KEY (id) ); CREATE INDEX IF NOT EXISTS ON apis(name); CREATE INDEX IF NOT EXISTS ON apis(request_host); CREATE INDEX IF NOT EXISTS ON apis(request_path); CREATE TABLE IF NOT EXISTS plugins( id uuid, api_id uuid, consumer_id uuid, name text, config text, -- serialized plugin configuration enabled boolean, created_at timestamp, PRIMARY KEY (id, name) ); CREATE INDEX IF NOT EXISTS ON plugins(name); CREATE INDEX IF NOT EXISTS ON plugins(api_id); CREATE INDEX IF NOT EXISTS ON plugins(consumer_id); ]], down = [[ DROP TABLE consumers; DROP TABLE apis; DROP TABLE plugins; ]] }, { name = "2015-11-23-817313_nodes", up = [[ CREATE TABLE IF NOT EXISTS nodes( name text, cluster_listening_address text, created_at timestamp, PRIMARY KEY (name) ) WITH default_time_to_live = 3600; CREATE INDEX IF NOT EXISTS ON nodes(cluster_listening_address); ]], down = [[ DROP TABLE nodes; ]] }, { name = "2016-02-25-160900_remove_null_consumer_id", up = function(_, _, dao) local rows, err = dao.plugins:find_all {consumer_id = "00000000-0000-0000-0000-000000000000"} if err then return err end for _, row in ipairs(rows) do row.consumer_id = nil local _, err = dao.plugins:update(row, row, {full = true}) if err then return err end end end }, { name = "2016-02-29-121813_remove_ttls", up = [[ ALTER TABLE nodes WITH default_time_to_live = 0; ]], down = [[ ALTER TABLE nodes WITH default_time_to_live = 3600; ]] }, { -- This is a 2 step migration; first create the extra column, using a cql -- statement and following iterate over the entries to insert default values. -- Step 1) create extra column name = "2016-09-05-212515_retries_step_1", up = [[ ALTER TABLE apis ADD retries int; ]], down = [[ ALTER TABLE apis DROP retries; ]] }, { -- Step 2) insert default values name = "2016-09-05-212515_retries_step_2", up = function(_, _, dao) local rows, err = dao.apis:find_all() -- fetch all rows if err then return err end for _, row in ipairs(rows) do if not row.retries then local _, err = dao.apis:update({ retries = 5 }, { id = row.id }) if err then return err end end end end, down = nil, }, { name = "2016-09-16-141423_upstreams", -- Note on the timestamps; -- The Cassandra timestamps are created in Lua code, and hence ALL entities -- will now be created in millisecond precision. The existing entries will -- remain in second precision, but new ones (for ALL entities!) will be -- in millisecond precision. -- This differs from the Postgres one where only the new entities (upstreams -- and targets) will get millisecond precision. up = [[ CREATE TABLE IF NOT EXISTS upstreams( id uuid, name text, slots int, orderlist text, created_at timestamp, PRIMARY KEY (id) ); CREATE INDEX IF NOT EXISTS ON upstreams(name); CREATE TABLE IF NOT EXISTS targets( id uuid, target text, weight int, upstream_id uuid, created_at timestamp, PRIMARY KEY (id) ); CREATE INDEX IF NOT EXISTS ON targets(upstream_id); ]], down = [[ DROP TABLE upstreams; DROP TABLE targets; ]], }, { name = "2016-12-14-172100_move_ssl_certs_to_core", up = [[ CREATE TABLE ssl_certificates( id uuid PRIMARY KEY, cert text, key text , created_at timestamp ); CREATE TABLE ssl_servers_names( name text, ssl_certificate_id uuid, created_at timestamp, PRIMARY KEY (name, ssl_certificate_id) ); CREATE INDEX IF NOT EXISTS ON ssl_servers_names(ssl_certificate_id); ALTER TABLE apis ADD https_only boolean; ALTER TABLE apis ADD http_if_terminated boolean; ]], down = [[ DROP INDEX ssl_servers_names_ssl_certificate_idx; DROP TABLE ssl_certificates; DROP TABLE ssl_servers_names; ALTER TABLE apis DROP https_only; ALTER TABLE apis DROP http_if_terminated; ]] }, { name = "2016-11-11-151900_new_apis_router_1", up = [[ ALTER TABLE apis ADD hosts text; ALTER TABLE apis ADD uris text; ALTER TABLE apis ADD methods text; ALTER TABLE apis ADD strip_uri boolean; ]], down = [[ ALTER TABLE apis DROP headers; ALTER TABLE apis DROP uris; ALTER TABLE apis DROP methods; ALTER TABLE apis DROP strip_uri; ]] }, { name = "2016-11-11-151900_new_apis_router_2", up = function(_, _, dao) -- create request_headers and request_uris -- with one entry each: the current request_host -- and the current request_path local rows, err = dao.apis:find_all() -- fetch all rows if err then return err end for _, row in ipairs(rows) do local hosts local uris local upstream_url = row.upstream_url while string.sub(upstream_url, #upstream_url) == "/" do upstream_url = string.sub(upstream_url, 1, #upstream_url - 1) end if row.request_host then hosts = { row.request_host } end if row.request_path then uris = { row.request_path } end local _, err = dao.apis:update({ hosts = hosts, uris = uris, strip_uri = row.strip_request_path, upstream_url = upstream_url, }, { id = row.id }) if err then return err end end end, down = function(_, _, dao) -- re insert request_host and request_path from -- the first element of request_headers and -- request_uris end }, { name = "2016-11-11-151900_new_apis_router_3", up = function(db, kong_config) local keyspace_name = kong_config.cassandra_keyspace if db.release_version < 3 then local rows, err = db:query([[ SELECT * FROM system.schema_columns WHERE keyspace_name = ']] .. keyspace_name .. [[' AND columnfamily_name = 'apis' AND column_name IN ('request_host', 'request_path') ]]) if err then return err end for i = 1, #rows do if rows[i].index_name then local res, err = db:query("DROP INDEX " .. rows[i].index_name) if not res then return err end end end else local rows, err = db:query([[ SELECT * FROM system_schema.indexes WHERE keyspace_name = ']] .. keyspace_name .. [[' AND table_name = 'apis' ]]) if err then return err end for i = 1, #rows do if rows[i].options and rows[i].options.target == "request_host" or rows[i].options.target == "request_path" then local res, err = db:query("DROP INDEX " .. rows[i].index_name) if not res then return err end end end end local err = db:queries [[ ALTER TABLE apis DROP request_host; ALTER TABLE apis DROP request_path; ALTER TABLE apis DROP strip_request_path; ]] if err then return err end end, down = [[ ALTER TABLE apis ADD request_host text; ALTER TABLE apis ADD request_path text; ALTER TABLE apis ADD strip_request_path boolean; CREATE INDEX IF NOT EXISTS ON apis(request_host); CREATE INDEX IF NOT EXISTS ON apis(request_path); ]] }, { name = "2017-01-24-132600_upstream_timeouts", up = [[ ALTER TABLE apis ADD upstream_connect_timeout int; ALTER TABLE apis ADD upstream_send_timeout int; ALTER TABLE apis ADD upstream_read_timeout int; ]], down = [[ ALTER TABLE apis DROP upstream_connect_timeout; ALTER TABLE apis DROP upstream_send_timeout; ALTER TABLE apis DROP upstream_read_timeout; ]] }, { name = "2017-01-24-132600_upstream_timeouts_2", up = function(_, _, dao) local rows, err = dao.db:query([[ SELECT * FROM apis; ]]) if err then return err end for _, row in ipairs(rows) do if not row.upstream_connect_timeout or not row.upstream_read_timeout or not row.upstream_send_timeout then local _, err = dao.apis:update({ upstream_connect_timeout = 60000, upstream_send_timeout = 60000, upstream_read_timeout = 60000, }, { id = row.id }) if err then return err end end end end, down = function(_, _, dao) end }, { name = "2017-03-27-132300_anonymous", -- this should have been in 0.10, but instead goes into 0.10.1 as a bugfix up = function(_, _, dao) for _, name in ipairs({ "basic-auth", "hmac-auth", "jwt", "key-auth", "ldap-auth", "oauth2", }) do local rows, err = dao.plugins:find_all( { name = name } ) if err then return err end for _, row in ipairs(rows) do if not row.config.anonymous then row.config.anonymous = "" local _, err = dao.plugins:update(row, { id = row.id }) if err then return err end end end end end, down = function(_, _, dao) end }, { name = "2017-04-04-145100_cluster_events", up = [[ CREATE TABLE IF NOT EXISTS cluster_events( channel text, at timestamp, node_id uuid, data text, id uuid, nbf timestamp, PRIMARY KEY ((channel), at, node_id, id) ) WITH default_time_to_live = 86400 AND comment = 'Kong cluster events broadcasting and polling'; ]], }, { name = "2017-05-19-173100_remove_nodes_table", up = [[ DROP TABLE nodes; ]], }, }
apache-2.0
liruqi/bigfoot
Interface/AddOns/DBM-Party-WoD/BloodmaulSlagMines/Crushto.lua
1
2262
local mod = DBM:NewMod(888, "DBM-Party-WoD", 2, 385) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 15007 $"):sub(12, -3)) mod:SetCreatureID(74787) mod:SetEncounterID(1653) mod:SetZone() mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_AURA_APPLIED 150751", "SPELL_CAST_START 150759 150801 153679 150753" ) local warnFerociousYell = mod:NewCastAnnounce(150759, 2) local warnCrushingLeap = mod:NewTargetAnnounce(150751, 3) local warnEarthCrush = mod:NewSpellAnnounce(153679, 4)--Target scanning unavailable. local specWarnFerociousYell = mod:NewSpecialWarningInterrupt(150759, "HasInterrupt", nil, 2, 1, 2) local specWarnRaiseMiners = mod:NewSpecialWarningSwitch(150801, "Tank", nil, nil, 1, 2) local specWarnCrushingLeap = mod:NewSpecialWarningTarget(150751, false)--seems useless. local specWarnEarthCrush = mod:NewSpecialWarningSpell(153679, nil, nil, nil, 3)--avoidable. local specWarnWildSlam = mod:NewSpecialWarningSpell(150753, nil, nil, nil, 2)--not avoidable. large aoe damage and knockback --local timerFerociousYellCD--12~18. large variable? --local timerRaiseMinersCD--14~26. large variable. useless. local timerCrushingLeapCD = mod:NewCDTimer(23, 150751, nil, nil, nil, 3)--23~25 variable. --local timerEarthCrushCD--13~21. large variable. useless. local timerWildSlamCD = mod:NewCDTimer(23, 150753, nil, nil, nil, 2)--23~24 variable. local voiceFerociousYell = mod:NewVoice(150759, "HasInterrupt") local voiceRaiseMiners = mod:NewVoice(150801) function mod:SPELL_AURA_APPLIED(args) if args.spellId == 150751 then warnCrushingLeap:Show(args.destName) specWarnCrushingLeap:Show(args.destName) timerCrushingLeapCD:Start() if self:IsTank() then voiceFerociousYell:Play("kickcast") else voiceFerociousYell:Play("helpkick") end end end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 150759 then warnFerociousYell:Show() specWarnFerociousYell:Show(args.sourceName) elseif spellId == 150801 then specWarnRaiseMiners:Show() voiceRaiseMiners:Play("mobsoon") elseif spellId == 153679 then warnEarthCrush:Show() specWarnEarthCrush:Show() elseif spellId == 150753 then specWarnWildSlam:Show() timerWildSlamCD:Start() end end
mit
shiprabehera/kong
spec/03-plugins/11-basic-auth/03-access_spec.lua
2
14628
local helpers = require "spec.helpers" local cjson = require "cjson" local meta = require "kong.meta" local utils = require "kong.tools.utils" describe("Plugin: basic-auth (access)", function() local client setup(function() helpers.run_migrations() local api1 = assert(helpers.dao.apis:insert { name = "api-1", hosts = { "basic-auth1.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "basic-auth", api_id = api1.id }) local api2 = assert(helpers.dao.apis:insert { name = "api-2", hosts = { "basic-auth2.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "basic-auth", api_id = api2.id, config = { hide_credentials = true } }) local consumer = assert(helpers.dao.consumers:insert { username = "bob" }) local anonymous_user = assert(helpers.dao.consumers:insert { username = "no-body" }) assert(helpers.dao.basicauth_credentials:insert { username = "bob", password = "kong", consumer_id = consumer.id }) assert(helpers.dao.basicauth_credentials:insert { username = "user123", password = "password123", consumer_id = consumer.id }) local api3 = assert(helpers.dao.apis:insert { name = "api-3", hosts = { "basic-auth3.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "basic-auth", api_id = api3.id, config = { anonymous = anonymous_user.id } }) local api4 = assert(helpers.dao.apis:insert { name = "api-4", hosts = { "basic-auth4.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "basic-auth", api_id = api4.id, config = { anonymous = utils.uuid() -- a non-existing consumer id } }) assert(helpers.start_kong()) client = helpers.proxy_client() end) teardown(function() if client then client:close() end helpers.stop_kong() end) describe("Unauthorized", function() it("returns Unauthorized on missing credentials", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "basic-auth1.com" } }) local body = assert.res_status(401, res) local json = cjson.decode(body) assert.same({ message = "Unauthorized" }, json) end) it("returns WWW-Authenticate header on missing credentials", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "basic-auth1.com" } }) assert.res_status(401, res) assert.equal('Basic realm="' .. meta._NAME .. '"', res.headers["WWW-Authenticate"]) end) end) describe("Forbidden", function() it("returns 403 Forbidden on invalid credentials in Authorization", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Authorization"] = "foobar", ["Host"] = "basic-auth1.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Invalid authentication credentials" }, json) end) it("returns 403 Forbidden on invalid credentials in Proxy-Authorization", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Proxy-Authorization"] = "foobar", ["Host"] = "basic-auth1.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Invalid authentication credentials" }, json) end) it("returns 403 Forbidden on password only", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Authorization"] = "Basic a29uZw==", ["Host"] = "basic-auth1.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Invalid authentication credentials" }, json) end) it("returns 403 Forbidden on username only", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Authorization"] = "Basic Ym9i", ["Host"] = "basic-auth1.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Invalid authentication credentials" }, json) end) it("authenticates valid credentials in Authorization", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth1.com" } }) assert.res_status(200, res) end) it("authenticates valid credentials in Authorization", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Authorization"] = "Basic dXNlcjEyMzpwYXNzd29yZDEyMw==", ["Host"] = "basic-auth1.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal('bob', body.headers["x-consumer-username"]) end) it("returns 403 for valid Base64 encoding", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Authorization"] = "Basic adXNlcjEyMzpwYXNzd29yZDEyMw==", ["Host"] = "basic-auth1.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Invalid authentication credentials" }, json) end) it("authenticates valid credentials in Proxy-Authorization", function() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Proxy-Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth1.com" } }) assert.res_status(200, res) end) end) describe("Consumer headers", function() it("sends Consumer headers to upstream", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth1.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.is_string(json.headers["x-consumer-id"]) assert.equal("bob", json.headers["x-consumer-username"]) end) end) describe("config.hide_credentials", function() it("false sends key to upstream", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth1.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("Basic Ym9iOmtvbmc=", json.headers.authorization) end) it("true doesn't send key to upstream", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth2.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.is_nil(json.headers.authorization) end) end) describe("config.anonymous", function() it("works with right credentials and anonymous", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Authorization"] = "Basic dXNlcjEyMzpwYXNzd29yZDEyMw==", ["Host"] = "basic-auth3.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal('bob', body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("works with wrong credentials and anonymous", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "basic-auth3.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal('true', body.headers["x-anonymous-consumer"]) assert.equal('no-body', body.headers["x-consumer-username"]) end) it("errors when anonymous user doesn't exist", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "basic-auth4.com" } }) assert.response(res).has.status(500) end) end) end) describe("Plugin: basic-auth (access)", function() local client, user1, user2, anonymous setup(function() local api1 = assert(helpers.dao.apis:insert { name = "api-1", hosts = { "logical-and.com" }, upstream_url = "http://mockbin.org/request" }) assert(helpers.dao.plugins:insert { name = "basic-auth", api_id = api1.id }) assert(helpers.dao.plugins:insert { name = "key-auth", api_id = api1.id }) anonymous = assert(helpers.dao.consumers:insert { username = "Anonymous" }) user1 = assert(helpers.dao.consumers:insert { username = "Mickey" }) user2 = assert(helpers.dao.consumers:insert { username = "Aladdin" }) local api2 = assert(helpers.dao.apis:insert { name = "api-2", hosts = { "logical-or.com" }, upstream_url = "http://mockbin.org/request" }) assert(helpers.dao.plugins:insert { name = "basic-auth", api_id = api2.id, config = { anonymous = anonymous.id } }) assert(helpers.dao.plugins:insert { name = "key-auth", api_id = api2.id, config = { anonymous = anonymous.id } }) assert(helpers.dao.keyauth_credentials:insert { key = "Mouse", consumer_id = user1.id }) assert(helpers.dao.basicauth_credentials:insert { username = "Aladdin", password = "OpenSesame", consumer_id = user2.id }) assert(helpers.start_kong()) client = helpers.proxy_client() end) teardown(function() if client then client:close() end helpers.stop_kong() end) describe("multiple auth without anonymous, logical AND", function() it("passes with all credentials provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["apikey"] = "Mouse", ["Authorization"] = "Basic QWxhZGRpbjpPcGVuU2VzYW1l", } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert(id == user1.id or id == user2.id) end) it("fails 401, with only the first credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["apikey"] = "Mouse", } }) assert.response(res).has.status(401) end) it("fails 401, with only the second credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["Authorization"] = "Basic QWxhZGRpbjpPcGVuU2VzYW1l", } }) assert.response(res).has.status(401) end) it("fails 401, with no credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", } }) assert.response(res).has.status(401) end) end) describe("multiple auth with anonymous, logical OR", function() it("passes with all credentials provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["apikey"] = "Mouse", ["Authorization"] = "Basic QWxhZGRpbjpPcGVuU2VzYW1l", } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert(id == user1.id or id == user2.id) end) it("passes with only the first credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["apikey"] = "Mouse", } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert.equal(user1.id, id) end) it("passes with only the second credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["Authorization"] = "Basic QWxhZGRpbjpPcGVuU2VzYW1l", } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert.equal(user2.id, id) end) it("passes with no credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", } }) assert.response(res).has.status(200) assert.request(res).has.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.equal(id, anonymous.id) end) end) end)
apache-2.0
Unknown8765/SpeedBot
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
goofanader/aijam-2015
libraries/hardoncollider/polygon.lua
14
13533
--[[ Copyright (c) 2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _PACKAGE, common_local = (...):match("^(.+)%.[^%.]+"), common if not (type(common) == 'table' and common.class and common.instance) then assert(common_class ~= false, 'No class commons specification available.') require(_PACKAGE .. '.class') common_local, common = common, common_local end local vector = require(_PACKAGE .. '.vector-light') ---------------------------- -- Private helper functions -- -- create vertex list of coordinate pairs local function toVertexList(vertices, x,y, ...) if not (x and y) then return vertices end -- no more arguments vertices[#vertices + 1] = {x = x, y = y} -- set vertex return toVertexList(vertices, ...) -- recurse end -- returns true if three vertices lie on a line local function areCollinear(p, q, r, eps) return math.abs(vector.det(q.x-p.x, q.y-p.y, r.x-p.x,r.y-p.y)) <= (eps or 1e-32) end -- remove vertices that lie on a line local function removeCollinear(vertices) local ret = {} local i,k = #vertices - 1, #vertices for l=1,#vertices do if not areCollinear(vertices[i], vertices[k], vertices[l]) then ret[#ret+1] = vertices[k] end i,k = k,l end return ret end -- get index of rightmost vertex (for testing orientation) local function getIndexOfleftmost(vertices) local idx = 1 for i = 2,#vertices do if vertices[i].x < vertices[idx].x then idx = i end end return idx end -- returns true if three points make a counter clockwise turn local function ccw(p, q, r) return vector.det(q.x-p.x, q.y-p.y, r.x-p.x, r.y-p.y) >= 0 end -- test wether a and b lie on the same side of the line c->d local function onSameSide(a,b, c,d) local px, py = d.x-c.x, d.y-c.y local l = vector.det(px,py, a.x-c.x, a.y-c.y) local m = vector.det(px,py, b.x-c.x, b.y-c.y) return l*m >= 0 end local function pointInTriangle(p, a,b,c) return onSameSide(p,a, b,c) and onSameSide(p,b, a,c) and onSameSide(p,c, a,b) end -- test whether any point in vertices (but pqr) lies in the triangle pqr -- note: vertices is *set*, not a list! local function anyPointInTriangle(vertices, p,q,r) for v in pairs(vertices) do if v ~= p and v ~= q and v ~= r and pointInTriangle(v, p,q,r) then return true end end return false end -- test is the triangle pqr is an "ear" of the polygon -- note: vertices is *set*, not a list! local function isEar(p,q,r, vertices) return ccw(p,q,r) and not anyPointInTriangle(vertices, p,q,r) end local function segmentsInterset(a,b, p,q) return not (onSameSide(a,b, p,q) or onSameSide(p,q, a,b)) end -- returns starting/ending indices of shared edge, i.e. if p and q share the -- edge with indices p1,p2 of p and q1,q2 of q, the return value is p1,q2 local function getSharedEdge(p,q) local pindex = setmetatable({}, {__index = function(t,k) local s = {} t[k] = s return s end}) -- record indices of vertices in p by their coordinates for i = 1,#p do pindex[p[i].x][p[i].y] = i end -- iterate over all edges in q. if both endpoints of that -- edge are in p as well, return the indices of the starting -- vertex local i,k = #q,1 for k = 1,#q do local v,w = q[i], q[k] if pindex[v.x][v.y] and pindex[w.x][w.y] then return pindex[w.x][w.y], k end i = k end end ----------------- -- Polygon class -- local Polygon = {} function Polygon:init(...) local vertices = removeCollinear( toVertexList({}, ...) ) assert(#vertices >= 3, "Need at least 3 non collinear points to build polygon (got "..#vertices..")") -- assert polygon is oriented counter clockwise local r = getIndexOfleftmost(vertices) local q = r > 1 and r - 1 or #vertices local s = r < #vertices and r + 1 or 1 if not ccw(vertices[q], vertices[r], vertices[s]) then -- reverse order if polygon is not ccw local tmp = {} for i=#vertices,1,-1 do tmp[#tmp + 1] = vertices[i] end vertices = tmp end -- assert polygon is not self-intersecting -- outer: only need to check segments #vert;1, 1;2, ..., #vert-3;#vert-2 -- inner: only need to check unconnected segments local q,p = vertices[#vertices] for i = 1,#vertices-2 do p, q = q, vertices[i] for k = i+1,#vertices-1 do local a,b = vertices[k], vertices[k+1] assert(not segmentsInterset(p,q, a,b), 'Polygon may not intersect itself') end end self.vertices = vertices -- make vertices immutable setmetatable(self.vertices, {__newindex = function() error("Thou shall not change a polygon's vertices!") end}) -- compute polygon area and centroid local p,q = vertices[#vertices], vertices[1] local det = vector.det(p.x,p.y, q.x,q.y) -- also used below self.area = det for i = 2,#vertices do p,q = q,vertices[i] self.area = self.area + vector.det(p.x,p.y, q.x,q.y) end self.area = self.area / 2 p,q = vertices[#vertices], vertices[1] self.centroid = {x = (p.x+q.x)*det, y = (p.y+q.y)*det} for i = 2,#vertices do p,q = q,vertices[i] det = vector.det(p.x,p.y, q.x,q.y) self.centroid.x = self.centroid.x + (p.x+q.x) * det self.centroid.y = self.centroid.y + (p.y+q.y) * det end self.centroid.x = self.centroid.x / (6 * self.area) self.centroid.y = self.centroid.y / (6 * self.area) -- get outcircle self._radius = 0 for i = 1,#vertices do self._radius = math.max(self._radius, vector.dist(vertices[i].x,vertices[i].y, self.centroid.x,self.centroid.y)) end end local newPolygon -- return vertices as x1,y1,x2,y2, ..., xn,yn function Polygon:unpack() local v = {} for i = 1,#self.vertices do v[2*i-1] = self.vertices[i].x v[2*i] = self.vertices[i].y end return unpack(v) end -- deep copy of the polygon function Polygon:clone() return Polygon( self:unpack() ) end -- get bounding box function Polygon:bbox() local ulx,uly = self.vertices[1].x, self.vertices[1].y local lrx,lry = ulx,uly for i=2,#self.vertices do local p = self.vertices[i] if ulx > p.x then ulx = p.x end if uly > p.y then uly = p.y end if lrx < p.x then lrx = p.x end if lry < p.y then lry = p.y end end return ulx,uly, lrx,lry end -- a polygon is convex if all edges are oriented ccw function Polygon:isConvex() local function isConvex() local v = self.vertices if #v == 3 then return true end if not ccw(v[#v], v[1], v[2]) then return false end for i = 2,#v-1 do if not ccw(v[i-1], v[i], v[i+1]) then return false end end if not ccw(v[#v-1], v[#v], v[1]) then return false end return true end -- replace function so that this will only be computed once local status = isConvex() self.isConvex = function() return status end return status end function Polygon:move(dx, dy) if not dy then dx, dy = dx:unpack() end for i,v in ipairs(self.vertices) do v.x = v.x + dx v.y = v.y + dy end self.centroid.x = self.centroid.x + dx self.centroid.y = self.centroid.y + dy end function Polygon:rotate(angle, cx, cy) if not (cx and cy) then cx,cy = self.centroid.x, self.centroid.y end for i,v in ipairs(self.vertices) do -- v = (v - center):rotate(angle) + center v.x,v.y = vector.add(cx,cy, vector.rotate(angle, v.x-cx, v.y-cy)) end local v = self.centroid v.x,v.y = vector.add(cx,cy, vector.rotate(angle, v.x-cx, v.y-cy)) end function Polygon:scale(s, cx,cy) if not (cx and cy) then cx,cy = self.centroid.x, self.centroid.y end for i,v in ipairs(self.vertices) do -- v = (v - center) * s + center v.x,v.y = vector.add(cx,cy, vector.mul(s, v.x-cx, v.y-cy)) end self._radius = self._radius * s end -- triangulation by the method of kong function Polygon:triangulate() if #self.vertices == 3 then return {self:clone()} end local vertices = self.vertices local next_idx, prev_idx = {}, {} for i = 1,#vertices do next_idx[i], prev_idx[i] = i+1,i-1 end next_idx[#next_idx], prev_idx[1] = 1, #prev_idx local concave = {} for i, v in ipairs(vertices) do if not ccw(vertices[prev_idx[i]], v, vertices[next_idx[i]]) then concave[v] = true end end local triangles = {} local n_vert, current, skipped, next, prev = #vertices, 1, 0 while n_vert > 3 do next, prev = next_idx[current], prev_idx[current] local p,q,r = vertices[prev], vertices[current], vertices[next] if isEar(p,q,r, concave) then triangles[#triangles+1] = newPolygon(p.x,p.y, q.x,q.y, r.x,r.y) next_idx[prev], prev_idx[next] = next, prev concave[q] = nil n_vert, skipped = n_vert - 1, 0 else skipped = skipped + 1 assert(skipped <= n_vert, "Cannot triangulate polygon") end current = next end next, prev = next_idx[current], prev_idx[current] local p,q,r = vertices[prev], vertices[current], vertices[next] triangles[#triangles+1] = newPolygon(p.x,p.y, q.x,q.y, r.x,r.y) return triangles end -- return merged polygon if possible or nil otherwise function Polygon:mergedWith(other) local p,q = getSharedEdge(self.vertices, other.vertices) assert(p and q, "Polygons do not share an edge") local ret = {} for i = 1,p-1 do ret[#ret+1] = self.vertices[i].x ret[#ret+1] = self.vertices[i].y end for i = 0,#other.vertices-2 do i = ((i-1 + q) % #other.vertices) + 1 ret[#ret+1] = other.vertices[i].x ret[#ret+1] = other.vertices[i].y end for i = p+1,#self.vertices do ret[#ret+1] = self.vertices[i].x ret[#ret+1] = self.vertices[i].y end return newPolygon(unpack(ret)) end -- split polygon into convex polygons. -- note that this won't be the optimal split in most cases, as -- finding the optimal split is a really hard problem. -- the method is to first triangulate and then greedily merge -- the triangles. function Polygon:splitConvex() -- edge case: polygon is a triangle or already convex if #self.vertices <= 3 or self:isConvex() then return {self:clone()} end local convex = self:triangulate() local i = 1 repeat local p = convex[i] local k = i + 1 while k <= #convex do local success, merged = pcall(function() return p:mergedWith(convex[k]) end) if success and merged:isConvex() then convex[i] = merged p = convex[i] table.remove(convex, k) else k = k + 1 end end i = i + 1 until i >= #convex return convex end function Polygon:contains(x,y) -- test if an edge cuts the ray local function cut_ray(p,q) return ((p.y > y and q.y < y) or (p.y < y and q.y > y)) -- possible cut and (x - p.x < (y - p.y) * (q.x - p.x) / (q.y - p.y)) -- x < cut.x end -- test if the ray crosses boundary from interior to exterior. -- this is needed due to edge cases, when the ray passes through -- polygon corners local function cross_boundary(p,q) return (p.y == y and p.x > x and q.y < y) or (q.y == y and q.x > x and p.y < y) end local v = self.vertices local in_polygon = false local p,q = v[#v],v[#v] for i = 1, #v do p,q = q,v[i] if cut_ray(p,q) or cross_boundary(p,q) then in_polygon = not in_polygon end end return in_polygon end function Polygon:intersectionsWithRay(x,y, dx,dy) local nx,ny = vector.perpendicular(dx,dy) local wx,xy,det local ts = {} -- ray parameters of each intersection local q1,q2 = nil, self.vertices[#self.vertices] for i = 1, #self.vertices do q1,q2 = q2,self.vertices[i] wx,wy = q2.x - q1.x, q2.y - q1.y det = vector.det(dx,dy, wx,wy) if det ~= 0 then -- there is an intersection point. check if it lies on both -- the ray and the segment. local rx,ry = q2.x - x, q2.y - y local l = vector.det(rx,ry, wx,wy) / det local m = vector.det(dx,dy, rx,ry) / det if m >= 0 and m <= 1 then -- we cannot jump out early here (i.e. when l > tmin) because -- the polygon might be concave ts[#ts+1] = l end else -- lines parralel or incident. get distance of line to -- anchor point. if they are incident, check if an endpoint -- lies on the ray local dist = vector.dot(q1.x-x,q1.y-y, nx,ny) if dist == 0 then local l = vector.dot(dx,dy, q1.x-x,q1.y-y) local m = vector.dot(dx,dy, q2.x-x,q2.y-y) if l >= m then ts[#ts+1] = l else ts[#ts+1] = m end end end end return ts end function Polygon:intersectsRay(x,y, dx,dy) local tmin = math.huge for _, t in ipairs(self:intersectionsWithRay(x,y,dx,dy)) do tmin = math.min(tmin, t) end return tmin ~= math.huge, tmin end Polygon = common_local.class('Polygon', Polygon) newPolygon = function(...) return common_local.instance(Polygon, ...) end return Polygon
gpl-2.0
liruqi/bigfoot
Interface/AddOns/DBM-Party-Legion/ReturnToKarazhan/Curator.lua
1
2589
local mod = DBM:NewMod(1836, "DBM-Party-Legion", 11, 860) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 17077 $"):sub(12, -3)) mod:SetCreatureID(114462) mod:SetEncounterID(1964) mod:SetZone() --mod:SetUsedIcons(1) --mod:SetHotfixNoticeRev(14922) --mod.respawnTime = 30 mod.noNormal = true mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_CAST_SUCCESS 234416", "SPELL_AURA_APPLIED 227254", "SPELL_AURA_REMOVED 227254", "SPELL_PERIODIC_DAMAGE 227465", "SPELL_PERIODIC_MISSED 227465", "UNIT_SPELLCAST_SUCCEEDED boss1" ) local warnAdds = mod:NewSpellAnnounce(227267, 2)--if not cast too often make special warning? local warnEvo = mod:NewSpellAnnounce(227254, 1) local warnEvoOver = mod:NewEndAnnounce(227254, 2) local specWarnPowerDischarge = mod:NewSpecialWarningMove(227465, nil, nil, nil, 1, 2) local timerSummonAddCD = mod:NewNextTimer(9.7, 227267, nil, nil, nil, 1) local timerPowerDischargeCD = mod:NewCDTimer(12.2, 227279, nil, nil, nil, 3) local timerEvoCD = mod:NewNextTimer(70, 227254, nil, nil, nil, 6) local timerEvo = mod:NewBuffActiveTimer(20, 227254, nil, nil, nil, 6) --local berserkTimer = mod:NewBerserkTimer(300) local countdownEvo = mod:NewCountdown(70, 227254) function mod:OnCombatStart(delay) timerSummonAddCD:Start(6-delay) timerPowerDischargeCD:Start(13.5) timerEvoCD:Start(68-delay) countdownEvo:Start(68) end function mod:OnCombatEnd() end function mod:SPELL_CAST_SUCCESS(args) local spellId = args.spellId if spellId == 234416 then warnAdds:Show() timerSummonAddCD:Start() end end function mod:SPELL_AURA_APPLIED(args) local spellId = args.spellId if spellId == 227254 then timerSummonAddCD:Stop() timerPowerDischargeCD:Stop() warnEvo:Show() timerEvo:Start() countdownEvo:Start(20) end end function mod:SPELL_AURA_REMOVED(args) local spellId = args.spellId if spellId == 227254 then warnEvoOver:Show() timerEvoCD:Start() countdownEvo:Start() end end function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId) if spellId == 227465 and destGUID == UnitGUID("player") and self:AntiSpam(2, 1) then specWarnPowerDischarge:Show() specWarnPowerDischarge:Play("runaway") end end mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, spellGUID) local spellId = tonumber(select(5, strsplit("-", spellGUID)), 10) if spellId == 227278 then timerPowerDischargeCD:Start() end end
mit
SbssTeam/QuickPlus
plugins/lock_badw.lua
4
1096
local function run(msg, matches) if msg.to.type == 'chat' then if is_momod then return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_badw'] then lock_adds = data[tostring(msg.to.id)]['settings']['lock_badw'] end end end local chat = get_receiver(msg) local user = "user#id"..msg.from.id if lock_adds == "yes" then send_large_msg(chat, 'Badwords is not allowed here!!') chat_del_user(chat, user, ok_cb, true) end end end return { patterns = { "(ک*س)$", "کیر", "کص", "کــــــــــیر", "کــــــــــــــــــــــــــــــیر", "کـیـــــــــــــــــــــــــــــــــــــــــــــــــــر", "ک×یر", "ک÷یر", "ک*ص", "کــــــــــیرر", "kir", "kos", "گوساله", "gosale", "gusale" }, run = run }
gpl-2.0
dromozoa/dromozoa-commons
dromozoa/commons/uint32.lua
3
9619
-- 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 lua_version_num = require "dromozoa.commons.lua_version_num" local function add(a, b, x, ...) local c = (a + b) % 0x100000000 if x == nil then return c else return add(c, x, ...) end end local function sub(a, b) return (a - b) % 0x100000000 end local function mul(a, b, x, ...) local a1 = a % 0x10000 local a2 = (a - a1) / 0x10000 local c1 = a1 * b local c2 = a2 * b % 0x10000 local c = (c1 + c2 * 0x10000) % 0x100000000 if x == nil then return c else return mul(c, x, ...) end end local function div(a, b) local c = a / b return c - c % 1 end local function mod(a, b) return a % b end local function byte(v, endian) local d = v % 0x100 local v = (v - d) / 0x100 local c = v % 0x100 local v = (v - c) / 0x100 local b = v % 0x100 local a = (v - b) / 0x100 if endian == ">" then return a, b, c, d else return d, c, b, a end end local function char(v, endian) return string.char(byte(v, endian)) end local function read(handle, n, endian) local a, b, c, d = handle:read(4):byte(1, 4) local v if endian == ">" then v = a * 0x1000000 + b * 0x10000 + c * 0x100 + d else v = d * 0x1000000 + c * 0x10000 + b * 0x100 + a end if n == nil or n == 1 then return v else return v, read(handle, n - 1, endian) end end if lua_version_num >= 503 then return assert(load([[ local function add(a, b, x, ...) local c = a + b & 0xffffffff if x == nil then return c else return add(c, x, ...) end end local function mul(a, b, x, ...) local c = a * b & 0xffffffff if x == nil then return c else return mul(c, x, ...) end end local function band(a, b, x, ...) local c = a & b if x == nil then return c else return band(c, x, ...) end end local function bor(a, b, x, ...) local c = a | b if x == nil then return c else return bor(c, x, ...) end end local function bxor(a, b, x, ...) local c = a ~ b if x == nil then return c else return bxor(c, x, ...) end end local function read(handle, n, endian) local v if endian == ">" then v = (">I4"):unpack(handle:read(4)) else v = ("<I4"):unpack(handle:read(4)) end if n == nil or n == 1 then return v else return v, read(handle, n - 1, endian) end end return { add = add; sub = function (a, b) return a - b & 0xffffffff end; mul = mul; div = function (a, b) return a // b end; mod = function (a, b) return a % b end; band = band; bor = bor; bxor = bxor; shl = function (a, b) return a << b & 0xffffffff end; shr = function (a, b) return a >> b end; bnot = function (v) return ~v & 0xffffffff end; rotl = function (a, b) return (a << b | a >> 32 - b) & 0xffffffff end; rotr = function (a, b) return (a >> b | a << 32 - b) & 0xffffffff end; byte = function (v, endian) if endian == ">" then local a, b, c, d = ("BBBB"):unpack((">I4"):pack(v)) return a, b, c, d else local a, b, c, d = ("BBBB"):unpack(("<I4"):pack(v)) return a, b, c, d end end; char = function (v, endian) if endian == ">" then return (">I4"):pack(v) else return ("<I4"):pack(v) end end; read = read; } ]]))() elseif bit32 then return { add = add; sub = sub; mul = mul; div = div; mod = mod; band = bit32.band; bor = bit32.bor; bxor = bit32.bxor; shl = bit32.lshift; shr = bit32.rshift; bnot = bit32.bnot; rotl = bit32.lrotate; rotr = bit32.rrotate; byte = byte; char = char; read = read; } elseif bit then local bit_band = bit.band local bit_bor = bit.bor local bit_bxor = bit.bxor local bit_lshift = bit.lshift local bit_rshift = bit.rshift local bit_bnot = bit.bnot local bit_rol = bit.rol local bit_ror = bit.ror return { add = add; sub = sub; mul = mul; div = div; mod = mod; band = function (...) return bit_band(...) % 0x100000000 end; bor = function (...) return bit_bor(...) % 0x100000000 end; bxor = function (...) return bit_bxor(...) % 0x100000000 end; shl = function (a, b) return bit_lshift(a, b) % 0x100000000 end; shr = function (a, b) return bit_rshift(a, b) % 0x100000000 end; bnot = function (v) return bit_bnot(v) % 0x100000000 end; rotl = function (a, b) return bit_rol(a, b) % 0x100000000 end; rotr = function (a, b) return bit_ror(a, b) % 0x100000000 end; byte = byte; char = char; read = read; } else local function optimize_unary(fn) local t = {} for v = 0, 255 do t[v] = fn(v) % 0x100 end return function (v) local v1 = v % 0x100 v = (v - v1) / 0x100 local v2 = v % 0x100 v = (v - v2) / 0x100 local v3 = v % 0x100 v = (v - v3) / 0x100 return t[v] * 0x1000000 + t[v3] * 0x10000 + t[v2] * 0x100 + t[v1] end end local function optimize_binary(fn) local t = {} for a = 0, 15 do t[a] = {} for b = 0, 15 do t[a][b] = fn(a, b) % 0x100 end end local function f(a, b, x, ...) local a1 = a % 0x10 a = (a - a1) / 0x10 local a2 = a % 0x10 a = (a - a2) / 0x10 local a3 = a % 0x10 a = (a - a3) / 0x10 local a4 = a % 0x10 a = (a - a4) / 0x10 local a5 = a % 0x10 a = (a - a5) / 0x10 local a6 = a % 0x10 a = (a - a6) / 0x10 local a7 = a % 0x10 a = (a - a7) / 0x10 local b1 = b % 0x10 b = (b - b1) / 0x10 local b2 = b % 0x10 b = (b - b2) / 0x10 local b3 = b % 0x10 b = (b - b3) / 0x10 local b4 = b % 0x10 b = (b - b4) / 0x10 local b5 = b % 0x10 b = (b - b5) / 0x10 local b6 = b % 0x10 b = (b - b6) / 0x10 local b7 = b % 0x10 b = (b - b7) / 0x10 local c = t[a][b] * 0x10000000 + t[a7][b7] * 0x1000000 + t[a6][b6] * 0x100000 + t[a5][b5] * 0x10000 + t[a4][b4] * 0x1000 + t[a3][b3] * 0x100 + t[a2][b2] * 0x10 + t[a1][b1] if x == nil then return c else return f(c, x, ...) end end return f end local function band(a, b, x, ...) local c = 0 local d = 1 for i = 1, 31 do local a1 = a % 2 local b1 = b % 2 if a1 + b1 == 2 then c = c + d end a = (a - a1) / 2 b = (b - b1) / 2 d = d * 2 end if a + b == 2 then c = c + d end if x == nil then return c else return band(c, x, ...) end end local function bor(a, b, x, ...) local c = 0 local d = 1 for i = 1, 31 do local a1 = a % 2 local b1 = b % 2 if a1 + b1 ~= 0 then c = c + d end a = (a - a1) / 2 b = (b - b1) / 2 d = d * 2 end if a + b ~= 0 then c = c + d end if x == nil then return c else return bor(c, x, ...) end end local function bxor(a, b, x, ...) local c = 0 local d = 1 for i = 1, 31 do local a1 = a % 2 local b1 = b % 2 if a1 ~= b1 then c = c + d end a = (a - a1) / 2 b = (b - b1) / 2 d = d * 2 end if a ~= b then c = c + d end if x == nil then return c else return bxor(c, x, ...) end end local function bnot(v) local c = 0 local d = 1 for i = 1, 31 do local v1 = v % 2 if v1 == 0 then c = c + d end v = (v - v1) / 2 d = d * 2 end if v == 0 then c = c + d end return c end local function shl(a, b) local b1 = 2 ^ b local b2 = 0x100000000 / b1 return a % b2 * b1 end local function shr(a, b) local b1 = 2 ^ b local c = a / b1 return c - c % 1 end local function rotl(a, b) local b1 = 2 ^ b local b2 = 0x100000000 / b1 local c1 = a % b2 local c2 = (a - c1) / b2 return c1 * b1 + c2 end local function rotr(a, b) local b1 = 2 ^ b local b2 = 0x100000000 / b1 local c1 = a % b1 local c2 = (a - c1) / b1 return c1 * b2 + c2 end return { add = add; sub = sub; mul = mul; div = div; mod = mod; band = optimize_binary(band); bor = optimize_binary(bor); bxor = optimize_binary(bxor); shl = shl; shr = shr; bnot = optimize_unary(bnot); rotl = rotl; rotr = rotr; byte = byte; char = char; read = read; } end
gpl-3.0
Zuck3rFr3i/Horrizon-Reloadet
Horrizon/playerdata_handler.lua
1
2852
addEvent("system:setupPlayerData", true) addEventHandler("system:setupPlayerData", root, function(playerElem, pSerial) local getData, rows = mysql_get("SELECT * FROM userdata WHERE serial=?", pSerial) if getData and rows >= 1 then local uid = getData[1]["uid"] local money = getData[1]["money"] local bankMoney = getData[1]["bankmoney"] local pkw local lkw local bike local heli local weapon local plane local xspawn local yspawn local zspawn for i, v in pairs(getData) do pkw, lkw, bike, heli, weapon, plane = tonumber(gettok(v.licences, 1, "|")), tonumber(gettok(v.licences, 2, "|")), tonumber(gettok(v.licences, 3, "|")), tonumber(gettok(v.licences, 4, "|")), tonumber(gettok(v.licences, 5, "|")), tonumber(gettok(v.licences, 6, "|")) xspawn, yspawn, zspawn = tonumber(gettok(v.spawn, 1, "|")), tonumber(gettok(v.spawn, 2, "|")), tonumber(gettok(v.spawn, 3, "|")) end if pkw and plane and money then setSaveElementData(playerElem, "uid", uid) setSaveElementData(playerElem, "money", money) setSaveElementData(playerElem, "bankmoney", bankmoney) setSaveElementData(playerElem, "pkw", pkw) setSaveElementData(playerElem, "lkw", lkw) setSaveElementData(playerElem, "bike", bike) setSaveElementData(playerElem, "heli", heli) setSaveElementData(playerElem, "weapon", weapon) setSaveElementData(playerElem, "plane", plane) setSaveElementData(playerElem, "adminlv", 2) setSaveElementData(playerElem, "loggedin", 1) -- Setup Tags and Colors for the chat! if getSaveElementData(playerElem, "adminlv") == 0 then setSaveElementData(playerElem, "tag", "[Spieler]") setSaveElementData(playerElem, "tagcolor", "#0DFF00") elseif getSaveElementData(playerElem, "adminlv") == 1 then setSaveElementData(playerElem, "tag", "[VIP]") setSaveElementData(playerElem, "tagcolor", "#F7FF00") elseif getSaveElementData(playerElem, "adminlv") == 2 then setSaveElementData(playerElem, "tag", "[GameMaster]") setSaveElementData(playerElem, "tagcolor", "#A700DA") elseif getSaveElementData(playerElem, "adminlv") == 3 then setSaveElementData(playerElem, "tag", "[GameAdmin]") setSaveElementData(playerElem, "tagcolor", "#FFBC00") elseif getSaveElementData(playerElem, "adminlv") == 4 then setSaveElementData(playerElem, "tag", "[ServerAdmin]") setSaveElementData(playerElem, "tagcolor", "#FF0004") end -- end spawnPlayer(playerElem, xspawn, yspawn, zspawn) setCameraTarget(playerElem, playerElement) outputChatBox("#FF4000[Horrizon]: #FFAF00Server meldet: #0066FF"..getPlayerName(playerElem)..", #FFAF00wurde eingeloggt, momentaner adminrang: "..getSaveElementData(playerElem, "adminlv"), source, 0, 0, 0, true) end end end)
gpl-3.0
inTact700/VLCHotkey
share/lua/modules/simplexml.lua
103
3732
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea 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. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream, errormsg) if not stream then return nil, errormsg end local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} local nodetype, nodename = reader:next_node() while nodetype > 0 do if nodetype == 1 then local node = { name= nodename, attributes= {}, children= {} } local attr, value = reader:next_attr() while attr ~= nil do node.attributes[attr] = value attr, value = reader:next_attr() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 2 then if #parents > 0 then local tmp = {} while nodename ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 3 then table.insert(tree.children, nodename) end nodetype, nodename = reader:next_node() end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end function add_name_maps(tree) tree.children_map = {} for _, node in pairs(tree.children) do if type(node) == "table" then if not tree.children_map[node.name] then tree.children_map[node.name] = {} end table.insert(tree.children_map[node.name], node) add_name_maps(node) end end end
gpl-2.0
liruqi/bigfoot
Interface/AddOns/Recount/GUI_DeathGraph.lua
1
1823
local Recount = _G.Recount local Graph = LibStub:GetLibrary("LibGraph-2.0") local AceLocale = LibStub("AceLocale-3.0") local L = AceLocale:GetLocale("Recount") local revision = tonumber(string.sub("$Revision: 1254 $", 12, -3)) if Recount.Version < revision then Recount.Version = revision end local me = {} function me:CreateDeathGraphWindow() local theFrame = Recount:CreateFrame("Recount_DeathGraph", L["Death Graph"], 182, 200) local g = Graph:CreateGraphLine("Recount_DeathScatter", theFrame, "BOTTOM", "BOTTOM", 0, 2, 197, 149) g:SetXAxis(-15, 1) g:SetYAxis(0, 100) g:SetGridSpacing(1, 25) g:SetGridColor({0.5, 0.5, 0.5, 0.5}) g:SetAxisDrawing(true, true) g:SetAxisColor({1.0, 1.0, 1.0, 1.0}) g:SetYLabels(true, false) theFrame.Graph = g g = Graph:CreateGraphScatterPlot("Recount_DeathScatter", theFrame, "BOTTOM", "BOTTOM", 0, 2, 197, 149) g:SetXAxis(-15, 1) g:SetYAxis(0, 100) g:SetGridSpacing(100, 100) g:SetGridColor({0.5, 0.5, 0.5, 0}) g:SetAxisDrawing(false, false) g:SetAxisColor({1.0, 1.0, 1.0, 0}) g:SetFrameLevel(theFrame.Graph:GetFrameLevel() + 1) theFrame.Scatter = g --Need to add it to our window ordering system Recount:AddWindow(theFrame) Recount.DeathGraph = theFrame end function Recount:ShowDeathGraph(Health, Heals, Hits) if not Recount.DeathGraph then me:CreateDeathGraphWindow() end local DeathGraph = Recount.DeathGraph DeathGraph:Show() --DeathGraph.Title:SetText("Death Graph - "..Title) DeathGraph.Graph:ResetData() DeathGraph.Graph:AddDataSeries(Health, {0.2, 1.0, 0.2, 0.8}, false) DeathGraph.Scatter:ResetData() if Heals then DeathGraph.Scatter:AddDataSeries(Heals, {0.1, 1.0, 0.1, 0.8}) end if Hits then DeathGraph.Scatter:AddDataSeries(Hits, {1.0, 0.1, 0.1, 0.8}) end end
mit
ingran/balzac
custom_feeds/teltonika_luci/applications/luci-sms-gateway/luasrc/model/cbi/sms_gateway/forwarding_to_sms.lua
1
1998
local utl = require "luci.util" local nw = require "luci.model.network" local sys = require "luci.sys" local ntm = require "luci.model.network".init() local m local savePressed = luci.http.formvalue("cbi.apply") and true or false m2 = Map("sms_gateway", translate("SMS Forwarding To SMS Configuration"), translate("")) m2.addremove = false sc = m2:section(NamedSection, "forwarding_to_sms","forwarding_to_sms", translate("SMS Forwarding To SMS Settings")) enb_block = sc:option(Flag, "enabled", translate("Enable"), translate("Enable/disable sms forwarding")) enb_block.rmempty = false enb_block = sc:option(Flag, "sender_num", translate("Add sender number"), translate("Enable/disable adding original message sender phone number at the end of message text. Only added if total message length is up to 480 characters")) enb_block.rmempty = false o = sc:option(ListValue, "mode", translate("Mode"), translate("Choose witch messages are going to be forwarded")) o:value("everyone", translate("All messages")) o:value("list", translate("From listed numbers")) o.default = "everyone" o = sc:option(DynamicList, "senders_number", translate("Sender's phone number(s)"), translate("Number(s) from witch received messages will be forwarded")) o:depends("mode", "list") function o:validate(Values) local failure for k,v in pairs(Values) do if not v:match("^[+%d]%d*$") then m2.message = translatef("err: SMS sender's phone number \"%s\" is incorrect!", v) failure = true end end if not failure then return Values end return nil end o = sc:option(DynamicList, "number", translate("recipients phone numbers"), translate("Number(s) to witch received messages will be forwarded to")) function o:validate(Values) local failure for k,v in pairs(Values) do if not v:match("^[+%d]%d*$") then m2.message = translatef("err: SMS recipient's phone number \"%s\" is incorrect!", v) failure = true end end if not failure then return Values end return nil end return m2
gpl-2.0
liruqi/bigfoot
Interface/AddOns/DBM-DragonSoul/SpineDeathwing.lua
1
11810
local mod = DBM:NewMod(318, "DBM-DragonSoul", nil, 187) local L = mod:GetLocalizedStrings() local sndWOP = mod:SoundMM("SoundWOP") mod:SetRevision(("$Revision: 79 $"):sub(12, -3)) mod:SetCreatureID(53879) mod:SetModelSound("sound\\CREATURE\\Deathwing\\VO_DS_DEATHWING_BACKEVENT_01.OGG", "sound\\CREATURE\\Deathwing\\VO_DS_DEATHWING_BACKSLAY_01") mod:SetZone() mod:SetUsedIcons(6, 5, 4, 3, 2, 1) mod:RegisterCombat("yell", L.Pull)--INSTANCE_ENCOUNTER_ENGAGE_UNIT comes 30 seconds after encounter starts, because of this, the mod can miss the first round of ability casts such as first grip targets. have to use yell mod:RegisterEventsInCombat( "SPELL_CAST_START", "SPELL_CAST_SUCCESS", "SPELL_AURA_APPLIED", "SPELL_AURA_APPLIED_DOSE", "SPELL_AURA_REMOVED", "SPELL_HEAL", "SPELL_PERIODIC_HEAL", "SPELL_DAMAGE", "SPELL_MISSED", "SWING_DAMAGE", "SWING_MISSED", "RAID_BOSS_EMOTE", "UNIT_DIED", "UNIT_HEALTH" ) local warnAbsorbedBlood = mod:NewStackAnnounce(105248, 2) local warnGrip = mod:NewTargetAnnounce(105490, 4) local warnNuclearBlast = mod:NewCastAnnounce(105845, 4) local warnSealArmor = mod:NewCastAnnounce(105847, 4) local warnAmalgamation = mod:NewSpellAnnounce("ej4054", 3, 106005)--Amalgamation spawning, give temp icon. local warnCorruptionDeath = mod:NewTargetAnnounce(106199, 3) local warnCorruptionEarth = mod:NewTargetAnnounce(106200, 3) local specWarnTendril = mod:NewSpecialWarning("SpecWarnTendril") local specWarnGrip = mod:NewSpecialWarningSpell(105490, mod:IsDps()) local specWarnNuclearBlast = mod:NewSpecialWarningRun(105845) local specWarnSealArmor = mod:NewSpecialWarningSpell(105847, mod:IsDps()) local specWarnAmalgamation = mod:NewSpecialWarningSpell("ej4054", false) local specWarnAmalgamationLowHP = mod:NewSpecialWarning("SpecWarnAmaLowHP") local timerSealArmor = mod:NewCastTimer(23, 105847) local timerBarrelRoll = mod:NewCastTimer(6, "ej4050") local timerGripCD = mod:NewNextTimer(32, 105490) local timerDeathCD = mod:NewCDTimer(8.5, 106199)--8.5-10sec variation. mod:RemoveOption("HealthFrame") mod:AddBoolOption("InfoFrame", true) mod:AddBoolOption("SetIconOnGrip", true) mod:AddBoolOption("SetIconOnDeath", true) mod:AddBoolOption("SetIconOnEarth", true) mod:AddBoolOption("ShowShieldInfo", mod:IsHealer()) local gripTargets = {} local gripIcon = 6 local corruptionActive = {} local residueNum = 0 local residueDebug = false local diedOozeGUIDS = {} local warnedAmalgamation = false local BloodAbsorbed = 0 local function checkTendrils() if not UnitDebuff("player", GetSpellInfo(105563)) and not UnitIsDeadOrGhost("player") then specWarnTendril:Show() end end local function showGripWarning() warnGrip:Show(table.concat(gripTargets, "<, >")) specWarnGrip:Show() sndWOP:Play("someonecaught") table.wipe(gripTargets) end local function warningResidue() if mod.Options.InfoFrame and residueNum >= 0 then DBM.InfoFrame:SetHeader(L.BloodCount) -- DBM.InfoFrame:Show(1, "texts", residueNum, nil, nil, L.BloodCount) end end local function checkOozeResurrect(GUID) -- set min resurrect time to 5 sec. (guessed) if diedOozeGUIDS[GUID] and GetTime() - diedOozeGUIDS[GUID] > 5 then residueNum = residueNum - 1 diedOozeGUIDS[GUID] = nil mod:Unschedule(warningResidue) mod:Schedule(1.25, warningResidue) if residueDebug then print("revived", residueNum) end end end local clearPlasmaTarget, setPlasmaTarget, clearPlasmaVariables do local plasmaTargets = {} local healed = {} function mod:SPELL_HEAL(_, _, _, _, destGUID, _, _, _, _, _, _, _, _, absorbed) if plasmaTargets[destGUID] then healed[destGUID] = healed[destGUID] + (absorbed or 0) DBM.BossHealth:Update() end end mod.SPELL_PERIODIC_HEAL = mod.SPELL_HEAL local function updatePlasmaTargets() local maxAbsorb = mod:IsDifficulty("heroic25") and 420000 or mod:IsDifficulty("heroic10") and 280000 or mod:IsDifficulty("normal25") and 300000 or mod:IsDifficulty("normal10") and 200000 or 1 DBM.BossHealth:Clear() if not DBM.BossHealth:IsShown() then DBM.BossHealth:Show(L.name) end for i,v in pairs(plasmaTargets) do DBM.BossHealth:AddBoss(function() return math.max(1, math.floor((healed[i] or 0) / maxAbsorb * 100)) end, L.PlasmaTarget:format(v)) end end function setPlasmaTarget(guid, name) plasmaTargets[guid] = name healed[guid] = 0 updatePlasmaTargets() end function clearPlasmaTarget(guid, name) plasmaTargets[guid] = nil healed[guid] = nil updatePlasmaTargets() end function clearPlasmaVariables() table.wipe(plasmaTargets) table.wipe(healed) updatePlasmaTargets() end end function mod:OnCombatStart(delay) if self:IsDifficulty("lfr25") then warnSealArmor = mod:NewCastAnnounce(105847, 4, 34.5) else warnSealArmor = mod:NewCastAnnounce(105847, 4) end table.wipe(gripTargets) table.wipe(corruptionActive) table.wipe(diedOozeGUIDS) if self.Options.ShowShieldInfo then clearPlasmaVariables() end gripIcon = 6 residueNum = 0 warnedAmalgamation = false BloodAbsorbed = 0 end function mod:OnCombatEnd() if self.Options.InfoFrame then DBM.InfoFrame:Hide() end end function mod:SPELL_CAST_START(args) if args:IsSpellID(105845) then warnNuclearBlast:Show() specWarnNuclearBlast:Show() sndWOP:Play("boomrun") warnedAmalgamation = false elseif args:IsSpellID(105847, 105848) then warnSealArmor:Show() specWarnSealArmor:Show() sndWOP:Play("killmuscle") if self:IsDifficulty("lfr25") then timerSealArmor:Start(34.5) else timerSealArmor:Start() end elseif args:IsSpellID(109379) then if not corruptionActive[args.sourceGUID] then corruptionActive[args.sourceGUID] = 0 if self:IsDifficulty("normal25", "heroic25") then timerGripCD:Start(16, args.sourceGUID) else timerGripCD:Start(nil, args.sourceGUID) end end corruptionActive[args.sourceGUID] = corruptionActive[args.sourceGUID] + 1 if corruptionActive[args.sourceGUID] == 2 and self:IsDifficulty("normal25", "heroic25") then timerGripCD:Update(8, 16, args.sourceGUID) sndWOP:Schedule(5, "Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\3") sndWOP:Schedule(6, "Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\2") sndWOP:Schedule(7, "Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\1") elseif corruptionActive[args.sourceGUID] == 4 and self:IsDifficulty("normal10", "heroic10") then timerGripCD:Update(24, 32, args.sourceGUID) sndWOP:Schedule(5, "Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\3") sndWOP:Schedule(6, "Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\2") sndWOP:Schedule(7, "Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\1") end end end function mod:SPELL_CAST_SUCCESS(args) if args:IsSpellID(106199) and self:IsHealer() then sndWOP:Play("dispelnow") elseif args:IsSpellID(105219) then residueNum = residueNum + 1 diedOozeGUIDS[args.sourceGUID] = GetTime() self:Unschedule(warningResidue) self:Schedule(1.25, warningResidue) if residueDebug then print("created", residueNum) end elseif args:IsSpellID(105248) and diedOozeGUIDS[args.sourceGUID] then residueNum = residueNum - 1 diedOozeGUIDS[args.sourceGUID] = nil self:Unschedule(warningResidue) self:Schedule(1.25, warningResidue) if residueDebug then print("absorbed", residueNum) end end end function mod:SPELL_DAMAGE(sourceGUID, _, _, _, destGUID) checkOozeResurrect(sourceGUID) end mod.SPELL_MISSED = mod.SPELL_DAMAGE function mod:SWING_DAMAGE(sourceGUID, _, _, _, destGUID) checkOozeResurrect(sourceGUID) end mod.SWING_MISSED = mod.SWING_DAMAGE function mod:SPELL_AURA_APPLIED(args) if args:IsSpellID(105248) then warnAbsorbedBlood:Show(args.destName, 1) BloodAbsorbed = 1 elseif args:IsSpellID(105490) then gripTargets[#gripTargets + 1] = args.destName timerGripCD:Cancel(args.sourceGUID) sndWOP:Cancel("Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\3") sndWOP:Cancel("Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\2") sndWOP:Cancel("Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\1") if corruptionActive[args.sourceGUID] then corruptionActive[args.sourceGUID] = nil end if self.Options.SetIconOnGrip then if gripIcon == 0 then gripIcon = 6 end self:SetIcon(args.destName, gripIcon) gripIcon = gripIcon - 1 end self:Unschedule(showGripWarning) self:Schedule(0.3, showGripWarning) elseif args:IsSpellID(105479) then if self.Options.ShowShieldInfo then setPlasmaTarget(args.destGUID, args.destName) end elseif args:IsSpellID(106199) then warnCorruptionDeath:Show(args.destName) if self.Options.SetIconOnDeath then self:SetIcon(args.destName, 8) end elseif args:IsSpellID(106200) then warnCorruptionEarth:Show(args.destName) if self.Options.SetIconOnEarth then self:SetIcon(args.destName, 7) end end end function mod:SPELL_AURA_APPLIED_DOSE(args) if args:IsSpellID(105248) then if args.amount == 9 then warnAbsorbedBlood:Show(args.destName, args.amount) warnedAmalgamation = true sndWOP:Play("killmixone") else warnAbsorbedBlood:Show(args.destName, args.amount) end BloodAbsorbed = args.amount end end function mod:SPELL_AURA_REMOVED(args) if args:IsSpellID(105490) then if self.Options.SetIconOnGrip then self:SetIcon(args.destName, 0) end if self:IsDps() then sndWOP:Play("safenow") end elseif args:IsSpellID(105479) then if self.Options.ShowShieldInfo then clearPlasmaTarget(args.destGUID, args.destName) end elseif args:IsSpellID(106199) then if self.Options.SetIconOnDeath then self:SetIcon(args.destName, 0) end elseif args:IsSpellID(106200) then if self.Options.SetIconOnEarth then self:SetIcon(args.destName, 0) end end end function mod:RAID_BOSS_EMOTE(msg) if msg == L.DRoll or msg:find(L.DRoll) or msg == L.DRollR or msg:find(L.DRollR) then self:Unschedule(checkTendrils) checkTendrils() self:Schedule(3, checkTendrils) timerBarrelRoll:Start() sndWOP:Schedule(4, "countthree") sndWOP:Schedule(5, "counttwo") sndWOP:Schedule(6, "countone") if msg == L.DRoll or msg:find(L.DRoll) then sndWOP:Play("leftside") elseif msg == L.DRollR or msg:find(L.DRollR) then sndWOP:Play("rightside") end elseif msg == L.DLevels or msg:find(L.DLevels) then sndWOP:Play("balancenow") self:Unschedule(checkTendrils) timerBarrelRoll:Cancel() sndWOP:Cancel("countthree") sndWOP:Cancel("counttwo") sndWOP:Cancel("countone") end end function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 53891 or cid == 56162 or cid == 56161 then timerGripCD:Cancel(args.sourceGUID) sndWOP:Cancel("Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\3") sndWOP:Cancel("Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\2") sndWOP:Cancel("Interface\\AddOns\\DBM-Core\\sounds\\Corsica_S\\1") warnAmalgamation:Schedule(4.5)--4.5-5 seconds after corruption dies. specWarnAmalgamation:Schedule(4.5) if self:IsDifficulty("heroic10", "heroic25") then timerDeathCD:Start(args.destGUID) end elseif cid == 56341 or cid == 56575 then timerSealArmor:Cancel() end end function mod:UNIT_HEALTH(uId) if self:GetUnitCreatureId(uId) == 53890 then local h = UnitHealth(uId) / UnitHealthMax(uId) * 100 if h < 15 and not warnedAmalgamation and BloodAbsorbed < 9 then warnedAmalgamation = true local bleft = 9 - BloodAbsorbed specWarnAmalgamationLowHP:Show(bleft) if not self:IsHealer() then sndWOP:Play("stopatk") end end end end
mit
gonku/awesome-wm-pabucolor
lain/widgets/mpd.lua
1
3596
--[[ Licensed under GNU General Public License v2 * (c) 2013, Luke Bonham * (c) 2010, Adrian C. <anrxc@sysphere.org> --]] local helpers = require("lain.helpers") local escape_f = require("awful.util").escape local naughty = require("naughty") local wibox = require("wibox") local io = { popen = io.popen } local os = { execute = os.execute, getenv = os.getenv } local string = { format = string.format, gmatch = string.gmatch } local setmetatable = setmetatable -- MPD infos -- lain.widgets.mpd local mpd = {} local function worker(args) local args = args or {} local timeout = args.timeout or 2 local password = args.password or "" local host = args.host or "127.0.0.1" local port = args.port or "6600" local music_dir = args.music_dir or os.getenv("HOME") .. "/Música" local cover_size = args.cover_size or 100 local default_art = args.default_art or "" local settings = args.settings or function() end local mpdcover = helpers.scripts_dir .. "mpdcover" local mpdh = "telnet://" .. host .. ":" .. port local echo = "echo 'password " .. password .. "\nstatus\ncurrentsong\nclose'" mpd.widget = wibox.widget.textbox('') mpd_notification_preset = { title = "Now playing", timeout = 6 } helpers.set_map("current mpd track", nil) function mpd.update() mpd_now = { state = "N/A", file = "N/A", artist = "N/A", title = "N/A", album = "N/A", date = "N/A" } local f = io.popen(echo .. " | curl --connect-timeout 1 -fsm 3 " .. mpdh) for line in f:lines() do for k, v in string.gmatch(line, "([%w]+):[%s](.*)$") do if k == "state" then mpd_now.state = v elseif k == "file" then mpd_now.file = v elseif k == "Artist" then mpd_now.artist = escape_f(v) elseif k == "Title" then mpd_now.title = escape_f(v) elseif k == "Album" then mpd_now.album = escape_f(v) elseif k == "Date" then mpd_now.date = escape_f(v) end end end f:close() mpd_notification_preset.text = string.format("%s (%s) - %s\n%s", mpd_now.artist, mpd_now.album, mpd_now.date, mpd_now.title) widget = mpd.widget settings() if mpd_now.state == "play" then if mpd_now.title ~= helpers.get_map("current mpd track") then helpers.set_map("current mpd track", mpd_now.title) os.execute(string.format("%s %q %q %d %q", mpdcover, music_dir, mpd_now.file, cover_size, default_art)) mpd.id = naughty.notify({ preset = mpd_notification_preset, icon = "/tmp/mpdcover.png", replaces_id = mpd.id }).id end elseif mpd_now.state ~= "pause" then helpers.set_map("current mpd track", nil) end end helpers.newtimer("mpd", timeout, mpd.update) return setmetatable(mpd, { __index = mpd.widget }) end return setmetatable(mpd, { __call = function(_, ...) return worker(...) end })
gpl-2.0
ingran/balzac
custom_feeds/teltonika_luci/applications/luci-radvd/luasrc/model/cbi/radvd/prefix.lua
1
3793
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: prefix.lua 8562 2012-04-15 14:31:12Z jow $ ]]-- local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - Prefix"), translate("Radvd is a router advertisement daemon for IPv6. It listens to router solicitations and sends router advertisements as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "prefix" then luci.http.redirect(m.redirect) return end s = m:section(NamedSection, sid, "interface", translate("Prefix Configuration")) s.addremove = false s:tab("general", translate("General")) s:tab("advanced", translate("Advanced")) -- -- General -- o = s:taboption("general", Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:taboption("general", Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:taboption("general", DynamicList, "prefix", translate("Prefixes"), translate("Advertised IPv6 prefixes. If empty, the current interface prefix is used")) o.optional = true o.datatype = "ip6addr" o.placeholder = translate("default") function o.cfgvalue(self, section) local l = { } local v = m.uci:get_list("radvd", section, "prefix") for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:taboption("general", Flag, "AdvOnLink", translate("On-link determination"), translate("Indicates that this prefix can be used for on-link determination (RFC4861)")) o.rmempty = false o.default = "1" o = s:taboption("general", Flag, "AdvAutonomous", translate("Autonomous"), translate("Indicates that this prefix can be used for autonomous address configuration (RFC4862)")) o.rmempty = false o.default = "1" -- -- Advanced -- o = s:taboption("advanced", Flag, "AdvRouterAddr", translate("Advertise router address"), translate("Indicates that the address of interface is sent instead of network prefix, as is required by Mobile IPv6")) o = s:taboption("advanced", Value, "AdvValidLifetime", translate("Valid lifetime"), translate("Advertises the length of time in seconds that the prefix is valid for the purpose of on-link determination.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 86400 o = s:taboption("advanced", Value, "AdvPreferredLifetime", translate("Preferred lifetime"), translate("Advertises the length of time in seconds that addresses generated from the prefix via stateless address autoconfiguration remain preferred.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 14400 o = s:taboption("advanced", Value, "Base6to4Interface", translate("6to4 interface"), translate("Specifies a logical interface name to derive a 6to4 prefix from. The interfaces public IPv4 address is combined with 2002::/3 and the value of the prefix option")) o.template = "cbi/network_netlist" o.nocreate = true o.unspecified = true return m
gpl-2.0
proubatsis/Procedural-City
Procedural City/lua/models/road/2_6_T_intersection.lua
1
3226
--[[ Copyright (C) 2015 Panagiotis Roubatsis 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. --]] dofile("lua/lib/vectors.lua") --Building functions baseIndex = 0 function createQuad(x,y,z,upX,upY,upZ,rightX,rightY,rightZ) normalX,normalY,normalZ = normalize(crossProduct(upX,upY,upZ,rightX,rightY,rightZ)) addVertex(x,y,z) addUV(0,0) addNormal(normalX,normalY,normalZ) addVertex(x+rightX,y+rightY,z+rightZ) addUV(1,0) addNormal(normalX,normalY,normalZ) addVertex(x+rightX+upX,y+rightY+upY,z+rightZ+upZ) addUV(1,1) addNormal(normalX,normalY,normalZ) addVertex(x+upX,y+upY,z+upZ) addUV(0,1) addNormal(normalX,normalY,normalZ) addTriangle(baseIndex + 0, baseIndex + 1, baseIndex + 2) addTriangle(baseIndex + 2, baseIndex + 3, baseIndex + 0) baseIndex = baseIndex + 4 end function createQuadUV(x,y,z,upX,upY,upZ,rightX,rightY,rightZ,uvX,uvY) normalX,normalY,normalZ = normalize(crossProduct(upX,upY,upZ,rightX,rightY,rightZ)) addVertex(x,y,z) addUV(0,0) addNormal(normalX,normalY,normalZ) addVertex(x+rightX,y+rightY,z+rightZ) addUV(uvX,0) addNormal(normalX,normalY,normalZ) addVertex(x+rightX+upX,y+rightY+upY,z+rightZ+upZ) addUV(uvX,uvY) addNormal(normalX,normalY,normalZ) addVertex(x+upX,y+upY,z+upZ) addUV(0,uvY) addNormal(normalX,normalY,normalZ) addTriangle(baseIndex + 0, baseIndex + 1, baseIndex + 2) addTriangle(baseIndex + 2, baseIndex + 3, baseIndex + 0) baseIndex = baseIndex + 4 end --Intersection createNode() setTexture("road.T_intersection.tex") createQuad(-16,0,16, 0,0,-32, 32,0,0) --Sidewalk createNode() baseIndex = 0 setTexture("road.sidewalk.tex") createQuad(-6,0.15,16, 0,0,-32, 2,0,0) --Top of T createQuadUV(16,0.15,-12, -12,0,0, 0,0,-4, 1,0.375) --Left of T createQuadUV(16,0.15,16, -12,0,0, 0,0,-4, 1,0.375) --Right of T --Flat behind sidewalk createNode() baseIndex = 0 createQuad(-16,0.15,16, 0,0,-32, 10,0,0) --Left --Curb createNode() baseIndex = 0 createQuad(-4,0,16, 0,0.15,0, 0,0,-32) --Inner left createQuad(-16,0,-16, 0,0.15,0, 0,0,32) --Outer left createQuad(-16,0,16, 0,0.15,0, 12,0,0) --Front left createQuad(-4,0,-16, 0,0.15,0, -12,0,0) --Back left --Top Right createQuad(4,0,16, 0,0.15,0, 12,0,0) --Front createQuad(16,0,12, 0,0.15,0, -12,0,0) --Back createQuad(4,0,12, 0,0.15,0, 0,0,4) --Left createQuad(16,0,16, 0,0.15,0, 0,0,-4) --Right --Bottom Right createQuad(4,0,-12, 0,0.15,0, 12,0,0) --Front createQuad(16,0,-16, 0,0.15,0, -12,0,0) --Back createQuad(4,0,-16, 0,0.15,0, 0,0,4) --Left createQuad(16,0,-12, 0,0.15,0, 0,0,-4) --Right
gpl-2.0
gastrodia/awesome
lib/awful/completion.lua
11
7193
--------------------------------------------------------------------------- --- Completion module. -- -- This module store a set of function using shell to complete commands name. -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @author Sébastien Gross &lt;seb-awesome@chezwam.org&gt; -- @copyright 2008 Julien Danjou, Sébastien Gross -- @release @AWESOME_VERSION@ -- @module awful.completion --------------------------------------------------------------------------- -- Grab environment we need local io = io local os = os local table = table local math = math local print = print local pairs = pairs local string = string local util = require("awful.util") local completion = {} -- mapping of command/completion function local bashcomp_funcs = {} local bashcomp_src = "@SYSCONFDIR@/bash_completion" --- Enable programmable bash completion in awful.completion.bash at the price of -- a slight overhead. -- @param src The bash completion source file, /etc/bash_completion by default. function completion.bashcomp_load(src) if src then bashcomp_src = src end local c, err = io.popen("/usr/bin/env bash -c 'source " .. bashcomp_src .. "; complete -p'") if c then while true do local line = c:read("*line") if not line then break end -- if a bash function is used for completion, register it if line:match(".* -F .*") then bashcomp_funcs[line:gsub(".* (%S+)$","%1")] = line:gsub(".*-F +(%S+) .*$", "%1") end end c:close() else print(err) end end local function bash_escape(str) str = str:gsub(" ", "\\ ") str = str:gsub("%[", "\\[") str = str:gsub("%]", "\\]") str = str:gsub("%(", "\\(") str = str:gsub("%)", "\\)") return str end --- Use shell completion system to complete command and filename. -- @param command The command line. -- @param cur_pos The cursor position. -- @param ncomp The element number to complete. -- @param shell The shell to use for completion (bash (default) or zsh). -- @return The new command, the new cursor position, the table of all matches. function completion.shell(command, cur_pos, ncomp, shell) local wstart = 1 local wend = 1 local words = {} local cword_index = 0 local cword_start = 0 local cword_end = 0 local i = 1 local comptype = "file" -- do nothing if we are on a letter, i.e. not at len + 1 or on a space if cur_pos ~= #command + 1 and command:sub(cur_pos, cur_pos) ~= " " then return command, cur_pos elseif #command == 0 then return command, cur_pos end while wend <= #command do wend = command:find(" ", wstart) if not wend then wend = #command + 1 end table.insert(words, command:sub(wstart, wend - 1)) if cur_pos >= wstart and cur_pos <= wend + 1 then cword_start = wstart cword_end = wend cword_index = i end wstart = wend + 1 i = i + 1 end if cword_index == 1 and not string.find(words[cword_index], "/") then comptype = "command" end local shell_cmd if shell == "zsh" or (not shell and os.getenv("SHELL"):match("zsh$")) then if comptype == "file" then -- NOTE: ${~:-"..."} turns on GLOB_SUBST, useful for expansion of -- "~/" ($HOME). ${:-"foo"} is the string "foo" as var. shell_cmd = "/usr/bin/env zsh -c 'local -a res; res=( ${~:-" .. string.format('%q', words[cword_index]) .. "}* ); " .. "print -ln -- ${res[@]}'" else -- check commands, aliases, builtins, functions and reswords shell_cmd = "/usr/bin/env zsh -c 'local -a res; ".. "res=( ".. "\"${(k)commands[@]}\" \"${(k)aliases[@]}\" \"${(k)builtins[@]}\" \"${(k)functions[@]}\" \"${(k)reswords[@]}\" ".. "${PWD}/*(:t)".. "); ".. "print -ln -- ${(M)res[@]:#" .. string.format('%q', words[cword_index]) .. "*}'" end else if bashcomp_funcs[words[1]] then -- fairly complex command with inline bash script to get the possible completions shell_cmd = "/usr/bin/env bash -c 'source " .. bashcomp_src .. "; " .. "__print_completions() { for ((i=0;i<${#COMPREPLY[*]};i++)); do echo ${COMPREPLY[i]}; done }; " .. "COMP_WORDS=(" .. command .."); COMP_LINE=\"" .. command .. "\"; " .. "COMP_COUNT=" .. cur_pos .. "; COMP_CWORD=" .. cword_index-1 .. "; " .. bashcomp_funcs[words[1]] .. "; __print_completions'" else shell_cmd = "/usr/bin/env bash -c 'compgen -A " .. comptype .. " " .. string.format('%q', words[cword_index]) .. "'" end end local c, err = io.popen(shell_cmd .. " | sort -u") local output = {} i = 0 if c then while true do local line = c:read("*line") if not line then break end if os.execute("test -d " .. string.format('%q', line)) == 0 then line = line .. "/" end table.insert(output, bash_escape(line)) end c:close() else print(err) end -- no completion, return if #output == 0 then return command, cur_pos end -- cycle while ncomp > #output do ncomp = ncomp - #output end local str = command:sub(1, cword_start - 1) .. output[ncomp] .. command:sub(cword_end) cur_pos = cword_end + #output[ncomp] + 1 return str, cur_pos, output end --- Run a generic completion. -- For this function to run properly the awful.completion.keyword table should -- be fed up with all keywords. The completion is run against these keywords. -- @param text The current text the user had typed yet. -- @param cur_pos The current cursor position. -- @param ncomp The number of yet requested completion using current text. -- @param keywords The keywords table uised for completion. -- @return The new match, the new cursor position, the table of all matches. function completion.generic(text, cur_pos, ncomp, keywords) -- The keywords table may be empty if #keywords == 0 then return text, #text + 1 end -- if no text had been typed yet, then we could start cycling around all -- keywords with out filtering and move the cursor at the end of keyword if text == nil or #text == 0 then ncomp = math.fmod(ncomp - 1, #keywords) + 1 return keywords[ncomp], #keywords[ncomp] + 2 end -- Filter out only keywords starting with text local matches = {} for _, x in pairs(keywords) do if x:sub(1, #text) == text then table.insert(matches, x) end end -- if there are no matches just leave out with the current text and position if #matches == 0 then return text, #text + 1, matches end -- cycle around all matches ncomp = math.fmod(ncomp - 1, #matches) + 1 return matches[ncomp], #matches[ncomp] + 1, matches end return completion -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
masoudre11/RaHabot
plugins/urbandictionary.lua
11
1055
local doc = [[ /urbandictionary <query> Returns a definition from Urban Dictionary. ]] local triggers = { '^/u[rban]*d[ictionary]*[@'..bot.username..']*', '^/urban[@'..bot.username..']*' } local action = function(msg) local input = msg.text:input() if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else sendReply(msg, doc) return end end local url = 'http://api.urbandictionary.com/v0/define?term=' .. URL.escape(input) local jstr, res = HTTP.request(url) if res ~= 200 then sendReply(msg, config.errors.connection) return end local jdat = JSON.decode(jstr) if jdat.result_type == "no_results" then sendReply(msg, config.errors.results) return end local message = '"' .. jdat.list[1].word .. '"\n' .. jdat.list[1].definition:trim() if string.len(jdat.list[1].example) > 0 then message = message .. '\n\nExample:\n' .. jdat.list[1].example:trim() end sendReply(msg, message) end return { action = action, triggers = triggers, doc = doc }
gpl-2.0
kin3tics/LuaTerrainGenerator
code/perlin_noise.lua
1
1783
perlinAlgo = {} perlinAlgo.noise = {} perlinAlgo.noise_width = 0 perlinAlgo.noise_height = 0 function perlinAlgo.generateNoise(width, height, frequency, octaves) perlinAlgo.noise_width = width perlinAlgo.noise_height = height for i=0,perlinAlgo.noise_height do local noise_row = {} for j=0,perlinAlgo.noise_width do local rand = math.random(1000) / 1000 table.insert(noise_row, rand) end table.insert(perlinAlgo.noise, noise_row) end local result = {} for i=0,perlinAlgo.noise_height do local row = {} for j=0,perlinAlgo.noise_width do local turb = math.floor(perlinAlgo.turbulence(i*frequency,j*frequency,octaves)) table.insert(row,turb) end table.insert(result, row) end return result end function perlinAlgo.turbulence(x, y, size) local value = 0.0 size = size * 1.0 local initial_size = size while size >= 1 do value = value + perlinAlgo.smoothNoise(x / size, y / size) * size size = size / 2.0 end return 128.0 * value / initial_size end function perlinAlgo.smoothNoise(x,y) local fractX = x - math.floor(x) local fractY = y - math.floor(y) local x1 = (math.floor(x) + perlinAlgo.noise_width) % perlinAlgo.noise_width local y1 = (math.floor(y) + perlinAlgo.noise_height) % perlinAlgo.noise_height local x2 = (x1 + perlinAlgo.noise_width - 1) % perlinAlgo.noise_width local y2 = (y1 + perlinAlgo.noise_height - 1) % perlinAlgo.noise_height local value = 0.0 --io.write (x,",",y," - ",y1,",",x1,",",y2,",",x2,"\n") value = value + fractX * fractY * perlinAlgo.noise[y1+1][x1+1] value = value + fractX * (1 - fractY) * perlinAlgo.noise[y2+1][x1+1] value = value + (1 - fractX) * fractY * perlinAlgo.noise[y1+1][x2+1] value = value + (1 - fractX) * (1 - fractY) * perlinAlgo.noise[y2+1][x2+1] return value end
gpl-3.0
liruqi/bigfoot
Interface/AddOns/BigFoot/AceLibs/Ace3/AceGUI-3.0/widgets/AceGUIWidget-Icon.lua
5
3939
--[[----------------------------------------------------------------------------- Icon Widget -------------------------------------------------------------------------------]] local Type, Version = "Icon", 21 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local select, pairs, print = select, pairs, print -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Button_OnClick(frame, button) frame.obj:Fire("OnClick", button) AceGUI:ClearFocus() end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetHeight(110) self:SetWidth(110) self:SetLabel() self:SetImage(nil) self:SetImageSize(64, 64) self:SetDisabled(false) end, -- ["OnRelease"] = nil, ["SetLabel"] = function(self, text) if text and text ~= "" then self.label:Show() self.label:SetText(text) self:SetHeight(self.image:GetHeight() + 25) else self.label:Hide() self:SetHeight(self.image:GetHeight() + 10) end end, ["SetImage"] = function(self, path, ...) local image = self.image image:SetTexture(path) if image:GetTexture() then local n = select("#", ...) if n == 4 or n == 8 then image:SetTexCoord(...) else image:SetTexCoord(0, 1, 0, 1) end end end, ["SetImageSize"] = function(self, width, height) self.image:SetWidth(width) self.image:SetHeight(height) --self.frame:SetWidth(width + 30) if self.label:IsShown() then self:SetHeight(height + 25) else self:SetHeight(height + 10) end end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.frame:Disable() self.label:SetTextColor(0.5, 0.5, 0.5) self.image:SetVertexColor(0.5, 0.5, 0.5, 0.5) else self.frame:Enable() self.label:SetTextColor(1, 1, 1) self.image:SetVertexColor(1, 1, 1, 1) end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Button", nil, UIParent) frame:Hide() frame:EnableMouse(true) frame:SetScript("OnEnter", Control_OnEnter) frame:SetScript("OnLeave", Control_OnLeave) frame:SetScript("OnClick", Button_OnClick) local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlight") label:SetPoint("BOTTOMLEFT") label:SetPoint("BOTTOMRIGHT") label:SetJustifyH("CENTER") label:SetJustifyV("TOP") label:SetHeight(18) local image = frame:CreateTexture(nil, "BACKGROUND") image:SetWidth(64) image:SetHeight(64) image:SetPoint("TOP", 0, -5) local highlight = frame:CreateTexture(nil, "HIGHLIGHT") highlight:SetAllPoints(image) highlight:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight") highlight:SetTexCoord(0, 1, 0.23, 0.77) highlight:SetBlendMode("ADD") local widget = { label = label, image = image, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end widget.SetText = function(self, ...) print("AceGUI-3.0-Icon: SetText is deprecated! Use SetLabel instead!"); self:SetLabel(...) end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
bdowning/lj-cdefdb
cdefdb-helper.lua
1
2692
#!/usr/bin/env luajit -- Copyright (C) 2014-2015 Brian Downing. MIT License. local arg = arg assert(arg[1], "Usage: "..arg[0].." <filename> ...") local cl = require("ljclang") arg[0] = nil local tu = cl.createIndex():parse(arg) if (tu == nil) then print('TU is nil') os.exit(1) end local predefined = { __gnuc_va_list = true, va_list = true, ptrdiff_t = true, size_t = true, wchar_t = true, int8_t = true, int16_t = true, int32_t = true, int64_t = true, uint8_t = true, uint16_t = true, uint32_t = true, uint64_t = true, intptr_t = true, uintptr_t = true, } local syms = { functions = { }, variables = { }, structs = { }, unions = { }, typedefs = { }, constants = { }, unemitted = 0 } local function emit_foo(kind) local to_emit = { } for sym, state in pairs(syms[kind]) do if state then table.insert(to_emit, sym) syms[kind][sym] = false end end table.sort(to_emit) if #to_emit > 0 then io.stdout:write(' '..kind..' = {\n') for _, sym in ipairs(to_emit) do io.stdout:write(" '"..sym.."',\n") end io.stdout:write(' },\n') end end local function emit() if syms.unemitted > 0 then io.stdout:write("require 'cdef' {\n") emit_foo('functions') emit_foo('variables') emit_foo('structs') emit_foo('unions') emit_foo('typedefs') emit_foo('constants') io.stdout:write("}\n") syms.unemitted = 0 end end local function add_sym(kind, sym) if sym ~= '' and syms[kind][sym] == nil then syms[kind][sym] = true syms.unemitted = syms.unemitted + 1 end end for _, stmt in ipairs(tu:cursor():children()) do if stmt:haskind("FunctionDecl") then if stmt:name() == '__emit__' then emit() else add_sym('functions', stmt:name()) end elseif stmt:haskind("VarDecl") then add_sym('variables', stmt:name()) elseif stmt:haskind("StructDecl") then add_sym('structs', stmt:name()) elseif stmt:haskind("UnionDecl") then add_sym('unions', stmt:name()) elseif stmt:haskind("TypedefDecl") then if not predefined[stmt:name()] then add_sym('typedefs', stmt:name()) end elseif stmt:haskind("EnumDecl") then for _, field in ipairs(stmt:children()) do if field:haskind("EnumConstantDecl") then add_sym('constants', field:name()) end end else print('-- unknown', stmt:kind(), stmt:name()) end end emit()
mit
ingran/balzac
custom_feeds/teltonika_luci/protocols/core/luasrc/model/cbi/admin_network/proto_dhcp_simp.lua
1
4829
--[[ 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 ut = require "luci.util" local sys = require "luci.sys" local map, section, interface, empty = ... local ifc = interface local ifname = interface:name() or "" local hostname, accept_ra, send_rs local bcast, no_gw, no_dns, dns, metric, clientid, vendorclass, macaddr, mtu local moduleproto = ut.trim(sys.exec("uci get network.ppp.proto")) hostname = section:taboption("general", Value, "hostname", translate("Hostname to send when requesting DHCP"), translate("Specify hostname which will be sent when requesting DHCP (Dynamic Host Configuration Protocol)")) hostname.placeholder = luci.sys.hostname() hostname.datatype = "hostname" if luci.model.network:has_ipv6() then local value=ut.trim(sys.exec("uci get -q system.ipv6.enable")) if tonumber(value)==1 then --accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements")) accept_ra = section:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"), translate("Enable to let accept router advertisements to locate router and learn parameters for operating local network")) accept_ra.default = accept_ra.enabled --send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations")) send_rs = section:taboption("general", Flag, "send_rs", translate("Send router solicitations"), translate("Enable to send router solicitations as response")) send_rs.default = send_rs.disabled send_rs:depends("accept_ra", "") end end bcast = section:taboption("advanced", Flag, "broadcast", translate("Use broadcast flag"), translate("Required for certain ISPs, e.g. Charter with DOCSIS 3")) bcast.default = bcast.disabled no_gw = section:taboption("advanced", Flag, "gateway", translate("Use default gateway"), translate("If unchecked, no default route is configured")) no_gw.default = no_gw.enabled function no_gw.cfgvalue(...) return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1" end function no_gw.write(self, section, value) if value == "1" then map:set(section, "gateway", nil) else map:set(section, "gateway", "0.0.0.0") end end no_dns = section:taboption("advanced", Flag, "_no_dns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS (Domain Name System) server addresses are ignored")) no_dns.default = no_dns.enabled function no_dns.cfgvalue(self, section) local addr for addr in luci.util.imatch(map:get(section, "dns")) do return self.disabled end return self.enabled end function no_dns.remove(self, section) return map:del(section, "dns") end function no_dns.write() end dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers"), translate("By entering custom DNS (Domain Name System) server the router will take care of host name resolution. You can enter multiple DNS server")) dns:depends("_no_dns", "") dns.datatype = "ipaddr" dns.cast = "string" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric"), translate("The WAN (Wide Area Network) configuration by default generates a routing table entry. With this field you can alter the metric of that entry")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("gateway", "1") clientid = section:taboption("advanced", Value, "clientid", translate("Client ID to send when requesting DHCP"), translate("Specify client ID which will be sent when requesting DHCP (Dynamic Host Configuration Protocol)")) vendorclass = section:taboption("advanced", Value, "vendorid", translate("Vendor class to send when requesting DHCP"), translate("Specify vendor class which will be sent when requesting DHCP (Dynamic Host Configuration Protocol)")) if moduleproto == "ndis" and ifname == "eth2" then --skip macoverride field else macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"), translate("Override MAC (Media Access Control) address of the WAN interface (Wide Area Network)")) macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00" macaddr.datatype = "macaddr" end mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"), translate("MTU (Maximum Transmission Unit) specifies the largest possible size of a data packet")) mtu.placeholder = "1500" mtu.datatype = "max(1500)" if empty then function bcast.cfgvalue(self, section) return self.default end if moduleproto ~= "ndis" and ifname ~= "eth2" then function macaddr.cfgvalue(self, section) return "" end end end
gpl-2.0
opticron/asterisk-testsuite-temporary
tests/apps/queues/wrapup_time/test.lua
5
4448
function manager_setup(a) local m,err = a:manager_connect() if not m then fail("error connecting to asterisk: " .. err) end login = ast.manager.action.login() if not login then fail("Couldn't create login?") end local r = m(login) if not r then fail("error logging in to the manager: " .. err) end if r["Response"] ~= "Success" then fail("error authenticating: " .. r["Message"]) end return m end function member1(event) --Userful for debugging --print("Got member1") --print("Queue: " .. tostring(event["Queue"])) --print("Uniqueid: " .. tostring(event["Uniqueid"])) --print("Channel: " .. tostring(event["Channel"])) --print("Member: " .. tostring(event["Member"])) --print("MemberName: " .. tostring(event["MemberName"])) --print("Holdtime: " .. tostring(event["Holdtime"])) --print("BridgedChannel: " .. tostring(event["BridgedChannel"])) --print("Ringtime: " .. tostring(event["Ringtime"])) if event["MemberName"] == "member1" then connectpass = true else print(event["Membername"]) end end function member2(event) --print("Got member2") --print("Queue: " .. tostring(event["Queue"])) --print("Uniqueid: " .. tostring(event["Uniqueid"])) --print("Channel: " .. tostring(event["Channel"])) --print("Member: " .. tostring(event["Member"])) --print("MemberName: " .. tostring(event["MemberName"])) --print("Holdtime: " .. tostring(event["Holdtime"])) --print("BridgedChannel: " .. tostring(event["BridgedChannel"])) --print("Ringtime: " .. tostring(event["Ringtime"])) if event["MemberName"] == "member2" then connectpass = true else print(event["Membername"]) end end function setup_ast_instance(which) local instance = ast.new() instance:load_config("configs/extensions.conf") instance:load_config("configs/" .. which .. "/queues.conf") instance:generate_manager_conf() instance:spawn() return instance end function complete_handler(event) completepass = true end function test_call(ast_instance, man, handler, exten) if handler then man:register_event("AgentConnect", handler) man:register_event("AgentComplete", complete_handler) connectpass = false completepass = false end local orig = ast.manager.action:new("Originate") orig["Channel"] = "Local/" .. exten .. "@test_context/n" orig["Application"] = "Wait" orig["Data"] = "1" local res, err = man(orig) if not res then fail("Error originating call: " .. err) end if res["Response"] ~= "Success" then if not handler then --When the handler is nil, this means we expect that no --queue members will be available to answer the call. Since --no one can answer the originated call, the originate will --fail. If it doesn't, then something went wrong. return else fail("Response failure for Originate: " .. res["Message"]) end elseif not handler then fail("Originate successful when there should have been no available queue members") end --This loop is constructed so that we will wait for the call to --finish before moving on. We'll only wait a maximum of 30 iterations --though. And since there is a 1 second sleep on each iteration, that --comes out to about 30 seconds. i = 0 while not completepass or not connectpass and i < 30 do res, err = man:pump_messages() if not res then fail("Failure while waiting for event" .. err) end man:process_events() i = i + 1; posix.sleep(1) end if not connectpass then fail("Failed to receive an AgentConnect event within 30 seconds") end if not completepass then fail("Failed to receive an AgentComplete event within 30 seconds") end man:unregister_event("AgentConnect", handler) man:unregister_event("AgentComplete", complete_handler) end instance1 = setup_ast_instance("ast1") instance2 = setup_ast_instance("ast2") man1 = manager_setup(instance1) man2 = manager_setup(instance2) test_call(instance1, man1, member1, "test1") posix.sleep(1) test_call(instance1, man1, member1, "test2") posix.sleep(1) test_call(instance1, man1, member2, "test1") posix.sleep(1) test_call(instance2, man2, member1, "test1") posix.sleep(1) test_call(instance2, man2, member2, "test2") posix.sleep(1) --On this call, since both members are unavailable, --originating a call to the queue will fail since --no one will answer test_call(instance2, man2, nil, "test1") logoff = ast.manager.action.logoff() man1(logoff) logoff = ast.manager.action.logoff() man2(logoff) instance1:term_or_kill() instance2:term_or_kill()
gpl-2.0
TeleDALAD/sg
plugins/persian_lang.lua
1
23723
print("سلام دنیا!") local LANG = 'fa' local function run(msg, matches) if permissions(msg.from.id, msg.to.id, "lang_install") then ------------------------- -- Translation version -- ------------------------- set_text(LANG, 'version', '0.1') set_text(LANG, 'versionExtended', 'نسخه ترجمه : نسخه 0.1') ------------- -- Plugins -- ------------- -- global plugins -- set_text(LANG, 'require_sudo', 'شما مالک بات نیستید.') set_text(LANG, 'require_admin', 'این پلاگین نیاز به دسترسی ادمین و یا بالا تر دارد.') set_text(LANG, 'require_mod', 'این پلاگین نیاز به دسترسی مدیر و یا بالا تر دارد.') -- Spam.lua -- set_text(LANG, 'reportUser', 'کاربر') set_text(LANG, 'reportReason', 'دلیل ریپورت') set_text(LANG, 'reportGroup', 'گروه') set_text(LANG, 'reportMessage', 'پیام') set_text(LANG, 'allowedSpamT', 'از حالا اسپم دادن در این چت آزاد است.') set_text(LANG, 'allowedSpamL', 'از حالا اسپم دادن در این سوپرگروه ازاد است.') set_text(LANG, 'notAllowedSpamT', 'اسپم دادن در این چت ممنوع می باشد.') set_text(LANG, 'notAllowedSpamL', 'اسپم دادن در این سوپرگروه ممنوع می باشد.') -- bot.lua -- set_text(LANG, 'botOn', 'من برگتشم ، بزن بریم!') set_text(LANG, 'botOff', 'دیگه کاری از دستم بر نمیاد') -- settings.lua -- set_text(LANG, 'user', 'کاربر') set_text(LANG, 'isFlooding', 'در حال فلود کردن است.') set_text(LANG, 'noStickersT', 'استفاده از هرگونه استیکر در این چت ممنوع می باشد.') set_text(LANG, 'noStickersL', 'استفاده از هرگونه استیکر در این سوپرگروه ممنوع می باشد.') set_text(LANG, 'stickersT', 'از حالا استفاده از استیکر در این چت آزاد می باشد .') set_text(LANG, 'stickersL', 'از حالا استفاده از استیکر در این سوپرگروه آزاد می باشد.') set_text(LANG, 'noGiftT', 'استفاده از تصاویر متحرک در این چت ممنوع می باشد.') set_text(LANG, 'noGiftL', 'استفاده از تصاویر متحرک در این سوپر گروه ممنوع می باشد.') set_text(LANG, 'GiftT','از حالا فرستادن تصاویر متحرک در این چت آزاد می باشد.') set_text(LANG, 'GiftL', 'از حالا فرستادن تصاویر متحرک در این سوپرگروه آزاد می باشد.') set_text(LANG, 'PhotosT', 'از حالا فرستادن تصاویر در این چت آزاد می باشد.') set_text(LANG, 'PhotosL', 'از حالا فرستادن تصاویر در این سوپرگروه آزاد می باشد.') set_text(LANG, 'noPhotos،', 'شما نمی توانید در این چت عکسی ارسال کنید.') set_text(LANG, 'noPhotosL', 'شما نمی توانید در این سوپرگروه عکسی ارسال کنید.') set_text(LANG, 'noArabicT', 'در این چت ، شما نمی توانید به زبان هایی مثل زبان عربی یا . . . صحبت کنید.') set_text(LANG, 'noArabicL', 'در این سوپرگروه، شما نمی توانید به زبان هایی مثل زبان عربی یا . . . صحبت کنید.') set_text(LANG, 'ArabicT', 'از حالا استفاده از زبان هایی همچون زبان عربی در این چت آزاد است.') set_text(LANG, 'ArabicL', 'از حالا استفاده از زبان هایی همچون زبان عربی در این سوپرگروه آزاد است.') set_text(LANG, 'audiosT', 'از حالا فرستادن فایل های صوتی در این چت آزاد است.') set_text(LANG, 'audiosL', 'از حالا فرستادن فایل های صوتی در این سوپرگروه آزاد است.') set_text(LANG, 'noAudiosT', 'فرستادن هرگونه فایل صوتی در این چت ممنوع می باشد.') set_text(LANG, 'noAudiosL', 'فرستادن هرگونه فایل صوتی در این سوپرگروه ممنوع می باشد.') set_text(LANG, 'kickmeT', 'از حالا استفاده از دستور kickme در این چت آزاد است.') set_text(LANG, 'kickmeL', 'از حالا استفاده از دستور kickme در این سوپر گروه آزاد است.') set_text(LANG, 'noKickmeT', 'شما نمی توانید از این دستور در این چت استفاده کنید.') set_text(LANG, 'noKickmeL', 'شما نمی توانید از این دستور در سوپرگروه چت استفاده کنید.') set_text(LANG, 'floodT', 'از حالا فلود کردن در این چت آزاد است.') set_text(LANG, 'floodL', 'از حالا فلود کردن در این سوپرگروه آزاد است.') set_text(LANG, 'noFloodT', 'شما نمی توانید در این چت فلود کنید.') set_text(LANG, 'noFloodL', 'شما نمی توانید در این سوپرگروه فلود کنید.') set_text(LANG, 'floodTime', 'زمان چک کردن فلود تنظیم شد به هر : ') set_text(LANG, 'floodMax', 'حداکثر پیام های فلود تنظیم شد به مقدار : ') set_text(LANG, 'gSettings', 'تنظیمات گروه') set_text(LANG, 'sSettings', 'تنظیمات سوپرگروه') set_text(LANG, 'allowed', 'امکان پذیر') set_text(LANG, 'noAllowed', 'ممنوع') set_text(LANG, 'noSet', 'تنظیم نشده') set_text(LANG, 'stickers', 'استیکر') set_text(LANG, 'links', 'لینک') set_text(LANG, 'arabic', 'زبان عربی') set_text(LANG, 'bots', 'ربات') set_text(LANG, 'gifs', 'تصاویر متحرک') set_text(LANG, 'photos', 'غکس') set_text(LANG, 'audios', 'فایل صوتی') set_text(LANG, 'kickme', 'Kickme دستور') set_text(LANG, 'spam', 'اسپم') set_text(LANG, 'gName', 'نام گروه') set_text(LANG, 'flood', 'فلود') set_text(LANG, 'language', 'زبان') set_text(LANG, 'mFlood', 'حداکثر فلود') set_text(LANG, 'tFlood', 'زمان چک کردن فلود') set_text(LANG, 'setphoto', 'تنظیم عکس گروه') set_text(LANG, 'photoSaved', 'تصویر ذخیره شد!') set_text(LANG, 'photoFailed', 'عملیات ناموفق, لطفا دوباره امتحان کنید!') set_text(LANG, 'setPhotoAborted', 'متوقف کردن عملیات تنظیم عکس...') set_text(LANG, 'sendPhoto', 'لطفا عکسی ارسال کنید.') set_text(LANG, 'linkSaved', 'لینک جدید گروه ذخیره شد.') set_text(LANG, 'groupLink', 'لینک گروه :') set_text(LANG, 'sGroupLink', 'لینک سوپرگروه :') set_text(LANG, 'noLinkSet', 'هیچ لینکی تنظیم نشده است. لطفا بوسیله #setlink [link] لینک جدیدی بسازید.') set_text(LANG, 'chatRename', 'از حالا می توانید نام گروه را تغییر دهید.') set_text(LANG, 'channelRename', 'از حالا می توانید نام چنل را تغییر دهید.') set_text(LANG, 'notChatRename', 'دیگر نمی توان نام گروه را تغییر داد.') set_text(LANG, 'notChannelRename', 'دیگر نمی توان نام چنل را تغییر داد.') set_text(LANG, 'lockMembersT', 'تعداد اعضا در این چت قفل شده است.') set_text(LANG, 'lockMembersL', 'تعداد اعضا در این چنل قفل شده است.') set_text(LANG, 'notLockMembersT', 'قفل تعداد اعضا در این چت باز شد.') set_text(LANG, 'notLockMembersL', 'قفل تعداد اعضا در این چنل باز شد.') set_text(LANG, 'langUpdated', 'زبان شما تغییر کرد به :') -- export_gban.lua -- set_text(LANG, 'accountsGban', 'اکانت به صورت سراسری بن شد.') -- giverank.lua -- set_text(LANG, 'alreadyAdmin', 'این شخص درحال حاضر ادمین است.') set_text(LANG, 'alreadyMod', 'این شخص درحال حاضر مدیر است.') set_text(LANG, 'newAdmin', 'ادمین جدید') set_text(LANG, 'newMod', 'مدیر جدید') set_text(LANG, 'nowUser', 'از حالا یک کاربر معمولی است.') set_text(LANG, 'modList', 'لیست مدیران') set_text(LANG, 'adminList', 'لیست ادامین') set_text(LANG, 'modEmpty', 'این چت هیچ مدیری ندارد.') set_text(LANG, 'adminEmpty', 'درحال حاضر هیچ شخصی ادمین نیست') -- id.lua -- set_text(LANG, 'user', 'کاربر') set_text(LANG, 'supergroupName', 'نام سوپرگروه') set_text(LANG, 'chatName', 'نام چت') set_text(LANG, 'supergroup', 'سوپرگروه') set_text(LANG, 'chat', 'چت') -- moderation.lua -- set_text(LANG, 'userUnmuted:1', 'کاربر') set_text(LANG, 'userUnmuted:2', 'توانایی چت کردن را دوباره بدست آورد.') set_text(LANG, 'userMuted:1', 'کاربر') set_text(LANG, 'userMuted:2', 'توانایی چت کردن را از دست داد.') set_text(LANG, 'kickUser:1', 'کاربر') set_text(LANG, 'kickUser:2', 'اخراج شد.') set_text(LANG, 'banUser:1', 'کاربر') set_text(LANG, 'banUser:2', 'بن شد.') set_text(LANG, 'unbanUser:1', 'کاربر') set_text(LANG, 'unbanUser:2', 'رفع بن شد.') set_text(LANG, 'gbanUser:1', 'کاربر') set_text(LANG, 'gbanUser:2', 'به صورت سراسری بن شد.') set_text(LANG, 'ungbanUser:1', 'کاربر') set_text(LANG, 'ungbanUser:2', 'به صورت سراسری رفع بن شد.') set_text(LANG, 'addUser:1', 'کاربر') set_text(LANG, 'addUser:2', 'به چت افزوده شد.') set_text(LANG, 'addUser:3', 'به چنل افزوده شد.') set_text(LANG, 'kickmeBye', 'بدرود.') -- plugins.lua -- set_text(LANG, 'plugins', 'پلاگین ها') set_text(LANG, 'installedPlugins', 'پلاگین های نصب شده.') set_text(LANG, 'pEnabled', 'فعال.') set_text(LANG, 'pDisabled', 'غیرفعال.') set_text(LANG, 'isEnabled:1', 'پلاگین') set_text(LANG, 'isEnabled:2', 'فعال است.') set_text(LANG, 'notExist:1', 'پلاگین') set_text(LANG, 'notExist:2', 'وجود ندارد.') set_text(LANG, 'notEnabled:1', 'پلاگین') set_text(LANG, 'notEnabled:2', 'فعال نیست.') set_text(LANG, 'pNotExists', 'این پلاگین وجود ندارد.') set_text(LANG, 'pDisChat:1', 'پلاگین') set_text(LANG, 'pDisChat:2', 'در این چت غیرفعال است.') set_text(LANG, 'anyDisPlugin', 'هیچ پلاگینی غیر فعال تیست.') set_text(LANG, 'anyDisPluginChat', 'هیچ پلاگینی در این چت غیر فعال نیست.') set_text(LANG, 'notDisabled', 'این پلاگین غیرفعال نیست.') set_text(LANG, 'enabledAgain:1', 'پلاگین') set_text(LANG, 'enabledAgain:2', 'دوباره فعال شد.') -- commands.lua -- set_text(LANG, 'commandsT', 'دستورات') set_text(LANG, 'errorNoPlug', 'این پلاگین وجود ندارد و یا فعال نیست.') ------------ -- Usages -- ------------ -- bot.lua -- set_text(LANG, 'bot:0', 2) set_text(LANG, 'bot:1', '#bot on: فعال کردن بات در چنل فعلی.') set_text(LANG, 'bot:2', '#bot off: غیر فعال کردن بات در چنل فعلی.') -- commands.lua -- set_text(LANG, 'commands:0', 2) set_text(LANG, 'commands:1', '#commands: نمایش دستورات تمامی پلاگین ها.') set_text(LANG, 'commands:2', '#commands [plugin]: نمایش دستورات پلاگین مورد نظر.') -- export_gban.lua -- set_text(LANG, 'export_gban:0', 2) set_text(LANG, 'export_gban:1', '#gbans installer: فرستادن لیست بن های سراسری به صورت یک فایل لوآ برای اشتراک گذاری با ربات های دیگر.') set_text(LANG, 'export_gban:2', '#gbans list: ارسال لیست بن های سراسری .') -- gban_installer.lua -- set_text(LANG, 'gban_installer:0', 1) set_text(LANG, 'gban_installer:1', '#install gbans: اضافه کردن لیست بن های سراسری به دیتابیس شما.') -- giverank.lua -- set_text(LANG, 'giverank:0', 9) set_text(LANG, 'giverank:1', '#rank admin (reply): افزودن ادمین با ریپلی.') set_text(LANG, 'giverank:2', '#rank admin <user_id>/<user_name>: افزودن ادمین بوسیله یوزرنیم و یا آی دی.') set_text(LANG, 'giverank:3', '#rank mod (reply): افزودن مدیر با ریپلی.') set_text(LANG, 'giverank:4', '#rank mod <user_id>/<user_name>: افزودن مدیر بوسیله یوزرنیم و یا آی دی.') set_text(LANG, 'giverank:5', '#rank guest (reply): گرفتن مقام ادمین ادمین با ریپلی.') set_text(LANG, 'giverank:6', '#rank guest <user_id>/<user_name>: گرفتن مقام ادمین ادمین بوسیله یوزرنیم و یا آی دی.') set_text(LANG, 'giverank:7', '#admins: لیست تمامی ادامین.') set_text(LANG, 'giverank:8', '#mods: لیست تمامی مدیران.') set_text(LANG, 'giverank:9', '#members: لیست تمامی اعضای چنل.') -- id.lua -- set_text(LANG, 'id:0', 6) set_text(LANG, 'id:1', '#id: نشان دادن ای دی شما و یا آی دی چنلی که در حال حاضر در آن هستید.') set_text(LANG, 'id:2', '#ids chat: نشان دادن آی دی چتی که در حال حاضر در آن هستید.') set_text(LANG, 'id:3', '#ids channel: نشان دادن آی دی چنلی که در حال حاضر در آن هستید.') set_text(LANG, 'id:4', '#id <user_name>: نشان دادن آی دی شخص مورد نظر شما.') set_text(LANG, 'id:5', '#whois <user_id>/<user_name>: نشان دادن یوزرنیم شخص مورد نظر شما.') set_text(LANG, 'id:6', '#whois (reply): نشان دادن آی دی شخص مورد نظر شما با ریپلی.') -- moderation.lua -- set_text(LANG, 'moderation:0', 18) set_text(LANG, 'moderation:1', '#add: با ریپلی کردن یک پیام شخص را به سوپرگروه یا گروه مورد نظر بی افزایید.') set_text(LANG, 'moderation:2', '#add <id>/<username>: افزودن شخصی به وسیله آی دی و یا یوزرنیم به سوپرگروه یا گروه.') set_text(LANG, 'moderation:3', '#kick: با ریپلی کردن یک پیام, شخص را از گروه و یا سوپر گروه اخراج کنید.') set_text(LANG, 'moderation:4', '#kick <id>/<username>: می توانید با استفاده از آی دی و یا یوزرنیم ، شخصی را از گروه اخراج کنید.') set_text(LANG, 'moderation:5', '#kickme: خودتان را از گروه اخراج کنید.') set_text(LANG, 'moderation:6', '#ban: با ریپلی کردن پیامی از کاربر ، شخصی را از گروه اخراج و از ورود دوباره به گروه محروم کنید.') set_text(LANG, 'moderation:7', '#ban <id>/<username>: بوسیله آی دی و یا یوزرنیم ، شخصی را از گروه اخراج و از ورود دوباره به گروه محروم کنید.') set_text(LANG, 'moderation:8', '#unban: با ریپلی کردن پیامی از کاربر, کاربر را در سوپرگروه و یا گروه رفع محرومیت کنید.') set_text(LANG, 'moderation:9', '#unban <id>/<username>: به وسیله آی دی و یا یوزرنیم ، شخصی را از گروه رفع ممنوعیت کنید.') set_text(LANG, 'moderation:10', '#gban: با ریپلی کردن پیامی از کاربر, شخصی را از تمامی گروه ها و سوپرگروه ها اخراج و محروم کنید.') set_text(LANG, 'moderation:11', '#gban <id>/<username>: بوسیله آی دی و یوزرنیم ، شخصی را اخراج و از ورود دوباره به تمامی گروه ها و سوپرگروه های خود محروم کنید.') set_text(LANG, 'moderation:12', '#ungban: با ریپلی کردن پیامی از کاربر, کاربر را از تمامی گروه ها و سوپرگروه ها رفع محرومیت کنید.') set_text(LANG, 'moderation:13', '#ungban <id>/<username>: بوسیله آی دی و یا یوزرنیم ، کاربر را از تمامی سوپرگروه ها و گروه ها رفع محرومیت کنید.') set_text(LANG, 'moderation:14', '#mute: با ریپلی کردن پیامی از کاربر ، شخصی را از فرستادن پیام در این سوپرگروه محروم کرده و تمامی پیام هایش را پاک می کند.') set_text(LANG, 'moderation:15', '#mute <id>/<username>: بوسیله آی دی و یا یوزرنیم ، شخصی را از فرستادن پیام در این سوپرگروه محروم کرده و تمامی پیام هایش را پاک می کند.') set_text(LANG, 'moderation:16', '#unmute: با ریپلی کردن پیامی از کاربر, کاربر را از محرومیت ارسال پیام خارج کنید .') set_text(LANG, 'moderation:17', '#unmute <id>/<username>: بوسیله آی دی و یا یوزرنیم کاربر ، کاربر را از محرومیت ارسال پیام خارج کنید.') set_text(LANG, 'moderation:18', '#rem: با ریپلی کردن پیامی از کاربر, آن پیام حذف می شود.') -- settings.lua -- set_text(LANG, 'settings:0', 19) set_text(LANG, 'settings:1', '#settings stickers enable/disable: وقتی فعال باشد ، ربات تمامی استکیر هارا پاک خواهد کرد.') set_text(LANG, 'settings:2', '#settings links enable/disable: وقتی فعال باشد ، ربات تمامی لینک هارا پاک خواهد کرد.') set_text(LANG, 'settings:3', '#settings arabic enable/disabl: وقتی فعال باشد ، ربات تمامی پیام های فارسی و یا عربی را پاک خواهد کرد..') set_text(LANG, 'settings:4', '#settings bots enable/disable: وقتی فعال باشد ، ربات اگر کسی رباتی را به گروه بیفزاید ، ربات را اخراج خواهد کرد.') set_text(LANG, 'settings:5', '#settings gifs enable/disable: وقتی فعال باشد ، ربات تمامی تصاویر متحرک را پاک خواهد کرد.') set_text(LANG, 'settings:6', '#settings photos enable/disable: وقتی فعال باشد ، ربات تمامی تصاویر را پاک خواهد کرد.') set_text(LANG, 'settings:7', '#settings audios enable/disable: وقتی فعال باشد ، ربات تمامی فایل های صوتی را پاک خواهد کرد.') set_text(LANG, 'settings:8', '#settings kickme enable/disable: وقتی فعال باشد ، ربات کاربران دیگر نمی توانند خودشان خودشان را اخراج کنند.') set_text(LANG, 'settings:9', '#settings spam enable/disable: وقتی فعال باشد ، ربات تمامی اسپم هارا پاک خواهد کرد.') set_text(LANG, 'settings:10', '#settings setphoto enable/disable: وقتی فعال باشد ، ربات اگر شخصی عکس گروه را تغییر دهد ، عکس قبلی گروه را بازگردانی و تنظیم می کند.') set_text(LANG, 'settings:11', '#settings setname enable/disable: وقتی فعال باشد ، ربات اگر کسی نام گروه را تغییر دهد ، نام گروه را بازگردانی و تنظیم خواهد کرد..') set_text(LANG, 'settings:12', '#settings lockmember enable/disable: وقتی فعال باشد ، ربات ربات هر شخصی را که وارد گروه شود را اخراج خواهد کرد.') set_text(LANG, 'settings:13', '#settings floodtime <ثانیه>: تنظیم مقدار زمانی که بات فلود را بررسی می کند.') set_text(LANG, 'settings:14', '#settings maxflood <ثانیه>: حداثکر تعداد فلود را تنظیم می کند.') set_text(LANG, 'settings:15', '#setname <group title>: نام گروه را تغییر می دهد.') set_text(LANG, 'settings:16', '#setphoto <then send photo>: تصویر گروه را تغییر می دهد.') set_text(LANG, 'settings:17', '#lang <language (en, es...)>: زبان ربات را تغییر می دهد.') set_text(LANG, 'settings:18', '#setlink <link>: لینک گروه را ذخیره می کند.') set_text(LANG, 'settings:19', '#link: لینک گروه را ارسال می کند.') -- plugins.lua -- set_text(LANG, 'plugins:0', 4) set_text(LANG, 'plugins:1', '#plugins: لیست تمامی پلاگین هارا نشان می دهد.') set_text(LANG, 'plugins:2', '#plugins <enable>/<disable> [plugin]: فعال/غیرفعال کردن پلاگین مورد نظر.') set_text(LANG, 'plugins:3', '#plugins <enable>/<disable> [plugin] chat: فعال ، غیر فعال کردن پلاگین مورد نظر در گروه و یا سوپرگروه کنونی.') set_text(LANG, 'plugins:4', '#plugins reload: بازنگری پلاگین ها.') -- version.lua -- set_text(LANG, 'version:0', 1) set_text(LANG, 'version:1', '#version: نشان دادن نسخه ربات.') -- rules.lua -- set_text(LANG, 'rules:0', 1) set_text(LANG, 'rules:1', '#rules: نشان دادن قوانین چنل.') if matches[1] == 'install' then return 'ℹ️ زبان شیرین فارسی (پارسی) با موفقیت بر روی ربات شما نصب شد.' elseif matches[1] == 'update' then return 'ℹ️ زبان شیرین فارسی(پارسی) با موفقیت بروزرسانی شد.' end else return "🚫 این پلاگین نیاز به دسترسی مالک ربات دارد." end end return { patterns = { '(install) (persian_lang)$', '(update) (persian_lang)$' }, run = run }
gpl-2.0
br-lemes/stuff
smartlan/socket/http.lua
121
12193
----------------------------------------------------------------------------- -- HTTP/1.1 client support for the Lua language. -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: http.lua,v 1.71 2007/10/13 23:55:20 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ------------------------------------------------------------------------------- local socket = require("socket") local url = require("socket.url") local ltn12 = require("ltn12") local mime = require("mime") local string = require("string") local base = _G local table = require("table") module("socket.http") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- connection timeout in seconds TIMEOUT = 60 -- default port for document retrieval PORT = 80 -- user agent field sent in request USERAGENT = socket._VERSION ----------------------------------------------------------------------------- -- Reads MIME headers from a connection, unfolding where needed ----------------------------------------------------------------------------- local function receiveheaders(sock, headers) local line, name, value, err headers = headers or {} -- get first line line, err = sock:receive() if err then return nil, err end -- headers go until a blank line is found while line ~= "" do -- get field-name and value name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)")) if not (name and value) then return nil, "malformed reponse headers" end name = string.lower(name) -- get next line (value might be folded) line, err = sock:receive() if err then return nil, err end -- unfold any folded values while string.find(line, "^%s") do value = value .. line line = sock:receive() if err then return nil, err end end -- save pair in table if headers[name] then headers[name] = headers[name] .. ", " .. value else headers[name] = value end end return headers end ----------------------------------------------------------------------------- -- Extra sources and sinks ----------------------------------------------------------------------------- socket.sourcet["http-chunked"] = function(sock, headers) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() -- get chunk size, skip extention local line, err = sock:receive() if err then return nil, err end local size = base.tonumber(string.gsub(line, ";.*", ""), 16) if not size then return nil, "invalid chunk size" end -- was it the last chunk? if size > 0 then -- if not, get chunk and skip terminating CRLF local chunk, err, part = sock:receive(size) if chunk then sock:receive() end return chunk, err else -- if it was, read trailers into headers table headers, err = receiveheaders(sock, headers) if not headers then return nil, err end end end }) end socket.sinkt["http-chunked"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if not chunk then return sock:send("0\r\n\r\n") end local size = string.format("%X\r\n", string.len(chunk)) return sock:send(size .. chunk .. "\r\n") end }) end ----------------------------------------------------------------------------- -- Low level HTTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function open(host, port, create) -- create socket with user connect function, or with default local c = socket.try((create or socket.tcp)()) local h = base.setmetatable({ c = c }, metat) -- create finalized try h.try = socket.newtry(function() h:close() end) -- set timeout before connecting h.try(c:settimeout(TIMEOUT)) h.try(c:connect(host, port or PORT)) -- here everything worked return h end function metat.__index:sendrequestline(method, uri) local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri) return self.try(self.c:send(reqline)) end function metat.__index:sendheaders(headers) local h = "\r\n" for i, v in base.pairs(headers) do h = i .. ": " .. v .. "\r\n" .. h end self.try(self.c:send(h)) return 1 end function metat.__index:sendbody(headers, source, step) source = source or ltn12.source.empty() step = step or ltn12.pump.step -- if we don't know the size in advance, send chunked and hope for the best local mode = "http-chunked" if headers["content-length"] then mode = "keep-open" end return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step)) end function metat.__index:receivestatusline() local status = self.try(self.c:receive(5)) -- identify HTTP/0.9 responses, which do not contain a status line -- this is just a heuristic, but is what the RFC recommends if status ~= "HTTP/" then return nil, status end -- otherwise proceed reading a status line status = self.try(self.c:receive("*l", status)) local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)")) return self.try(base.tonumber(code), status) end function metat.__index:receiveheaders() return self.try(receiveheaders(self.c)) end function metat.__index:receivebody(headers, sink, step) sink = sink or ltn12.sink.null() step = step or ltn12.pump.step local length = base.tonumber(headers["content-length"]) local t = headers["transfer-encoding"] -- shortcut local mode = "default" -- connection close if t and t ~= "identity" then mode = "http-chunked" elseif base.tonumber(headers["content-length"]) then mode = "by-length" end return self.try(ltn12.pump.all(socket.source(mode, self.c, length), sink, step)) end function metat.__index:receive09body(status, sink, step) local source = ltn12.source.rewind(socket.source("until-closed", self.c)) source(status) return self.try(ltn12.pump.all(source, sink, step)) end function metat.__index:close() return self.c:close() end ----------------------------------------------------------------------------- -- High level HTTP API ----------------------------------------------------------------------------- local function adjusturi(reqt) local u = reqt -- if there is a proxy, we need the full url. otherwise, just a part. if not reqt.proxy and not PROXY then u = { path = socket.try(reqt.path, "invalid path 'nil'"), params = reqt.params, query = reqt.query, fragment = reqt.fragment } end return url.build(u) end local function adjustproxy(reqt) local proxy = reqt.proxy or PROXY if proxy then proxy = url.parse(proxy) return proxy.host, proxy.port or 3128 else return reqt.host, reqt.port end end local function adjustheaders(reqt) -- default headers local lower = { ["user-agent"] = USERAGENT, ["host"] = reqt.host, ["connection"] = "close, TE", ["te"] = "trailers" } -- if we have authentication information, pass it along if reqt.user and reqt.password then lower["authorization"] = "Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password)) end -- override with user headers for i,v in base.pairs(reqt.headers or lower) do lower[string.lower(i)] = v end return lower end -- default url parts local default = { host = "", port = PORT, path ="/", scheme = "http" } local function adjustrequest(reqt) -- parse url if provided local nreqt = reqt.url and url.parse(reqt.url, default) or {} -- explicit components override url for i,v in base.pairs(reqt) do nreqt[i] = v end if nreqt.port == "" then nreqt.port = 80 end socket.try(nreqt.host and nreqt.host ~= "", "invalid host '" .. base.tostring(nreqt.host) .. "'") -- compute uri if user hasn't overriden nreqt.uri = reqt.uri or adjusturi(nreqt) -- ajust host and port if there is a proxy nreqt.host, nreqt.port = adjustproxy(nreqt) -- adjust headers in request nreqt.headers = adjustheaders(nreqt) return nreqt end local function shouldredirect(reqt, code, headers) return headers.location and string.gsub(headers.location, "%s", "") ~= "" and (reqt.redirect ~= false) and (code == 301 or code == 302) and (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD") and (not reqt.nredirects or reqt.nredirects < 5) end local function shouldreceivebody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end -- forward declarations local trequest, tredirect function tredirect(reqt, location) local result, code, headers, status = trequest { -- the RFC says the redirect URL has to be absolute, but some -- servers do not respect that url = url.absolute(reqt.url, location), source = reqt.source, sink = reqt.sink, headers = reqt.headers, proxy = reqt.proxy, nredirects = (reqt.nredirects or 0) + 1, create = reqt.create } -- pass location header back as a hint we redirected headers = headers or {} headers.location = headers.location or location return result, code, headers, status end function trequest(reqt) -- we loop until we get what we want, or -- until we are sure there is no way to get it local nreqt = adjustrequest(reqt) local h = open(nreqt.host, nreqt.port, nreqt.create) -- send request line and headers h:sendrequestline(nreqt.method, nreqt.uri) h:sendheaders(nreqt.headers) -- if there is a body, send it if nreqt.source then h:sendbody(nreqt.headers, nreqt.source, nreqt.step) end local code, status = h:receivestatusline() -- if it is an HTTP/0.9 server, simply get the body and we are done if not code then h:receive09body(status, nreqt.sink, nreqt.step) return 1, 200 end local headers -- ignore any 100-continue messages while code == 100 do headers = h:receiveheaders() code, status = h:receivestatusline() end headers = h:receiveheaders() -- at this point we should have a honest reply from the server -- we can't redirect if we already used the source, so we report the error if shouldredirect(nreqt, code, headers) and not nreqt.source then h:close() return tredirect(reqt, headers.location) end -- here we are finally done if shouldreceivebody(nreqt, code) then h:receivebody(headers, nreqt.sink, nreqt.step) end h:close() return 1, code, headers, status end local function srequest(u, b) local t = {} local reqt = { url = u, sink = ltn12.sink.table(t) } if b then reqt.source = ltn12.source.string(b) reqt.headers = { ["content-length"] = string.len(b), ["content-type"] = "application/x-www-form-urlencoded" } reqt.method = "POST" end local code, headers, status = socket.skip(1, trequest(reqt)) return table.concat(t), code, headers, status end request = socket.protect(function(reqt, body) if base.type(reqt) == "string" then return srequest(reqt, body) else return trequest(reqt) end end)
mit
TechAtNYU/wiki
extensions/Scribunto/engines/LuaCommon/lualib/package.lua
1
3811
--[[ -- A package library similar to the one that comes with Lua 5.1, but without -- the local filesystem access. Based on Compat-5.1 which comes with the -- following license notice: -- -- Copyright © 2004-2006 The Kepler Project. -- -- 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 assert, error, ipairs, setmetatable, type = assert, error, ipairs, setmetatable, type local format = string.format -- -- avoid overwriting the package table if it's already there -- package = package or {} local _PACKAGE = package package.loaded = package.loaded or {} package.loaded.debug = debug package.loaded.string = string package.loaded.math = math package.loaded.io = io package.loaded.os = os package.loaded.table = table package.loaded._G = _G package.loaded.coroutine = coroutine package.loaded.package = package local _LOADED = package.loaded -- -- avoid overwriting the package.preload table if it's already there -- package.preload = package.preload or {} local _PRELOAD = package.preload -- -- check whether library is already loaded -- local function loader_preload (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) assert (type(_PRELOAD) == "table", "`package.preload' must be a table") return _PRELOAD[name] end -- create `loaders' table package.loaders = package.loaders or { loader_preload } local _LOADERS = package.loaders -- -- iterate over available loaders -- local function load (name, loaders) -- iterate over available loaders assert (type (loaders) == "table", "`package.loaders' must be a table") for i, loader in ipairs (loaders) do local f = loader (name) if f then return f end end error (format ("module `%s' not found", name)) end -- sentinel local sentinel = function () end -- -- require -- function _G.require (modname) assert (type(modname) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(modname))) local p = _LOADED[modname] if p then -- is it there? if p == sentinel then error (format ("loop or previous error loading module '%s'", modname)) end return p -- package is already loaded end local init = load (modname, _LOADERS) _LOADED[modname] = sentinel local actual_arg = _G.arg _G.arg = { modname } local res = init (modname) if res then _LOADED[modname] = res end _G.arg = actual_arg if _LOADED[modname] == sentinel then _LOADED[modname] = true end return _LOADED[modname] end -- -- package.seeall function -- function _PACKAGE.seeall (module) local t = type(module) assert (t == "table", "bad argument #1 to package.seeall (table expected, got "..t..")") local meta = getmetatable (module) if not meta then meta = {} setmetatable (module, meta) end meta.__index = _G end
gpl-2.0
shiprabehera/kong
spec/03-plugins/04-file-log/01-log_spec.lua
2
3252
local cjson = require "cjson" local utils = require "kong.tools.utils" local helpers = require "spec.helpers" local pl_path = require "pl.path" local pl_file = require "pl.file" local pl_stringx = require "pl.stringx" local FILE_LOG_PATH = os.tmpname() describe("Plugin: file-log (log)", function() local client setup(function() helpers.run_migrations() local api1 = assert(helpers.dao.apis:insert { name = "api-1", hosts = { "file_logging.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { api_id = api1.id, name = "file-log", config = { path = FILE_LOG_PATH, reopen = true, } }) assert(helpers.start_kong()) end) teardown(function() helpers.stop_kong() end) before_each(function() client = helpers.proxy_client() os.remove(FILE_LOG_PATH) end) after_each(function() if client then client:close() end os.remove(FILE_LOG_PATH) end) it("logs to file", function() local uuid = utils.random_string() -- Making the request local res = assert(client:send({ method = "GET", path = "/status/200", headers = { ["file-log-uuid"] = uuid, ["Host"] = "file_logging.com" } })) assert.res_status(200, res) helpers.wait_until(function() return pl_path.exists(FILE_LOG_PATH) and pl_path.getsize(FILE_LOG_PATH) > 0 end, 10) local file_log = pl_file.read(FILE_LOG_PATH) local log_message = cjson.decode(pl_stringx.strip(file_log)) assert.same("127.0.0.1", log_message.client_ip) assert.same(uuid, log_message.request.headers["file-log-uuid"]) end) it("reopens file on each request", function() local uuid1 = utils.uuid() -- Making the request local res = assert(client:send({ method = "GET", path = "/status/200", headers = { ["file-log-uuid"] = uuid1, ["Host"] = "file_logging.com" } })) assert.res_status(200, res) helpers.wait_until(function() return pl_path.exists(FILE_LOG_PATH) and pl_path.getsize(FILE_LOG_PATH) > 0 end, 10) -- remove the file to see whether it gets recreated os.remove(FILE_LOG_PATH) -- Making the next request local uuid2 = utils.uuid() local res = assert(client:send({ method = "GET", path = "/status/200", headers = { ["file-log-uuid"] = uuid2, ["Host"] = "file_logging.com" } })) assert.res_status(200, res) local uuid3 = utils.uuid() local res = assert(client:send({ method = "GET", path = "/status/200", headers = { ["file-log-uuid"] = uuid3, ["Host"] = "file_logging.com" } })) assert.res_status(200, res) helpers.wait_until(function() return pl_path.exists(FILE_LOG_PATH) and pl_path.getsize(FILE_LOG_PATH) > 0 end, 10) local file_log, err = pl_file.read(FILE_LOG_PATH) assert.is_nil(err) assert(not file_log:find(uuid1, nil, true), "did not expected 1st request in logfile") assert(file_log:find(uuid2, nil, true), "expected 2nd request in logfile") assert(file_log:find(uuid3, nil, true), "expected 3rd request in logfile") end) end)
apache-2.0
Xusine1131/QSanguosha-DGAH
lua/sgs_ex.lua
1
25195
-- this script file defines all functions written by Lua -- packages function sgs.CreateLuaPackage(spec) --扩展包名称 local name = spec.name assert(type(name) == "string") --扩展包类型 local pack_type = spec.type or sgs.Package_GeneralPack assert(type(pack_type) == "number") --创建扩展包 local extension = sgs.Package(name, pack_type) --名称翻译 local translation = spec.translation if type(translation) == "string" then sgs.AddTranslationEntry(name, translation) end --AI文件 local ai = spec.ai if type(ai) == "string" then extension:setAIFilePath(string.format("extension/%s", ai)) end return extension end -- characters function sgs.CreateLuaGeneral(spec) --武将姓名 local name = spec.name assert(type(name) == "string") --真实姓名 local real_name = spec.real_name or name assert(type(real_name) == "string") --姓名翻译 local translation = spec.translation if type(translation) == "string" then sgs.AddTranslationEntry(name, translation) end --武将显示名称 local display_name = spec.display_name if type(display_name) == "string" then sgs.AddTranslationEntry(string.format("&%s", name), display_name) end --武将称号 local nick_name = spec.nick_name if type(nick_name) == "string" then sgs.AddTranslationEntry(string.format("#%s", name), nick_name) end --设计者 local designer = spec.designer if type(designer) == "string" then sgs.AddTranslationEntry(string.format("designer:%s", name), designer) end --配音人员 local cv = spec.cv if type(cv) == "string" then sgs.AddTranslationEntry(string.format("cv:%s", name), cv) end --画师 local illustrator = spec.illustrator if type(illustrator) == "string" then sgs.AddTranslationEntry(string.format("illustrator:%s", name), illustrator) end --所在扩展包 local pack = spec.add_to_package --势力 local kingdom = spec.kingdom assert(type(kingdom) == "string") --性别是否为男性 local male = ( spec.male == nil ) and true or spec.male assert(type(male) == "boolean") --体力上限 local maxhp = spec.max_hp or spec.maxhp or 4 assert(type(maxhp) == "number" or type(maxhp) == "string") --是否隐藏 local is_hidden = spec.hidden or false assert(type(is_hidden) == "boolean") --是否完全隐藏 local never_shown = spec.never_shown or false assert(type(never_shown) == "boolean") --创建武将 local general = nil if type(pack) == "string" then pack = sgs.Sanguosha:getPackage(pack) end if type(pack) == "userdata" and pack:inherits("Package") then general = sgs.General(pack, name, kingdom, maxhp, male, is_hidden, never_shown) else general = sgs.General(name, kingdom, maxhp, male, is_hidden, never_shown) end if name ~= real_name then general:setRealName(real_name) end --性别 local sex = spec.sex if type(sex) == "number" and sex >= 0 and sex < 4 then general:setGender(sex) end --在“闯关模式”中的序号 local order = spec.order if type(order) == "number" and order > 0 and order <= 10 then general:setOrder(order) end --AI文件 local AI = spec.ai if type(AI) == "string" then general:setAIPath(AI) end --配音文件夹 local audio = spec.audio if type(audio) == "string" then if string.sub(audio, -1) == "/" then audio = string.sub(audio, 1, -2) end general:setAudioPath(audio) end --武将阵亡台词 local last_word = spec.last_word if type(last_word) == "string" then sgs.AddTranslationEntry(string.format("~%s", name), last_word) end --武将卡牌文件 local card = spec.card if type(card) == "string" then general:setCardPath(card) end --武将头像文件 local avatar = spec.avatar if type(avatar) == "string" then general:setAvatarPath(avatar) end --武将全身像文件 local full = spec.full if type(full) == "string" then general:setFullSkinPath(full) end return general end -- dummy skills function sgs.CreateDummySkill(spec) assert(type(spec.name) == "string") return sgs.LuaDummySkill(spec.name) end -- trigger skills function sgs.CreateTriggerSkill(spec) local name = spec.name assert(type(name) == "string") if string.sub(name, -1, 1) == "$" then return sgs.LuaDummySkill(name) end local vs_skill = spec.view_as_skill if vs_skill then if vs_skill:inherits("DummySkill") or string.sub(vs_skill:objectName(), -1, 1) == "$" then return sgs.LuaDummySkill(name) end end assert(type(spec.on_trigger) == "function") if spec.frequency then assert(type(spec.frequency) == "number") end if spec.limit_mark then assert(type(spec.limit_mark) == "string") end local frequency = spec.frequency or sgs.Skill_NotFrequent local limit_mark = spec.limit_mark or "" local skill = sgs.LuaTriggerSkill(name, frequency, limit_mark) if type(spec.guhuo_type) == "string" and spec.guhuo_type ~= "" then skill:setGuhuoDialog(guhuo_type) end if type(spec.events) == "number" then skill:addEvent(spec.events) elseif type(spec.events) == "table" then for _, event in ipairs(spec.events) do skill:addEvent(event) end end if type(spec.global) == "boolean" then skill:setGlobal(spec.global) end if vs_skill then skill:setViewAsSkill(vs_skill) end skill.on_trigger = spec.on_trigger if spec.can_trigger then skill.can_trigger = spec.can_trigger end if type(spec.priority) == "number" then skill.priority = spec.priority elseif type(spec.priority) == "table" then for triggerEvent, priority in pairs(spec.priority) do skill:insertPriorityTable(triggerEvent, priority) end end if type(dynamic_frequency) == "function" then skill.dynamic_frequency = spec.dynamic_frequency end return skill end function sgs.CreateProhibitSkill(spec) local name = spec.name assert(type(name) == "string") if string.sub(name, -1, 1) == "$" then return sgs.LuaDummySkill(name) end assert(type(spec.is_prohibited) == "function") local skill = sgs.LuaProhibitSkill(name) skill.is_prohibited = spec.is_prohibited return skill end function sgs.CreateFilterSkill(spec) local name = spec.name assert(type(name) == "string") if string.sub(name, -1, 1) == "$" then return sgs.LuaDummySkill(name) end assert(type(spec.view_filter) == "function") assert(type(spec.view_as) == "function") local skill = sgs.LuaFilterSkill(name) skill.view_filter = spec.view_filter skill.view_as = spec.view_as return skill end function sgs.CreateDistanceSkill(spec) local name = spec.name assert(type(name) == "string") if string.sub(name, -1, 1) == "$" then return sgs.LuaDummySkill(name) end assert(type(spec.correct_func) == "function") local skill = sgs.LuaDistanceSkill(name) skill.correct_func = spec.correct_func return skill end function sgs.CreateMaxCardsSkill(spec) local name = spec.name assert(type(name) == "string") if string.sub(name, -1, 1) == "$" then return sgs.LuaDummySkill(name) end assert(type(spec.extra_func) == "function" or type(spec.fixed_func) == "function") local skill = sgs.LuaMaxCardsSkill(name) if spec.extra_func then skill.extra_func = spec.extra_func else skill.fixed_func = spec.fixed_func end return skill end function sgs.CreateTargetModSkill(spec) local name = spec.name assert(type(name) == "string") if string.sub(name, -1, 1) == "$" then return sgs.LuaDummySkill(name) end assert(type(spec.residue_func) == "function" or type(spec.distance_limit_func) == "function" or type(spec.extra_target_func) == "function") if spec.pattern then assert(type(spec.pattern) == "string") end local skill = sgs.LuaTargetModSkill(name, spec.pattern or "Slash") if spec.residue_func then skill.residue_func = spec.residue_func end if spec.distance_limit_func then skill.distance_limit_func = spec.distance_limit_func end if spec.extra_target_func then skill.extra_target_func = spec.extra_target_func end return skill end function sgs.CreateInvaliditySkill(spec) local name = spec.name assert(type(name) == "string") if string.sub(name, -1, 1) == "$" then return sgs.LuaDummySkill(name) end assert(type(spec.skill_valid) == "function") local skill = sgs.LuaInvaliditySkill(name) skill.skill_valid = spec.skill_valid return skill end function sgs.CreateAttackRangeSkill(spec) local name = spec.name assert(type(name) == "string") if string.sub(name, -1, 1) == "$" then return sgs.LuaDummySkill(name) end assert(type(spec.extra_func) == "function" or type(spec.fixed.func) == "function") local skill = sgs.LuaAttackRangeSkill(spec.name) if spec.extra_func then skill.extra_func = spec.extra_func or 0 end if spec.fixed_func then skill.fixed_func = spec.fixed_func or 0 end return skill end function sgs.CreateMasochismSkill(spec) assert(type(spec.on_damaged) == "function") spec.events = sgs.Damaged function spec.on_trigger(skill, event, player, data) local damage = data:toDamage() spec.on_damaged(skill, player, damage) return false end return sgs.CreateTriggerSkill(spec) end function sgs.CreatePhaseChangeSkill(spec) assert(type(spec.on_phasechange) == "function") spec.events = sgs.EventPhaseStart function spec.on_trigger(skill, event, player, data) return spec.on_phasechange(skill, player) end return sgs.CreateTriggerSkill(spec) end function sgs.CreateDrawCardsSkill(spec) assert(type(spec.draw_num_func) == "function") if not spec.is_initial then spec.events = sgs.DrawNCards else spec.events = sgs.DrawInitialCards end function spec.on_trigger(skill, event, player, data) local n = data:toInt() local nn = spec.draw_num_func(skill, player, n) data:setValue(nn) return false end return sgs.CreateTriggerSkill(spec) end function sgs.CreateGameStartSkill(spec) assert(type(spec.on_gamestart) == "function") spec.events = sgs.GameStart function spec.on_trigger(skill, event, player, data) spec.on_gamestart(skill, player) return false end return sgs.CreateTriggerSkill(spec) end -------------------------------------------- -- skill cards function sgs.CreateSkillCard(spec) assert(spec.name) if spec.skill_name then assert(type(spec.skill_name) == "string") end local card = sgs.LuaSkillCard(spec.name, spec.skill_name) if type(spec.target_fixed) == "boolean" then card:setTargetFixed(spec.target_fixed) end if type(spec.will_throw) == "boolean" then card:setWillThrow(spec.will_throw) end if type(spec.can_recast) == "boolean" then card:setCanRecast(spec.can_recast) end if type(spec.handling_method) == "number" then card:setHandlingMethod(spec.handling_method) end if type(spec.mute) == "boolean" then card:setMute(spec.mute) end if type(spec.filter) == "function" then function card:filter(...) local result,vote = spec.filter(self,...) if type(result) == "boolean" and type(vote) == "number" then return result,vote elseif type(result) == "boolean" and vote == nil then if result then vote = 1 else vote = 0 end return result,vote elseif type(result) == "number" then return result > 0,result else return false,0 end end end card.feasible = spec.feasible card.about_to_use = spec.about_to_use card.on_use = spec.on_use card.on_effect = spec.on_effect card.on_validate = spec.on_validate card.on_validate_in_response = spec.on_validate_in_response return card end function sgs.CreateBasicCard(spec) assert(type(spec.name) == "string" or type(spec.class_name) == "string") if not spec.name then spec.name = spec.class_name elseif not spec.class_name then spec.class_name = spec.name end if spec.suit then assert(type(spec.suit) == "number") end if spec.number then assert(type(spec.number) == "number") end if spec.subtype then assert(type(spec.subtype) == "string") end local card = sgs.LuaBasicCard(spec.suit or sgs.Card_NoSuit, spec.number or 0, spec.name, spec.class_name, spec.subtype or "BasicCard") if type(spec.target_fixed) == "boolean" then card:setTargetFixed(spec.target_fixed) end if type(spec.can_recast) == "boolean" then card:setCanRecast(spec.can_recast) end card.filter = spec.filter card.feasible = spec.feasible card.available = spec.available card.about_to_use = spec.about_to_use card.on_use = spec.on_use card.on_effect = spec.on_effect return card end -- ============================================ -- default functions for Trick cards function isAvailable_AOE(self, player) local canUse = false local players = player:getSiblings() for _, p in sgs.qlist(players) do if p:isDead() or player:isProhibited(p, self) then continue end canUse = true break end return canUse and self:cardIsAvailable(player) end function onUse_AOE(self, room, card_use) local source = card_use.from local targets = sgs.SPlayerList() local other_players = room:getOtherPlayers(source) for _, player in sgs.qlist(other_players) do local skill = room:isProhibited(source, player, self) if skill ~= nil then local log_message = sgs.LogMessage() log_message.type = "#SkillAvoid" log_message.from = player log_message.arg = skill:objectName() log_message.arg2 = self:objectName() room:broadcastSkillInvoke(skill:objectName()) else targets:append(player) end end local use = card_use use.to = targets self:cardOnUse(room, use) end function isAvailable_GlobalEffect(self, player) local canUse = false local players = player:getSiblings() players:append(player) for _, p in sgs.qlist(players) do if p:isDead() or player:isProhibited(p, self) then continue end canUse = true break end return canUse and self:cardIsAvailable(player) end function onUse_GlobalEffect(self, room, card_use) local source = card_use.from local targets = sgs.SPlayerList() local all_players = room:getAllPlayers() for _, player in sgs.qlist(all_players) do local skill = room:isProhibited(source, player, self) if skill ~= nil then local log_message = sgs.LogMessage() log_message.type = "#SkillAvoid" log_message.from = player log_message.arg = skill:objectName() log_message.arg2 = self:objectName() room:broadcastSkillInvoke(skill:objectName()) else targets:append(player) end end local use = card_use use.to = targets self:cardOnUse(room, use) end function onUse_DelayedTrick(self, room, card_use) local use = card_use local wrapped = sgs.Sanguosha:getWrappedCard(self:getEffectiveId()) use.card = wrapped local data = sgs.QVariant() data:setValue(use) local thread = room:getThread() thread:trigger(sgs.PreCardUsed, room, use.from, data) use = data:toCardUse() local logm = sgs.LogMessage() logm.from = use.from logm.to = use.to logm.type = "#UseCard" logm.card_str = self:toString() room:sendLog(logm) local reason = sgs.CardMoveReason(sgs.CardMoveReason_S_REASON_USE, use.from:objectName(), use.to:first():objectName(), self:getSkillName(), "") room:moveCardTo(self, use.from, use.to:first(), sgs.Player_PlaceDelayedTrick, reason, true) thread:trigger(sgs.CardUsed, room, use.from, data) use = data:toCardUse() thread:trigger(sgs.CardFinished, room, use.from, data) end function use_DelayedTrick(self, room, source, targets) if #targets == 0 then local reason = sgs.CardMoveReason(sgs.CardMoveReason_S_REASON_USE, source:objectName(), "", self:getSkillName(), "") room:moveCardTo(self, room:getCardOwner(self:getEffectiveId()), nil, sgs.Player_DiscardPile, reason, true) end end function onNullified_DelayedTrick_movable(self, target) local room = target:getRoom() local thread = room:getThread() local players = room:getOtherPlayers(target) players:append(target) local p = nil for _, player in sgs.qlist(players) do if player:containsTrick(self:objectName()) then continue end local skill = room:isProhibited(target, player, self) if skill then local logm = sgs.LogMessage() logm.type = "#SkillAvoid" logm.from = player logm.arg = skill:objectName() logm.arg2 = self:objectName() room:sendLog(logm) room:broadcastSkillInvoke(skill:objectName()) continue end local reason = sgs.CardMoveReason(sgs.CardMoveReason_S_REASON_TRANSFER, target:objectName(), "", self:getSkillName(), "") room:moveCardTo(self, target, player, sgs.Player_PlaceDelayedTrick, reason, true) if target:objectName() == player:objectName() then break end local use = sgs.CardUseStruct() use.from = nil use.to:append(player) use.card = self local data = sgs.QVariant() data:setValue(use) thread:trigger(sgs.TargetConfirming, room, player, data) local new_use = data:toCardUse() if new_use.to:isEmpty() then p = player break end for _, ps in sgs.qlist(room:getAllPlayers()) do thread:trigger(sgs.TargetConfirmed, room, ps, data) end break end if p then self:on_nullified(p) end end function onNullified_DelayedTrick_unmovable(self, target) local reason = sgs.CardMoveReason(sgs.CardMoveReason_S_REASON_NATURAL_ENTER, target:objectName()) target:getRoom():throwCard(self, reason, nil) end -- ============================================ function sgs.CreateTrickCard(spec) assert(type(spec.name) == "string" or type(spec.class_name) == "string") if not spec.name then spec.name = spec.class_name elseif not spec.class_name then spec.class_name = spec.name end if spec.suit then assert(type(spec.suit) == "number") end if spec.number then assert(type(spec.number) == "number") end if spec.subtype then assert(type(spec.subtype) == "string") else local subtype_table = { "TrickCard", "single_target_trick", "delayed_trick", "aoe", "global_effect" } spec.subtype = subtype_table[(spec.subclass or 0) + 1] end local card = sgs.LuaTrickCard(spec.suit or sgs.Card_NoSuit, spec.number or 0, spec.name, spec.class_name, spec.subtype) if type(spec.target_fixed) == "boolean" then card:setTargetFixed(spec.target_fixed) end if type(spec.can_recast) == "boolean" then card:setCanRecast(spec.can_recast) end if type(spec.subclass) == "number" then card:setSubClass(spec.subclass) else card:setSubClass(sgs.LuaTrickCard_TypeNormal) end if spec.subclass then if spec.subclass == sgs.LuaTrickCard_TypeDelayedTrick then if not spec.about_to_use then spec.about_to_use = onUse_DelayedTrick end if not spec.on_use then spec.on_use = use_DelayedTrick end if not spec.on_nullified then if spec.movable then spec.on_nullified = onNullified_DelayedTrick_movable else spec.on_nullified = onNullified_DelayedTrick_unmovable end end elseif spec.subclass == sgs.LuaTrickCard_TypeAOE then if not spec.available then spec.available = isAvailable_AOE end if not spec.about_to_use then spec.about_to_use = onUse_AOE end if not spec.target_fixed then card:setTargetFixed(true) end elseif spec.subclass == sgs.LuaTrickCard_TypeGlobalEffect then if not spec.available then spec.available = isAvailable_GlobalEffect end if not spec.about_to_use then spec.about_to_use = onUse_GlobalEffect end if not spec.target_fixed then card:setTargetFixed(true) end end end card.filter = spec.filter card.feasible = spec.feasible card.available = spec.available card.is_cancelable = spec.is_cancelable card.on_nullified = spec.on_nullified card.about_to_use = spec.about_to_use card.on_use = spec.on_use card.on_effect = spec.on_effect return card end function sgs.CreateViewAsSkill(spec) assert(type(spec.name) == "string") if spec.response_pattern then assert(type(spec.response_pattern) == "string") end local response_pattern = spec.response_pattern or "" local response_or_use = spec.response_or_use or false if spec.expand_pile then assert(type(spec.expand_pile) == "string") end local expand_pile = spec.expand_pile or "" local skill = sgs.LuaViewAsSkill(spec.name, response_pattern, response_or_use, expand_pile) local n = spec.n or 0 function skill:view_as(cards) return spec.view_as(self, cards) end function skill:view_filter(selected, to_select) if #selected >= n then return false end return spec.view_filter(self, selected, to_select) end if type(spec.guhuo_type) == "string" and spec.guhuo_type ~= "" then skill:setGuhuoDialog(guhuo_type) end skill.should_be_visible = spec.should_be_visible skill.enabled_at_play = spec.enabled_at_play skill.enabled_at_response = spec.enabled_at_response skill.enabled_at_nullification = spec.enabled_at_nullification return skill end function sgs.CreateOneCardViewAsSkill(spec) assert(type(spec.name) == "string") if spec.response_pattern then assert(type(spec.response_pattern) == "string") end local response_pattern = spec.response_pattern or "" local response_or_use = spec.response_or_use or false if spec.filter_pattern then assert(type(spec.filter_pattern) == "string") end if spec.expand_pile then assert(type(spec.expand_pile) == "string") end local expand_pile = spec.expand_pile or "" local skill = sgs.LuaViewAsSkill(spec.name, response_pattern, response_or_use, expand_pile) if type(spec.guhuo_type) == "string" and spec.guhuo_type ~= "" then skill:setGuhuoDialog(guhuo_type) end function skill:view_as(cards) if #cards ~= 1 then return nil end return spec.view_as(self, cards[1]) end function skill:view_filter(selected, to_select) if #selected >= 1 or to_select:hasFlag("using") then return false end if spec.view_filter then return spec.view_filter(self, to_select) end if spec.filter_pattern then local pat = spec.filter_pattern if string.endsWith(pat, "!") then if sgs.Self:isJilei(to_select) then return false end pat = string.sub(pat, 1, -2) end return sgs.Sanguosha:matchExpPattern(pat, sgs.Self, to_select) end end skill.enabled_at_play = spec.enabled_at_play skill.enabled_at_response = spec.enabled_at_response skill.enabled_at_nullification = spec.enabled_at_nullification return skill end function sgs.CreateZeroCardViewAsSkill(spec) assert(type(spec.name) == "string") if spec.response_pattern then assert(type(spec.response_pattern) == "string") end local response_pattern = spec.response_pattern or "" local response_or_use = spec.response_or_use or false local skill = sgs.LuaViewAsSkill(spec.name, response_pattern, response_or_use, "") if type(spec.guhuo_type) == "string" and spec.guhuo_type ~= "" then skill:setGuhuoDialog(guhuo_type) end function skill:view_as(cards) if #cards > 0 then return nil end return spec.view_as(self) end function skill:view_filter(selected, to_select) return false end skill.enabled_at_play = spec.enabled_at_play skill.enabled_at_response = spec.enabled_at_response skill.enabled_at_nullification = spec.enabled_at_nullification return skill end function sgs.CreateEquipCard(spec) assert(type(spec.location) == "number" and spec.location ~= sgs.EquipCard_DefensiveHorseLocation and spec.location ~= sgs.EquipCard_OffensiveHorseLocation) assert(type(spec.name) == "string" or type(spec.class_name) == "string") if not spec.name then spec.name = spec.class_name elseif not spec.class_name then spec.class_name = spec.name end if spec.suit then assert(type(spec.suit) == "number") end if spec.number then assert(type(spec.number) == "number") end if spec.location == sgs.EquipCard_WeaponLocation then assert(type(spec.range) == "number") end local card = nil if spec.location == sgs.EquipCard_WeaponLocation then card = sgs.LuaWeapon(spec.suit or sgs.Card_NoSuit, spec.number or 0, spec.range, spec.name, spec.class_name) elseif spec.location == sgs.EquipCard_ArmorLocation then card = sgs.LuaArmor(spec.suit or sgs.Card_NoSuit, spec.number or 0, spec.name, spec.class_name) elseif spec.location == sgs.EquipCard_TreasureLocation then card = sgs.LuaTreasure(spec.suit or sgs.Card_NoSuit, spec.number or 0, spec.name, spec.class_name) end assert(card ~= nil) card.on_install = spec.on_install card.on_uninstall = spec.on_uninstall return card end function sgs.CreateWeapon(spec) spec.location = sgs.EquipCard_WeaponLocation return sgs.CreateEquipCard(spec) end function sgs.CreateArmor(spec) spec.location = sgs.EquipCard_ArmorLocation return sgs.CreateEquipCard(spec) end function sgs.CreateTreasure(spec) spec.location = sgs.EquipCard_TreasureLocation return sgs.CreateEquipCard(spec) end -- general levels function sgs.CreateGeneralLevel(spec) local name = spec.name assert(type(name) == "string") local level = sgs.LuaGeneralLevel(name) local translation = spec.translation if type(translation) == "string" then sgs.AddTranslationEntry(name, translation) end local order = spec.order assert(type(order) == "number") level:setOrder(order) local introduction = spec.introduction or "" if type(introduction) == "string" then sgs.AddTranslationEntry(string.format(":%s", name), introduction) end local sub_levels = spec.sub_levels if type(sub_levels) == "table" then for _,sub_level in ipairs(sub_levels) do level:addSubLevel(sub_level) end end local gatekeepers = spec.gatekeepers if type(gatekeepers) == "table" then for _,general in ipairs(gatekeepers) do level:addGateKeeper(general) end elseif type(gatekeepers) == "string" then level:addGateKeeper(gatekeepers) end level.judge_func = spec.judge_func return level end function sgs.LoadTranslationTable(t) for key, value in pairs(t) do sgs.AddTranslationEntry(key, value) end end
gpl-3.0
Playermet/luajit-estrela
est/math.lua
1
1069
local mod = {} function mod.lerp(value, from, to) return (1 - value) * from + value * to end function mod.inverse_lerp(value, from, to) return (value - from) / (to - from) end function mod.clamp(value, min, max) if value < min then return min end if value > max then return max end return value end function mod.round(value) if value >= 0 then return math.floor(value + 0.5) end return math.ceil(value - 0.5) end function mod.trunc(x) return (math.modf(x)) end function mod.floor_by(value, quantum) return math.floor(value / quantum) * quantum end function mod.ceil_by(value, quantum) return math.ceil(value / quantum) * quantum end function mod.round_by(value, quantum) return mod.round(value / quantum) * quantum end function mod.sign(x) if x > 0 then return 1 elseif x < 0 then return -1 end return 0 end -- greatest common divisor function mod.gcd(x, y) while x ~= 0 do x, y = y % x, x end return y end -- least common multiple function mod.lcm(x, y) return (x * y) / mod.gcd(x, y) end return mod
mit
Capibara-/cardpeek
dot_cardpeek_dir/scripts/lib/en1545.lua
16
7123
-- -- 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/>. -- require('lib.strict') require('lib.country_codes') EPOCH = os.time({hour=0, min=0, year=1997, month=1, sec=0, day=1}) --EPOCH = 852073200 date_days = 0 function en1545_DATE(source) date_days = EPOCH+bytes.tonumber(source)*24*3600 return os.date("%a %x",date_days) end function en1545_TIME(source) local date_minutes local part = bytes.sub(source, 0, 10) -- 11 bits part = bytes.pad_left(part,32,0) date_minutes = date_days + bytes.tonumber(part)*60 date_days = 0 return os.date("%X",date_minutes) end function en1545_DATE_TIME(source) local dtSeconds = EPOCH + bytes.tonumber(source) return os.date("%c", dtSeconds) end function en1545_BCD_DATE(source) local dob = tostring(bytes.convert(source,8)) local dobYear = string.sub(dob, 1, 4) local dobMonth = string.sub(dob, 5, 6) local dobDay = string.sub(dob, 7, 8) local dateOfBirth = dobDay.."/"..dobMonth.."/"..dobYear return dateOfBirth end ALPHA = { "-","A","B","C","D","E","F","G", "H","I","J","K","L","M","N","O", "P","Q","R","S","T","U","V","W", "X","Y","Z","?","?","?","?"," " } function en1545_ALPHA(source) local i local c local str = {""} for i=0,#source-4,5 do c=bytes.tonumber(bytes.sub(source,i,i+4)) table.insert(str,ALPHA[c+1]) end return table.concat(str) end function en1545_NETWORKID(source) local country = bytes.sub(source, 0, 11) local region = bytes.sub(source, 12, 23) local country_code local region_code country_code = iso_country_code_name(tonumber(country:convert(4):format("%D"))) region_code = tonumber(region:convert(4):format("%D")) if region_code then return "country "..country_code.." / network "..region_code end return "country "..country_code end function en1545_NUMBER(source) return bytes.tonumber(source) end function en1545_AMOUNT(source) return string.format("%.2f€",bytes.tonumber(source)/100) end function en1545_ZONES(source) local zones = bytes.tonumber(source) local n = 8 local maxzone = 0 local minzone while n >= 1 do if zones >= 2^(n-1) then if maxzone == 0 then maxzone = n end zones = zones - 2^(n-1) if zones == 0 then minzone = n end end n = n - 1 end return string.format("%d-%d",minzone,maxzone) end function en1545_UNDEFINED(source) local hex_info = source:convert(8) return hex_info:format("0x%D") end en1545_BITMAP = 1 en1545_REPEAT = 2 --[[ in en1545_parse_item, the "format" parameter is a table with entries containing 3 or 4 elements: - format[1]: the type of the entry, which is either a) en1545_BITMAP: indicates a bitmap field (1 => field is present) b) en1545_REPEAT: indicates the field is repeated n times. c) en1545_XXXXXX: a function to call on the data for further processing. - format[2]: the length of the entry in bits. - format[3]: the name of the entry - format[4]: used only for en1545_BITMAP, points to a sub-table of entries. --]] function en1545_parse_item(ctx, format, data, position, reference_index) local parsed = 0 local index, item_node, bitmap_node, bitmap_size, item, alt if format == nil then return 0 end parsed = format[2] -- entry length item = bytes.sub(data,position,position+parsed-1) if item == nil then return 0 end item_node = ctx:append{ classname="item", label=format[3], --[[ id=reference_index --]] } if format[1] == en1545_BITMAP then -- entry type is bitmap bitmap_size = parsed parsed = bitmap_size item_node:append{ classname="item", label="("..format[3].."Bitmap)", val=item } -- go through bit table in reverse order, since lsb=first bit for index,bit in item:reverse():ipairs() do if bit==1 then parsed = parsed + en1545_parse_item(item_node, format[4][index], data, position+parsed, index) end end elseif format[1] == en1545_REPEAT then -- entry type is repeat item_node:set_attribute("val",item) item_node:set_attribute("alt",bytes.tonumber(item)) for index=1,bytes.tonumber(item) do parsed = parsed + en1545_parse_item(ctx, format[4][0], data, position+parsed, reference_index+index) end else -- entry type is item alt = format[1](item) if alt==nil then item_node:remove() else item_node:set_attribute("val",item) item_node:set_attribute("size",#item) item_node:set_attribute("alt",alt) end end return parsed end function en1545_parse(ctx, format, data) local index local parsed = 0 for index=0,#format do parsed = parsed + en1545_parse_item(ctx,format[index],data,parsed,index) end return parsed end function en1545_unparsed(ctx, data) if data and bytes.tonumber(data)>0 then ctx:append{ classname="item", label="(remaining unparsed data)", val=data, alt="(binary data)" } end end function en1545_map(cardenv, data_type, ...) local record_node local bits local i local parsed local block for file in cardenv:find({label=data_type}) do for record_node in file:find({label="record"}) do if record_node==nil then break end bits = record_node:get_attribute("val"):convert(1) parsed = 0 for i,template in ipairs({...}) do block = bytes.sub(bits,parsed) if bytes.is_all(block,0)==false then parsed = parsed + en1545_parse(record_node,template,block) end end en1545_unparsed(record_node,bytes.sub(bits,parsed)) end file:set_attribute("parsed","true") end end
gpl-3.0
bjornbytes/RxLua
tests/take.lua
2
1302
describe('take', function() it('produces an error if its parent errors', function() local observable = Rx.Observable.of(''):map(function(x) return x() end) expect(observable).to.produce.error() expect(observable:take(1)).to.produce.error() end) it('produces nothing if the count is zero', function() local observable = Rx.Observable.of(3):take(0) expect(observable).to.produce.nothing() end) it('produces nothing if the count is less than zero', function() local observable = Rx.Observable.of(3):take(-3) expect(observable).to.produce.nothing() end) it('takes one element if no count is specified', function() local observable = Rx.Observable.fromTable({2, 3, 4}, ipairs):take() expect(observable).to.produce(2) end) it('produces all values if it takes all of the values of the original', function() local observable = Rx.Observable.fromTable({1, 2}, ipairs):take(2) expect(observable).to.produce(1, 2) end) it('completes and does not fail if it takes more values than were produced', function() local observable = Rx.Observable.of(3):take(5) local onNext, onError, onCompleted = observableSpy(observable) expect(onNext).to.equal({{3}}) expect(#onError).to.equal(0) expect(#onCompleted).to.equal(1) end) end)
mit
creationix/redis-luvit
test.lua
1
1089
local codec = require('redis-codec') local jsonStringify = require('json').stringify local function test(str, extra, expected) local result, e = codec.decode(str, 1) p(str) e = str and extra and str:sub(e) p(e, extra) p(result, expected) assert(extra == e) assert(jsonStringify(result) == jsonStringify(expected)) end test("*2\r\n*1\r\n+Hello\r\n+World\r\n", "", {{"Hello"},"World"}) test("*2\r\n*1\r\n$5\r\nHello\r\n$5\r\nWorld\r\n", "", {{"Hello"},"World"}) test("set language Lua\r\n", "", {"set", "language", "Lua"}) test("$5\r\n12345\r\n", "", "12345") test("$5\r\n12345\r") test("$5\r\n12345\r\nabc", "abc", "12345") test("+12") test("+1234\r") test("+1235\r\n", "", "1235") test("+1235\r\n1234", "1234", "1235") test(":45\r") test(":45\r\n", "", 45) test("*-1\r\nx", "x", nil) test("-FATAL, YIKES\r\n", "", {error="FATAL, YIKES"}) test("*12\r\n$4\r\n2048\r\n$1\r\n0\r\n$4\r\n1024\r\n$2\r\n42\r\n$1\r\n5\r\n$1\r\n7\r\n$1\r\n5\r\n$1\r\n7\r\n$1\r\n5\r\n$1\r\n7\r\n$1\r\n5\r\n$1\r\n7\r\n", "", { '2048', '0', '1024', '42', '5', '7', '5', '7', '5', '7', '5', '7' })
mit
liruqi/bigfoot
Interface/AddOns/Bagnon/libs/Unfit-1.0/Unfit-1.0.lua
1
5835
--[[ Copyright 2011-2016 João Cardoso Unfit is distributed under the terms of the GNU General Public License (Version 3). As a special exception, the copyright holders of this library give you permission to embed it with independent modules to produce an addon, regardless of the license terms of these independent modules, and to copy and distribute the resulting software under terms of your choice, provided that you also meet, for each embedded independent module, the terms and conditions of the license of that module. Permission is not granted to modify this library. This library 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 the library. If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>. This file is part of Unfit. --]] local Lib = LibStub:NewLibrary('Unfit-1.0', 9) if not Lib then return end --[[ Data ]]-- do local _, Class = UnitClass('player') local Unusable if Class == 'DEATHKNIGHT' then Unusable = { -- weapon, armor, dual-wield {LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_STAFF,LE_ITEM_WEAPON_UNARMED, LE_ITEM_WEAPON_DAGGER, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW, LE_ITEM_WEAPON_WAND}, {LE_ITEM_ARMOR_SHIELD} } elseif Class == 'DEMONHUNTER' then Unusable = { {LE_ITEM_WEAPON_AXE2H, LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_MACE1H, LE_ITEM_WEAPON_MACE2H, LE_ITEM_WEAPON_POLEARM, LE_ITEM_WEAPON_SWORD2H, LE_ITEM_WEAPON_STAFF, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW, LE_ITEM_WEAPON_WAND}, {LE_ITEM_ARMOR_MAIL, LE_ITEM_ARMOR_PLATE, LE_ITEM_ARMOR_SHIELD} } elseif Class == 'DRUID' then Unusable = { {LE_ITEM_WEAPON_AXE1H, LE_ITEM_WEAPON_AXE2H, LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_SWORD1H, LE_ITEM_WEAPON_SWORD2H, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW, LE_ITEM_WEAPON_WAND}, {LE_ITEM_ARMOR_MAIL, LE_ITEM_ARMOR_PLATE, LE_ITEM_ARMOR_SHIELD}, true } elseif Class == 'HUNTER' then Unusable = { {LE_ITEM_WEAPON_MACE1H, LE_ITEM_WEAPON_MACE2H, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_WAND}, {LE_ITEM_ARMOR_PLATE, LE_ITEM_ARMOR_SHIELD} } elseif Class == 'MAGE' then Unusable = { {LE_ITEM_WEAPON_AXE1H, LE_ITEM_WEAPON_AXE2H, LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_MACE1H, LE_ITEM_WEAPON_MACE2H, LE_ITEM_WEAPON_POLEARM, LE_ITEM_WEAPON_SWORD2H, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_UNARMED, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW}, {LE_ITEM_ARMOR_LEATHER, LE_ITEM_ARMOR_MAIL, LE_ITEM_ARMOR_PLATE, LE_ITEM_ARMOR_SHIELD}, true } elseif Class == 'MONK' then Unusable = { {LE_ITEM_WEAPON_AXE2H, LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_MACE2H, LE_ITEM_WEAPON_SWORD2H, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_DAGGER, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW, LE_ITEM_WEAPON_WAND}, {LE_ITEM_ARMOR_MAIL, LE_ITEM_ARMOR_PLATE, LE_ITEM_ARMOR_SHIELD} } elseif Class == 'PALADIN' then Unusable = { {LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_STAFF, LE_ITEM_WEAPON_UNARMED, LE_ITEM_WEAPON_DAGGER, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW, LE_ITEM_WEAPON_WAND}, {}, true } elseif Class == 'PRIEST' then Unusable = { {LE_ITEM_WEAPON_AXE1H, LE_ITEM_WEAPON_AXE2H, LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_MACE2H, LE_ITEM_WEAPON_POLEARM, LE_ITEM_WEAPON_SWORD1H, LE_ITEM_WEAPON_SWORD2H, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_UNARMED, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW}, {LE_ITEM_ARMOR_LEATHER, LE_ITEM_ARMOR_MAIL, LE_ITEM_ARMOR_PLATE, LE_ITEM_ARMOR_SHIELD}, true } elseif Class == 'ROGUE' then Unusable = { {LE_ITEM_WEAPON_AXE2H, LE_ITEM_WEAPON_MACE2H, LE_ITEM_WEAPON_POLEARM, LE_ITEM_WEAPON_SWORD2H, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_STAFF, LE_ITEM_WEAPON_WAND}, {LE_ITEM_ARMOR_MAIL, LE_ITEM_ARMOR_PLATE, LE_ITEM_ARMOR_SHIELD} } elseif Class == 'SHAMAN' then Unusable = { {LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_POLEARM, LE_ITEM_WEAPON_SWORD1H, LE_ITEM_WEAPON_SWORD2H, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW, LE_ITEM_WEAPON_WAND}, {LE_ITEM_ARMOR_PLATEM} } elseif Class == 'WARLOCK' then Unusable = { {LE_ITEM_WEAPON_AXE1H, LE_ITEM_WEAPON_AXE2H, LE_ITEM_WEAPON_BOWS, LE_ITEM_WEAPON_GUNS, LE_ITEM_WEAPON_MACE1H, LE_ITEM_WEAPON_MACE2H, LE_ITEM_WEAPON_POLEARM, LE_ITEM_WEAPON_SWORD2H, LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_UNARMED, LE_ITEM_WEAPON_THROWN, LE_ITEM_WEAPON_CROSSBOW}, {LE_ITEM_ARMOR_LEATHER, LE_ITEM_ARMOR_MAIL, LE_ITEM_ARMOR_PLATE, LE_ITEM_ARMOR_SHIELD}, true } elseif Class == 'WARRIOR' then Unusable = {{LE_ITEM_WEAPON_WARGLAIVE, LE_ITEM_WEAPON_WAND}, {}} else Unusable = {{}, {}} end Lib.unusable = {} Lib.cannotDual = Unusable[3] for i, class in ipairs({LE_ITEM_CLASS_WEAPON, LE_ITEM_CLASS_ARMOR}) do local list = {} for _, subclass in ipairs(Unusable[i]) do list[subclass] = true end Lib.unusable[class] = list end end --[[ API ]]-- function Lib:IsItemUnusable(...) if ... then local slot, _,_, class, subclass = select(9, GetItemInfo(...)) return Lib:IsClassUnusable(class, subclass, slot) end end function Lib:IsClassUnusable(class, subclass, slot) if class and subclass and Lib.unusable[class] then return slot ~= '' and Lib.unusable[class][subclass] or slot == 'INVTYPE_WEAPONOFFHAND' and Lib.cannotDual end end
mit
liruqi/bigfoot
Interface/AddOns/Bagnon_Config/localization/tw.lua
1
2587
--[[ Chinese Traditional Localization *** --]] local L = LibStub('AceLocale-3.0'):NewLocale('Bagnon-Config', 'zhTW') if not L then return end -- general L.GeneralDesc = '根據你的喜好來切換一般功能設定。' L.Locked = '鎖定框架' L.Fading = '框架淡化' L.TipCount = '物品統計提示' L.FlashFind = '閃爍找到' L.EmptySlots = '在空的槽位顯示背景顏色' L.DisplayBlizzard = '隱藏的背包顯示為內建框架' -- frame L.FrameSettings = '框架設定' L.FrameSettingsDesc = '設定Bagnon框架。' L.Frame = '框架' L.Enabled = '啟用框架' --L.CharacterSpecific = 'Character Specific Settings' L.ExclusiveReagent = '分離材料銀行' L.BagFrame = '背包列表' L.Money = '金錢' L.Broker = 'Databroker外掛' L.Sort = '排序按鈕' L.Search = '切換搜尋' L.Options = '設定按鈕' L.Appearance = '外觀' L.Layer = '階層' L.BagBreak = '根據背包顯示' L.ReverseBags = '反轉背包順序' L.ReverseSlots = '反轉槽位順序' L.Color = '背景顏色' L.BorderColor = '邊框顏色' L.Strata = '框架層級' L.Columns = '列' L.Scale = '縮放' L.ItemScale = '物品縮放' L.Spacing = '間距' L.Alpha = '透明度' -- auto display L.DisplaySettings = '自動顯示' L.DisplaySettingsDesc = '讓你設定在遊戲事件中背包自動開啟或關閉。' L.DisplayInventory = '顯示背包' L.CloseInventory = '關閉背包' L.DisplayBank = '訪問銀行' L.DisplayAuction = '訪問拍賣行' L.DisplayTrade = '交易物品' L.DisplayCraft = '製造' L.DisplayMail = '檢查信箱' L.DisplayGuildbank = '訪問公會銀行' L.DisplayPlayer = '開啟角色資訊' L.DisplayGems = '鑲崁寶石' L.CloseCombat = '進入戰鬥' L.CloseVehicle = '進入載具' L.CloseBank = '離開銀行' L.CloseVendor = '離開商人' -- colors L.ColorSettings = '顏色設定' L.ColorSettingsDesc = '讓你設定在Bagnon框架裡較簡單辨識物品槽位。' L.GlowQuality = '根據品質高亮物品' L.GlowNew = '高亮新物品' L.GlowQuest = '高亮任務物品' L.GlowUnusable = '高亮無法使用的物品' L.GlowSets = '高亮裝備設定物品' L.ColorSlots = '根據背包類型高亮空的槽' L.NormalColor = '一般背包槽顏色' L.LeatherColor = '製皮包槽顏色' L.InscribeColor = '銘文包槽顏色' L.HerbColor = '草藥包槽顏色' L.EnchantColor = '附魔包槽顏色' L.EngineerColor = '工程箱槽顏色' L.GemColor = '寶石包顏色' L.MineColor = '礦石包顏色' L.TackleColor = '工具箱顏色' L.RefrigeColor = '冰箱顏色' L.ReagentColor = '材料銀行顏色' L.GlowAlpha = '高亮亮度'
mit
kidanger/Chronored
levels/level8.lua
2
2546
local level = { boxes={ {y=46, x=9, w=11, h=91}, {y=46, x=20, w=158, h=8}, {y=84, x=20, w=104, h=9}, {y=127, x=20, w=158, h=10}, {y=93, x=60, w=3, h=4}, {y=97, x=61, w=4, h=3}, {y=100, x=62, w=3, h=2}, {y=96, x=63, w=1, h=1}, {y=102, x=63, w=2, h=3}, {y=113, x=63, w=3, h=1}, {y=125, x=63, w=3, h=2}, {y=114, x=64, w=3, h=2}, {y=123, x=64, w=3, h=2}, {y=116, x=65, w=2, h=7}, {y=125, x=66, w=1, h=1}, {y=115, x=67, w=1, h=6}, {y=61, x=120, w=2, h=1}, {y=60, x=121, w=4, h=1}, {y=79, x=121, w=1, h=2}, {y=81, x=122, w=1, h=1}, {y=82, x=123, w=1, h=2}, {y=59, x=124, w=2, h=1}, {y=57, x=125, w=1, h=2}, {y=54, x=126, w=1, h=3}, {y=54, x=166, w=12, h=73}, }, start={y=115, x=29}, arrival={y=70, x=28}, capsules={ {y=97, x=123, type="fuel"}, {y=98, x=123, type="health"}, {y=98, x=124, type="fuel"}, {y=99, x=124, type="health"}, {y=99, x=125, type="fuel"}, {y=100, x=125, type="health"}, {y=100, x=126, type="fuel"}, {y=101, x=126, type="health"}, {y=101, x=127, type="fuel"}, {y=102, x=127, type="health"}, {y=102, x=128, type="fuel"}, {y=103, x=128, type="health"}, {y=103, x=129, type="fuel"}, {y=104, x=129, type="health"}, {y=104, x=130, type="fuel"}, {y=105, x=130, type="health"}, {y=105, x=131, type="fuel"}, {y=106, x=131, type="health"}, {y=106, x=132, type="fuel"}, {y=107, x=132, type="health"}, {y=107, x=133, type="fuel"}, {y=108, x=133, type="health"}, {y=108, x=134, type="fuel"}, {y=109, x=134, type="health"}, {y=109, x=135, type="fuel"}, {y=110, x=135, type="health"}, {y=110, x=136, type="fuel"}, {y=111, x=136, type="health"}, {y=111, x=137, type="fuel"}, {y=112, x=137, type="health"}, {y=112, x=138, type="fuel"}, {y=113, x=138, type="health"}, {y=113, x=139, type="fuel"}, {y=114, x=139, type="health"}, {y=114, x=140, type="fuel"}, {y=115, x=140, type="health"}, {y=115, x=141, type="fuel"}, {y=116, x=141, type="health"}, {y=116, x=142, type="fuel"}, {y=117, x=142, type="health"}, {y=117, x=143, type="fuel"}, {y=118, x=143, type="health"}, {y=118, x=144, type="fuel"}, {y=119, x=144, type="health"}, {y=119, x=145, type="fuel"}, }, turrets={ {y=82, x=59}, {y=54, x=63}, {y=93, x=80}, {y=54, x=81}, {y=125, x=82}, {y=82, x=89}, {y=54, x=104}, {y=125, x=109}, {y=82, x=112}, {y=93, x=121}, {y=125, x=141}, {y=125, x=161}, }, texts={ {y=94, x=23, text=1, w=6, h=32}, {y=94, x=29, text=1, w=30, h=21}, {y=116, x=29, text=1, w=30, h=10}, {y=115, x=30, text=1, w=29, h=1}, }, textdata={ "Pro tip: be fast!", "", "", "", }, } return level
gpl-2.0
Raugharr/Herald
data/gui/FactionMenu.lua
1
2547
Menu.moveable = true Menu.Width = 500 Menu.Height = 600 local function ShowGeneral(Menu, Faction) local Table = Menu:CreateTable(2, 6) local Skin = Menu:GetSkin() local Font = Skin:Table():GetFont() Table:SetCellWidth(Font:Width() * 8) Table:SetCellHeight(Font:Height()) Table:CreateLabel("Leader") Table:CreateLabel(Faction:GetLeader():GetName()) Table:CreateLabel("Power") Table:CreateLabel(Faction:GetPower()) Table:CreateLabel("Power Gain") Table:CreateLabel(Faction:GetPowerGain()) Table:CreateLabel("Members") Table:CreateLabel(Faction:GetMembers()) end local function ShowCastePower(Menu, Faction) local Table = Menu:CreateTable(3, World.CasteNum + 1) local Skin = Menu:GetSkin() local Font = Skin:Table():GetFont() local Idx = 1 local Power = Faction:GetCastePower() local Weight = Faction:GetCasteWeight() Table:SetCellWidth(Font:Width() * 8) Table:SetCellHeight(Font:Height()) Table:CreateLabel("Caste") Table:CreateLabel("Power") Table:CreateLabel("Weight") for i, Caste in ipairs(World.Castes) do Table:CreateLabel(Caste) Table:CreateLabel(Power[Idx]) Table:CreateLabel(Weight[Idx] .. "%") Idx = Idx + 1 end end local function DisplayGoals(Menu, FactId) local Container = Gui.VerticalContainer(Menu, Menu:GetWidth(), 200) Container:CreateButton("Select goal", function(Widget) if FactId:CanPassGoal() == false then return end if Widget.Open == nil or Widget.Open == false then for k, v in pairs(FactId:ListGoals()) do Container:CreateButton(v, function(Widget) local Window = nil if k - 1 == Faction.SupportCaste then Window = "FactionGoalSelect" elseif k - 1 == Faction.ChangePolicy then print("Policy") Window = "FactionGoalPolicy" end print (k - 1, Faction.AddPolicy) Gui.CreateWindow(Window, {Faction = FactId, Goal = k - 1}) end) end Widget.Open = true end end) end function Menu.Init(Menu, Data) local Player = Data.Player local Settlement = Player:GetSettlement() local Faction = Player:GetFaction() local Skin = Menu:GetSkin() Menu:OnNewChild(Container.Vertical) Menu:SetSkin(Gui.GetSkin("Header")) if Faction ~= nil then Menu:CreateLabel(Faction:GetName() .. " Faction") Menu:SetSkin(Skin) ShowGeneral(Menu, Faction) ShowCastePower(Menu, Faction) DisplayGoals(Menu, Faction) else Menu:CreateLabel("No Faction") Menu:SetSkin(Skin) end Menu:CreateButton("Close", function(Widget) Menu:Close() end) end function Menu.Think(Menu) end
gpl-2.0
dmccuskey/lua-corovel
corovel/plugin/openssl.lua
1
2013
--====================================================================-- -- corovel/plugin/openssl.lua -- -- Documentation: http://docs.davidmccuskey.com/display/docs/Lua+Corovel.lua --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2015 David McCuskey 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. --]] --====================================================================-- --== Corovel : SSL Shim --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== Imports local ssl = require 'ssl' --====================================================================-- --== Setup, Constants assert( ssl, "ssl package not found" ) -- fake loaded package package.loaded['plugin_luasec_ssl'] = ssl -- TODO: figure out what to return here -- maybe just true ? return { ssl=ssl }
mit
ryanplusplus/the-legend-of-zorldo
render/fancy_message.lua
2
1069
local width_padding = 5 local height_padding = 2 return function(scene) local map_height local map_width for entity in pairs(scene:entities_with('map')) do map_height = entity.map.height * entity.map.tileHeight map_width = entity.map.width * entity.map.tileWidth end for entity in pairs(scene:entities_with('fancy_message')) do local fancy_message = entity.fancy_message local text = fancy_message.text local box_width = fancy_message.font:getWidth(text) + 2 * width_padding local box_height = fancy_message.font:getHeight(text) + 2 * height_padding local x = map_width / 2 - box_width / 2 local y = map_height / 2 - box_height / 2 love.graphics.setFont(fancy_message.font) love.graphics.setColor(0, 0, 0, 175) love.graphics.rectangle('fill', x, y, box_width, box_height) love.graphics.setColor(255, 255, 255, 200) love.graphics.rectangle('line', x, y, box_width, box_height) love.graphics.setColor(255, 255, 255, 255) love.graphics.print(text, x + width_padding, y + height_padding) end end
mit
liruqi/bigfoot
Interface/AddOns/BigFoot/AceLibs/wyLib/NetEaseGUI-2.0/Embed/Help.lua
1
1892
local GUI = LibStub('NetEaseGUI-2.0') local Help = GUI:NewEmbed('Help', 4) if not Help then return end ---- Help local function HelpOnClick(self) local enable = self.helpPlate and not HelpPlate_IsShowing(self.helpPlate) if enable then HelpPlate_Show(self.helpPlate, self:GetParent(), self, true) else HelpPlate_Hide(true) end if type(self.callback) == 'function' then self.callback(enable) end end local function HelpOnHide() HelpPlate_Hide() end local function HelpOnShow(self) local parent = self:GetParent() repeat if parent.PortraitFrame then return self:SetFrameLevel(parent.PortraitFrame:GetFrameLevel()+1) end parent = parent:GetParent() until not parent end function Help:AddHelpButton(parent, helpPlate, callback, anchor) local HelpButton = CreateFrame('Button', nil, parent, 'MainHelpPlateButton') HelpButton.helpPlate = helpPlate HelpButton:SetPoint('TOPLEFT', anchor or self, 'TOPLEFT', 39, 20) HelpButton:SetScript('OnClick', HelpOnClick) HelpButton:SetScript('OnHide', HelpOnHide) HelpButton:SetScript('OnShow', HelpOnShow) HelpButton.callback = callback self.helpButtons[parent] = HelpButton return HelpButton end function Help:HideHelpButtons() for _, button in pairs(self.helpButtons) do button:Hide() end HelpPlate_Hide() end function Help:ShowHelpButtons() for _, button in pairs(self.helpButtons) do button:Show() end end function Help:ShowHelpPlate(parent) local HelpButton = self.helpButtons[parent] if HelpButton then if not HelpPlate_IsShowing(HelpButton.helpPlate) then HelpButton:Click() end end end function Help:OnEmbed(target) target.helpButtons = {} end
mit
liruqi/bigfoot
Interface/AddOns/DBM-PvP/Battlegrounds/EyeOfTheStorm.lua
1
9707
-- EyeOfTheStorm mod v3.0 -- rewrite by Nitram and Tandanu -- -- thanks DiabloHu local mod = DBM:NewMod("z566", "DBM-PvP", 2) local L = mod:GetLocalizedStrings() mod:RemoveOption("HealthFrame") mod:SetRevision(("$Revision: 63 $"):sub(12, -3)) mod:SetZone(DBM_DISABLE_ZONE_DETECTION) mod:RegisterEvents( "ZONE_CHANGED_NEW_AREA" ) local bgzone = false local GetMapLandmarkInfo, GetNumMapLandmarks = C_WorldMap.GetMapLandmarkInfo, GetNumMapLandmarks local ResPerSec = { [0] = 1e-300, -- blah [1] = 1, [2] = 2, [3] = 5, [4] = 10, } local allyColor = { r = 0, g = 0, b = 1, } local hordeColor = { r = 1, g = 0, b = 0, } mod:AddBoolOption("ShowPointFrame", true, nil, function() if mod.Options.ShowPointFrame and bgzone then mod:ShowEstimatedPoints() else mod:HideEstimatedPoints() end end) local winTimer = mod:NewTimer(30, "TimerWin", "Interface\\Icons\\INV_Misc_PocketWatch_01") local flagTimer = mod:NewTimer(7, "TimerFlag", "Interface\\Icons\\INV_Banner_02") local objectives = { [1] = 6, -- Blood Elf [2] = 6, -- Draenai [3] = 6, -- Fel Reaver [4] = 6, -- Mage [5] = 45 -- Flag } local function isFlag(id) return id == 45 or id == 44 or id ==43 end local function isTower(id) return id == 6 or id == 10 or id == 11 end local function getBasecount() local alliance = 0 local horde = 0 for k,v in pairs(objectives) do if v == 11 then alliance = alliance + 1 elseif v == 10 then horde = horde + 1 end end return alliance, horde end local function getScore() if not bgzone then return 0, 0 end local ally, horde = 2, 3 for i = 1, 3 do if select(5, GetWorldStateUIInfo(i)) then if string.match(select(5, GetWorldStateUIInfo(i)), "Alliance") then--find -- "Interface\\TargetingFrame\\UI-PVP-Alliance", must be alliance. ally = i horde = i + 1 break end end end local allyScore = tonumber(string.match((select(4, GetWorldStateUIInfo(ally)) or ""), L.ScoreExpr)) or 0 local hordeScore = tonumber(string.match((select(4, GetWorldStateUIInfo(horde)) or ""), L.ScoreExpr)) or 0 return allyScore, hordeScore end local getGametime local updateGametime do local gametime = 0 function updateGametime() gametime = time() end function getGametime() local systime = GetBattlefieldInstanceRunTime() if systime > 0 then return systime / 1000 else return time() - gametime end end end do local function initialize() if DBM:GetCurrentArea() == 566 then bgzone = true mod:RegisterShortTermEvents( "CHAT_MSG_BG_SYSTEM_HORDE", "CHAT_MSG_BG_SYSTEM_ALLIANCE", "CHAT_MSG_BG_SYSTEM_NEUTRAL", "UPDATE_WORLD_STATES" ) updateGametime() for i=1, GetNumMapLandmarks(), 1 do local _, name, _, textureIndex = GetMapLandmarkInfo(i) if name and textureIndex then if isTower(textureIndex) or isFlag(textureIndex) then objectives[i] = textureIndex end end end if mod.Options.ShowPointFrame then mod:ShowEstimatedPoints() end elseif bgzone then bgzone = false mod:UnregisterShortTermEvents() if mod.Options.ShowPointFrame then mod:HideEstimatedPoints() end end end mod.OnInitialize = initialize function mod:ZONE_CHANGED_NEW_AREA() self:Schedule(1, initialize) end end do local function checkForUpdates() if not bgzone then return end for i = 1, GetNumMapLandmarks() do local _, name, _, textureIndex = GetMapLandmarkInfo(i) if name and textureIndex then if isTower(textureIndex) or isFlag(textureIndex) then objectives[i] = textureIndex end end end mod:UPDATE_WORLD_STATES() end local function scheduleCheck(self) self:Schedule(1, checkForUpdates) end function mod:CHAT_MSG_BG_SYSTEM_ALLIANCE(arg1) if self.Options.ShowPointFrame then if string.match(arg1, L.FlagTaken) then local name = string.match(arg1, L.FlagTaken) if name then self.AllyFlag = name self.HordeFlag = nil self:UpdateFlagDisplay() end elseif string.match(arg1, L.FlagDropped) then self.AllyFlag = nil self.HordeFlag = nil self:UpdateFlagDisplay() elseif string.match(arg1, L.FlagCaptured) then flagTimer:Start() self.AllyFlag = nil self.HordeFlag = nil self:UpdateFlagDisplay() end end scheduleCheck(self) end function mod:CHAT_MSG_BG_SYSTEM_HORDE(arg1) if self.Options.ShowPointFrame then if string.match(arg1, L.FlagTaken) then local name = string.match(arg1, L.FlagTaken) if name then self.AllyFlag = nil self.HordeFlag = name self:UpdateFlagDisplay() end elseif string.match(arg1, L.FlagDropped) then self.AllyFlag = nil self.HordeFlag = nil self:UpdateFlagDisplay() elseif string.match(arg1, L.FlagCaptured) then flagTimer:Start() self.AllyFlag = nil self.HordeFlag = nil self:UpdateFlagDisplay() end end scheduleCheck(self) end function mod:CHAT_MSG_BG_SYSTEM_NEUTRAL(arg1) if not bgzone then return end if string.match(arg1, L.FlagReset) then self.AllyFlag = nil self.HordeFlag = nil self:UpdateFlagDisplay() end scheduleCheck(self) end end function mod:UPDATE_WORLD_STATES() if not bgzone then return end local last_alliance_bases, last_horde_bases = getBasecount() local last_alliance_score, last_horde_score = getScore() -- calculate new times local AllyTime = (1500 - last_alliance_score) / ResPerSec[last_alliance_bases] local HordeTime = (1500 - last_horde_score) / ResPerSec[last_horde_bases] if AllyTime > 5000 then AllyTime = 5000 end if HordeTime > 5000 then HordeTime = 5000 end if AllyTime == HordeTime then winTimer:Stop() if self.ScoreFrame1Text then self.ScoreFrame1Text:SetText("") self.ScoreFrame2Text:SetText("") end elseif AllyTime > HordeTime then -- Horde wins winTimer:Update(getGametime(), getGametime()+HordeTime) winTimer:DisableEnlarge() local title = L.Horde or FACTION_HORDE--L.Horde is nil in english local, unless it's added to non english local, FACTION_HORDE will be used winTimer:UpdateName(L.WinBarText:format(title)) winTimer:SetColor(hordeColor) if self.ScoreFrame1Text and self.ScoreFrame2Text then local AllyPoints = math.floor((HordeTime * ResPerSec[last_alliance_bases]) + last_alliance_score) self.ScoreFrame1Text:SetText("("..AllyPoints..")") self.ScoreFrame2Text:SetText("(1500)") self:UpdateFlagDisplay() end elseif HordeTime > AllyTime then -- Alliance wins winTimer:Update(getGametime(), getGametime()+AllyTime) winTimer:DisableEnlarge() local title = L.Alliance or FACTION_ALLIANCE--L.Alliance is nil in english local, unless it's added to non english local, FACTION_ALLIANCE will be used winTimer:UpdateName(L.WinBarText:format(title)) winTimer:SetColor(allyColor) if self.ScoreFrame1Text and self.ScoreFrame2Text then local HordePoints = math.floor((HordeTime * ResPerSec[last_horde_bases]) + last_horde_score) self.ScoreFrame1Text:SetText("(1500)") self.ScoreFrame2Text:SetText("("..HordePoints..")") self:UpdateFlagDisplay() end end end function mod:UpdateFlagDisplay() if self.ScoreFrame1Text and self.ScoreFrame2Text then local newText local oldText = self.ScoreFrame1Text:GetText() local flagName = L.Flag or "Flag" if self.AllyFlag then if not oldText or oldText == "" then newText = "Flag: "..self.AllyFlag else newText = string.gsub(oldText, "%((%d+)%).*", "%(%1%) "..flagName..": "..self.AllyFlag) end elseif oldText and oldText ~= "" then newText = string.gsub(oldText, "%((%d+)%).*", "%(%1%)") end self.ScoreFrame1Text:SetText(newText) newText = nil oldText = self.ScoreFrame2Text:GetText() if self.HordeFlag then if not oldText or oldText == "" then newText = "Flag: "..self.HordeFlag else newText = string.gsub(oldText, "%((%d+)%).*", "%(%1%) "..flagName..": "..self.HordeFlag) end elseif oldText and oldText ~= "" then newText = string.gsub(oldText, "%((%d+)%).*", "%(%1%)") end self.ScoreFrame2Text:SetText(newText) end end function mod:ShowEstimatedPoints() if AlwaysUpFrame1 and AlwaysUpFrame2 then if not self.ScoreFrame1 then self.ScoreFrame1 = CreateFrame("Frame", nil, AlwaysUpFrame1) self.ScoreFrame1:SetHeight(10) self.ScoreFrame1:SetWidth(200) self.ScoreFrame1:SetPoint("LEFT", "AlwaysUpFrame1DynamicIconButton", "RIGHT", 4, 0) self.ScoreFrame1Text = self.ScoreFrame1:CreateFontString(nil, nil, "GameFontNormalSmall") self.ScoreFrame1Text:SetAllPoints(self.ScoreFrame1) self.ScoreFrame1Text:SetJustifyH("LEFT") end if not self.ScoreFrame2 then self.ScoreFrame2 = CreateFrame("Frame", nil, AlwaysUpFrame2) self.ScoreFrame2:SetHeight(10) self.ScoreFrame2:SetWidth(200) self.ScoreFrame2:SetPoint("LEFT", "AlwaysUpFrame2DynamicIconButton", "RIGHT", 4, 0) self.ScoreFrame2Text= self.ScoreFrame2:CreateFontString(nil, nil, "GameFontNormalSmall") self.ScoreFrame2Text:SetAllPoints(self.ScoreFrame2) self.ScoreFrame2Text:SetJustifyH("LEFT") end self.ScoreFrame1Text:SetText("") self.ScoreFrame1:Show() self.ScoreFrame2Text:SetText("") self.ScoreFrame2:Show() end end function mod:HideEstimatedPoints() if self.ScoreFrame1 and self.ScoreFrame2 then self.ScoreFrame1:Hide() self.ScoreFrame1Text:SetText("") self.ScoreFrame2:Hide() self.ScoreFrame2Text:SetText("") end end
mit
bjornbytes/RxLua
tests/flatMap.lua
2
1222
describe('flatMap', function() it('produces an error if its parent errors', function() local observable = Rx.Observable.of(''):flatMap(function(x) return x() end) expect(observable).to.produce.error() end) it('uses the identity function as the callback if none is specified', function() local observable = Rx.Observable.fromTable{ Rx.Observable.fromRange(3), Rx.Observable.fromRange(5) }:flatMap() expect(observable).to.produce(1, 2, 3, 1, 2, 3, 4, 5) end) it('produces all values produced by the observables produced by its parent', function() local observable = Rx.Observable.fromRange(3):flatMap(function(i) return Rx.Observable.fromRange(i, 3) end) expect(observable).to.produce(1, 2, 3, 2, 3, 3) end) it('completes after all observables produced by its parent', function() s = Rx.CooperativeScheduler.create() local observable = Rx.Observable.fromRange(3):flatMap(function(i) return Rx.Observable.fromRange(i, 3):delay(i, s) end) local onNext, onError, onCompleted, order = observableSpy(observable) repeat s:update(1) until s:isEmpty() expect(#onNext).to.equal(6) expect(#onCompleted).to.equal(1) end) end)
mit
Datamats/ServerContent
notagain/lua/notagain/jrpg/autorun/hitmarks.lua
1
17140
local hitmarkers = _G.hitmarkers or {} _G.hitmarkers = hitmarkers if CLIENT then local function set_blend_mode(how) if not render.OverrideBlendFunc then return end if how == "additive" then render.OverrideBlendFunc(true, BLEND_SRC_ALPHA, BLEND_ONE, BLEND_SRC_ALPHA, BLEND_ONE) elseif how == "multiplicative" then render.OverrideBlendFunc(true, BLEND_DST_COLOR, BLEND_ZERO, BLEND_DST_COLOR, BLEND_ZERO) else render.OverrideBlendFunc(false) end end local draw_line = requirex("draw_line") local draw_rect = requirex("draw_skewed_rect") local prettytext = requirex("pretty_text") local gradient = CreateMaterial(tostring({}), "UnlitGeneric", { ["$BaseTexture"] = "gui/center_gradient", ["$BaseTextureTransform"] = "center .5 .5 scale 1 1 rotate 90 translate 0 0", ["$VertexAlpha"] = 1, ["$VertexColor"] = 1, ["$Additive"] = 0, }) local border = CreateMaterial(tostring({}), "UnlitGeneric", { ["$BaseTexture"] = "props/metalduct001a", ["$VertexAlpha"] = 1, ["$VertexColor"] = 1, }) local function draw_health_bar(x,y, w,h, health, last_health, fade, border_size, skew) surface.SetDrawColor(200, 200, 200, 50*fade) draw.NoTexture() draw_rect(x,y,w,h, skew) surface.SetMaterial(gradient) surface.SetDrawColor(200, 50, 50, 255*fade) for _ = 1, 2 do draw_rect(x,y,w*last_health,h, skew, 0, 70, 5, gradient:GetTexture("$BaseTexture"):Width()) end surface.SetDrawColor(0, 200, 100, 255*fade) for _ = 1, 2 do draw_rect(x,y,w*health,h, skew, 0, 70, 5, gradient:GetTexture("$BaseTexture"):Width()) end surface.SetDrawColor(150, 150, 150, 255*fade) surface.SetMaterial(border) for _ = 1, 2 do draw_rect(x,y,w,h, skew, 1, 64,border_size, border:GetTexture("$BaseTexture"):Width(), true) end end local gradient = Material("gui/gradient_up") local border = CreateMaterial(tostring({}), "UnlitGeneric", { ["$BaseTexture"] = "props/metalduct001a", ["$VertexAlpha"] = 1, ["$VertexColor"] = 1, ["$Additive"] = 1, }) local function draw_weapon_info(x,y, w,h, color, fade) set_blend_mode("additive") local skew = 0 surface.SetDrawColor(25, 25, 25, 200*fade) draw.NoTexture() draw_rect(x,y,w,h, skew) surface.SetMaterial(gradient) surface.SetDrawColor(color.r, color.g, color.b, 255*fade) for _ = 1, 2 do draw_rect(x,y,w,h, skew) end surface.SetDrawColor(200, 200, 200, 255*fade) surface.SetMaterial(border) for _ = 1, 2 do draw_rect(x,y,w,h, skew, 3, 64,4, border:GetTexture("$BaseTexture"):Width(), true) end set_blend_mode() end local hitmark_fonts = { { min = 0, max = 0.25, font = "Gabriola", blur_size = 4, weight = 30, size = 100, color = Color(0, 0, 0, 255), }, { min = 0.25, max = 0.5, font = "Gabriola", blur_size = 4, weight = 30, size = 200, color = Color(150, 150, 50, 255), }, { min = 0.5, max = 1, font = "Gabriola", blur_size = 4, weight = 30, size = 300, color = Color(200, 50, 50, 255), }, { min = 1, max = math.huge, font = "Gabriola", blur_size = 4, weight = 100, size = 400, --color = Color(200, 50, 50, 255), }, } local function find_head_pos(ent) if not ent.bc_head or ent.bc_last_mdl ~= ent:GetModel() then for i = 0, ent:GetBoneCount() do local name = ent:GetBoneName(i):lower() if name:find("head") then ent.bc_head = i ent.bc_last_mdl = ent:GetModel() break end end end if ent.bc_head then return ent:GetBonePosition(ent.bc_head) end return ent:EyePos(), ent:EyeAngles() end local line_mat = Material("particle/Particle_Glow_04") local line_width = 8 local line_height = -31 local max_bounce = 2 local bounce_plane_height = 5 local life_time = 3 local hitmarks = {} local height_offset = 0 local health_bars = {} local weapon_info = {} hook.Add("HUDDrawTargetID", "hitmarks", function() return false end) local function surface_DrawTexturedRectRotatedPoint( x, y, w, h, rot) x = math.ceil(x) y = math.ceil(y) w = math.ceil(w) h = math.ceil(h) local y0 = -h/2 local x0 = -w/2 local c = math.cos( math.rad( rot ) ) local s = math.sin( math.rad( rot ) ) local newx = y0 * s - x0 * c local newy = y0 * c + x0 * s surface.DrawTexturedRectRotated( x + newx, y + newy, w, h, rot ) end -- close enough local function draw_RoundedBoxOutlined(border_size, x, y, w, h, color ) x = math.ceil(x) y = math.ceil(y) w = math.ceil(w) h = math.ceil(h) border_size = border_size/2 surface.SetDrawColor(color) surface.DrawRect(x, y, border_size*2, h, color) surface.DrawRect(x+border_size*2, y, w-border_size*4, border_size*2) surface.DrawRect(x+w-border_size*2, y, border_size*2, h) surface.DrawRect(x+border_size*2, y+h-border_size*2, w-border_size*4, border_size*2) end hook.Add("HUDPaint", "hitmarks", function() if hook.Call("HideHitmarks") then return end local ply = LocalPlayer() local boss_bar_y = 0 for i = #health_bars, 1, -1 do local data = health_bars[i] local ent = data.ent if ent:IsValid() then local t = RealTime() local fraction = (data.time - t) / life_time * 2 local name if ent:IsPlayer() then name = ent:Nick() else name = ent:GetClass() local npcs = ents.FindByClass(name) if npcs[2] then for i, other in ipairs(npcs) do other.hm_letter = string.char(64 + i%26) end end if language.GetPhrase(name) then name = language.GetPhrase(name) end if ent.hm_letter then name = name .. " " .. ent.hm_letter end end local pos = (ent:NearestPoint(ent:EyePos() + Vector(0,0,100000)) + Vector(0,0,2)):ToScreen() if pos.visible then surface.DrawRect(pos.x, pos.y, 1,1) local cur = ent.hm_cur_health or ent:Health() local max = ent.hm_max_health or ent:GetMaxHealth() local last = ent.hm_last_health or max if max == 0 or cur > max then max = 100 cur = 100 end if not ent.hm_last_health_time or ent.hm_last_health_time < CurTime() then last = cur end data.cur_health_smooth = data.cur_health_smooth or cur data.last_health_smooth = data.last_health_smooth or last data.cur_health_smooth = data.cur_health_smooth + ((cur - data.cur_health_smooth) * FrameTime() * 5) data.last_health_smooth = data.last_health_smooth + ((last - data.last_health_smooth) * FrameTime() * 5) local cur = data.cur_health_smooth local last = data.last_health_smooth local fade = math.Clamp(fraction ^ 0.25, 0, 1) local w, h = prettytext.GetTextSize(name, "Candara", 20, 30, 2) local height = 8 local border_size = 3 local skew = 0 local width = math.Clamp(ent:BoundingRadius() * 3.5 * (ent:GetModelScale() or 1), w * 1.5, ScrW()/2) if max > 1000 then height = 35 height = 35 pos.x = ScrW() / 2 pos.y = 50 + boss_bar_y width = ScrW() / 1.1 skew = 30 border_size = 10 boss_bar_y = boss_bar_y + height + 20 end local width2 = width/2 local text_x_offset = 15 draw_health_bar(pos.x - width2, pos.y-height/2, width, height, math.Clamp(cur / max, 0, 1), math.Clamp(last / max, 0, 1), fade, border_size, skew) prettytext.Draw(name, pos.x - width2 - text_x_offset, pos.y - 5, "Arial", 20, 800, 3, Color(230, 230, 230, 255 * fade), nil, 0, -1) end if fraction <= 0 then table.remove(health_bars, i) end end end for i = #weapon_info, 1, -1 do local data = weapon_info[i] local ent = data.ent if not ent:IsValid() then table.remove(weapon_info, i) continue end local pos = (ent:NearestPoint(ent:EyePos() + Vector(0,0,100000)) + Vector(0,0,2)):ToScreen() if pos.visible then local time = RealTime() if data.time > time then local fade = math.min(((data.time - time) / data.length) + 0.75, 1) local w, h = prettytext.GetTextSize(data.name, "Arial", 20, 800, 2) local x, y = pos.x, pos.y x = x - w / 2 y = y - h * 3 local bg local fg if ent == ply or (ent:IsPlayer() and (ent:GetFriendStatus() == "friend")) then fg = Color(200, 220, 255, 255 * fade) bg = Color(25, 75, 150, 255 * fade) else fg = Color(255, 220, 200, 255 * fade) bg = Color(200, 50, 25, 255) end local border = 13 local scale_h = 0.5 local border = border draw_weapon_info(x - border, y - border*scale_h, w + border*2, h + border*2*scale_h, bg, fade) prettytext.Draw(data.name, x, y, "Arial", 20, 600, 3, fg) else table.remove(weapon_info, i) end end end if hitmarks[1] then local d = FrameTime() for i = #hitmarks, 1, -1 do local data = hitmarks[i] local t = RealTime() + data.offset local fraction = (data.life - t) / life_time local pos = data.real_pos if data.ent:IsValid() then pos = LocalToWorld(data.real_pos, Angle(0,0,0), data.ent:GetPos(), data.first_angle) data.last_pos = pos else pos = data.last_pos or pos end local fade = math.Clamp(fraction ^ 0.25, 0, 1) if data.bounced < max_bounce then data.vel = data.vel + Vector(0,0,-0.25) data.vel = data.vel * 0.99 else data.vel = data.vel * 0.85 end if data.pos.z < -bounce_plane_height and data.bounced < max_bounce then data.vel.z = -data.vel.z * 0.5 data.pos.z = -bounce_plane_height data.bounced = data.bounced + 1 if data.bounced == max_bounce then data.vel.z = data.vel.z * -1 end end data.pos = data.pos + data.vel * d * 25 pos = (pos + data.pos + Vector(0, 0, bounce_plane_height)):ToScreen() local txt = math.Round(Lerp(math.Clamp(fraction-0.95, 0, 1), data.dmg, 0)) if data.dmg == 0 then txt = "MISS" elseif data.dmg > 0 then txt = "+" .. txt end if pos.visible then local x = pos.x + data.pos.x local y = pos.y + data.pos.y if fade < 0.5 then y = y + (fade-0.5)*150 end surface.SetAlphaMultiplier(fade) local fraction = -data.dmg / data.max_health local font_info = hitmark_fonts[1] for _, info in ipairs(hitmark_fonts) do if fraction >= info.min and fraction <= info.max then font_info = info break end end if fraction >= 1 then font_info.color = HSVToColor((t*500)%360, 0.75, 1) end local w, h = prettytext.GetTextSize(txt, font_info.font, font_info.size, font_info.weight, font_info.blur_size) local hoffset = data.height_offset * -h * 0.5 if data.dmg == 0 then surface.SetDrawColor(255, 255, 255, 255) elseif data.rec then surface.SetDrawColor(100, 255, 100, 255) else surface.SetDrawColor(255, 100, 100, 255) end surface.SetMaterial(line_mat) draw_line( x - w, hoffset + y + h + line_height, x - w + w * 3, hoffset + y + h + line_height, line_width, true ) prettytext.Draw(txt, x, hoffset + y, font_info.font, font_info.size, font_info.weight, font_info.blur_size, Color(255, 255, 255, 255), font_info.color) surface.SetAlphaMultiplier(1) end if fraction <= 0 then table.remove(hitmarks, i) end end end end) function hitmarkers.ShowHealth(ent, focus) if focus then table.Empty(health_bars) else for i, data in ipairs(health_bars) do if data.ent == ent then table.remove(health_bars, i) break end end end table.insert(health_bars, {ent = ent, time = focus and math.huge or (RealTime() + life_time * 2)}) end function hitmarkers.ShowAttack(ent, name) for i, data in ipairs(weapon_info) do if data.ent == ent then table.remove(weapon_info, i) break end end local length = 2 table.insert(weapon_info, {name = name, ent = ent, time = RealTime() + length, length = length}) end function hitmarkers.ShowDamage(ent, dmg, pos, type) ent = ent or NULL dmg = dmg or 0 pos = pos or ent:EyePos() if ent:IsValid() then pos = ent:WorldToLocal(pos) end local rec = dmg > 0 local vel = VectorRand() local offset = math.random() * 10 height_offset = (height_offset + 1)%5 table.insert( hitmarks, { ent = ent, first_angle = ent:IsValid() and ent:GetAngles() or Angle(0,0,0), real_pos = pos, dmg = dmg, max_health = ent.hm_max_health or dmg, life = RealTime() + offset + life_time + math.random(), dir = vel, pos = Vector(), vel = vel, rec = rec, offset = offset, height_offset = height_offset, bounced = 0, type = type, } ) hitmarkers.ShowHealth(ent) end timer.Create("hitmark", 0.25, 0, function() local ply = LocalPlayer() if not ply:IsValid() then return end local data = ply:GetEyeTrace() local ent = data.Entity if ent:IsNPC() or ent:IsPlayer() then hitmarkers.ShowHealth(ent) end for _, ent in pairs(ents.FindInSphere(ply:GetPos(), 1000)) do if ent:IsNPC() or ent:IsPlayer() then local wep = ent:GetActiveWeapon() local name if wep:IsValid() and wep:GetClass() ~= ent.hm_last_wep then name = wep:GetClass() ent.hm_last_wep = name end if ent:IsNPC() then local seq_name = ent:GetSequenceName(ent:GetSequence()):lower() if not seq_name:find("idle") and not seq_name:find("run") and not seq_name:find("walk") then local fixed = seq_name:gsub("shoot", "") fixed = fixed:gsub("attack", "") fixed = fixed:gsub("loop", "") if fixed:Trim() == "" or not fixed:find("[a-Z]") then name = seq_name else name = fixed end name = name:gsub("_", " ") name = name:gsub("%d", "") name = name:gsub("^%l", function(s) return s:upper() end) name = name:gsub(" %l", function(s) return s:upper() end) name = name:Trim() if name == "" then name = seq_name end end end if name then if language.GetPhrase(name) then name = language.GetPhrase(name) end hitmarkers.ShowAttack(ent, name) hitmarkers.ShowHealth(ent) end end end end) net.Receive("hitmark", function() local ent = net.ReadEntity() local dmg = math.Round(net.ReadFloat()) local pos = net.ReadVector() local cur = math.Round(net.ReadFloat()) local max = math.Round(net.ReadFloat()) local type = net.ReadInt(32) if not ent.hm_last_health_time or ent.hm_last_health_time < CurTime() then ent.hm_last_health = ent.hm_cur_health or max end ent.hm_last_health_time = CurTime() + 3 ent.hm_cur_health = cur ent.hm_max_health = max hitmarkers.ShowDamage(ent, dmg, pos, type) end) end if SERVER then function hitmarkers.ShowDamage(ent, dmg, pos, type, filter) ent = ent or NULL dmg = dmg or 0 pos = pos or ent:EyePos() type = type or 0 filter = filter or player.GetAll() net.Start("hitmark") net.WriteEntity(ent) net.WriteFloat(dmg) net.WriteVector(pos) net.WriteFloat(ent.ACF and ent.ACF.Health or ent.ee_cur_hp or ent:Health()) net.WriteFloat(ent.ACF and ent.ACF.MaxHealth or ent.ee_max_hp or ent:GetMaxHealth()) net.WriteInt(type, 32) net.Send(filter) end util.AddNetworkString("hitmark") hook.Add("EntityTakeDamage", "hitmarker", function(ent, dmg) if not (dmg:GetAttacker():IsNPC() or dmg:GetAttacker():IsPlayer()) then return end local filter = {} for k,v in pairs(player.GetAll()) do if v ~= ent and v:GetPos():Distance(ent:GetPos()) < 1500 * (ent:GetModelScale() or 1) then table.insert(filter, v) end end local last_health = ent:Health() local health = -dmg:GetDamage() local pos = dmg:GetDamagePosition() if pos == vector_origin then pos = ent:GetPos() end if ent.ee_cur_hp then last_health = ent.ee_cur_hp end timer.Simple(0, function() if ent:IsValid() then if ent.ee_cur_hp then health = -(last_health - ent.ee_cur_hp) elseif last_health == ent:Health() then if ent:IsNPC() or ent:IsPlayer() then health = 0 else return end elseif (ent:Health() - last_health) ~= health then health = ent:Health() - last_health end hitmarkers.ShowDamage(ent, health, pos, dmg:GetDamageType(), filter) end end) end) if ACF_Damage then old_ACF_Damage = old_ACF_Damage or ACF_Damage function ACF_Damage(...) local res = {old_ACF_Damage(...)} local data = res[1] if type(data) == "table" and data.Damage then local ent = select(1, ...) if IsEntity(ent) and ent:IsValid() and math.floor(data.Damage) ~= 0 then hitmarkers.ShowDamage(ent, -data.Damage, ent:GetPos(), data.Damage > 500) end end return unpack(res) end end timer.Create("hitmarker",1, 0, function() for _, ent in ipairs(ents.GetAll()) do if ent:IsPlayer() or ent:IsNPC() then if ent.hm_last_health ~= ent:Health() then local diff = ent:Health() - (ent.hm_last_health or 0) if diff > 0 then hitmarkers.ShowDamage(ent, diff) end ent.hm_last_health = ent:Health() end end end end) end return hitmarkers
mit
ff-kbu/openwrt-packages-bb
net/luci-app-ocserv/files/usr/lib/lua/luci/model/cbi/ocserv/main.lua
30
4979
--[[ LuCI - Lua Configuration Interface Copyright 2014 Nikos Mavrogiannopoulos <n.mavrogiannopoulos@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ local niulib = require "luci.niulib" ]]-- local fs = require "nixio.fs" local has_ipv6 = fs.access("/proc/net/ipv6_route") m = Map("ocserv", translate("OpenConnect VPN")) s = m:section(TypedSection, "ocserv", "OpenConnect") s.anonymous = true s:tab("general", translate("General Settings")) s:tab("ca", translate("CA certificate")) s:tab("template", translate("Edit Template")) local e = s:taboption("general", Flag, "enable", translate("Enable server")) e.rmempty = false e.default = "1" function m.on_commit(map) luci.sys.call("/usr/bin/occtl reload >/dev/null 2>&1") end function e.write(self, section, value) if value == "0" then luci.sys.call("/etc/init.d/ocserv stop >/dev/null 2>&1") luci.sys.call("/etc/init.d/ocserv disable >/dev/null 2>&1") else luci.sys.call("/etc/init.d/ocserv enable >/dev/null 2>&1") luci.sys.call("/etc/init.d/ocserv restart >/dev/null 2>&1") end Flag.write(self, section, value) end local o o = s:taboption("general", ListValue, "auth", translate("User Authentication"), translate("The authentication method for the users. The simplest is plain with a single username-password pair. Use PAM modules to authenticate using another server (e.g., LDAP, Radius).")) o.rmempty = false o.default = "plain" o:value("plain") o:value("PAM") o = s:taboption("general", Value, "zone", translate("Firewall Zone"), translate("The firewall zone that the VPN clients will be set to")) o.nocreate = true o.default = "lan" o.template = "cbi/firewall_zonelist" s:taboption("general", Value, "port", translate("Port"), translate("The same UDP and TCP ports will be used")) s:taboption("general", Value, "max_clients", translate("Max clients")) s:taboption("general", Value, "max_same", translate("Max same clients")) s:taboption("general", Value, "dpd", translate("Dead peer detection time (secs)")) local pip = s:taboption("general", Flag, "predictable_ips", translate("Predictable IPs"), translate("The assigned IPs will be selected deterministically")) pip.default = "1" local udp = s:taboption("general", Flag, "udp", translate("Enable UDP"), translate("Enable UDP channel support; this must be enabled unless you know what you are doing")) udp.default = "1" local cisco = s:taboption("general", Flag, "cisco_compat", translate("AnyConnect client compatibility"), translate("Enable support for CISCO AnyConnect clients")) cisco.default = "1" ipaddr = s:taboption("general", Value, "ipaddr", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Network-Address")) ipaddr.default = "192.168.100.1" nm = s:taboption("general", Value, "netmask", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")) nm.default = "255.255.255.0" nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") if has_ipv6 then ip6addr = s:taboption("general", Value, "ip6addr", translate("VPN <abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Network-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix")) end tmpl = s:taboption("template", Value, "_tmpl", translate("Edit the template that is used for generating the ocserv configuration.")) tmpl.template = "cbi/tvalue" tmpl.rows = 20 function tmpl.cfgvalue(self, section) return nixio.fs.readfile("/etc/ocserv/ocserv.conf.template") end function tmpl.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile("/etc/ocserv/ocserv.conf.template", value) end ca = s:taboption("ca", Value, "_ca", translate("View the CA certificate used by this server. You will need to save it as 'ca.pem' and import it into the clients.")) ca.template = "cbi/tvalue" ca.rows = 20 function ca.cfgvalue(self, section) return nixio.fs.readfile("/etc/ocserv/ca.pem") end --[[DNS]]-- s = m:section(TypedSection, "dns", translate("DNS servers"), translate("The DNS servers to be provided to clients; can be either IPv6 or IPv4")) s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s:option(Value, "ip", translate("IP Address")).rmempty = true --[[Routes]]-- s = m:section(TypedSection, "routes", translate("Routing table"), translate("The routing table to be provided to clients; you can mix IPv4 and IPv6 routes, the server will send only the appropriate. Leave empty to set a default route")) s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s:option(Value, "ip", translate("IP Address")).rmempty = true o = s:option(Value, "netmask", translate("Netmask (or IPv6-prefix)")) o.default = "255.255.255.0" o:value("255.255.255.0") o:value("255.255.0.0") o:value("255.0.0.0") return m
gpl-2.0
AngelBaltar/RenegadeKlingon
Utils/Advanced-Tiled-Loader/ObjectLayer.lua
1
6273
--------------------------------------------------------------------------------------------------- -- -= ObjectLayer =- --------------------------------------------------------------------------------------------------- -- Setup TILED_LOADER_PATH = "Utils/Advanced-Tiled-Loader/" TILED_LOADER_PATH = TILED_LOADER_PATH or ({...})[1]:gsub("[%.\\/][Oo]bject[Ll]ayer$", "") .. '.' local love = love local unpack = unpack local pairs = pairs local ipairs = ipairs local Object = require( TILED_LOADER_PATH .. "Object") local ObjectLayer = {class = "ObjectLayer"} local grey = {128,128,128,255} ObjectLayer.__index = ObjectLayer --------------------------------------------------------------------------------------------------- -- Creates and returns a new ObjectLayer function ObjectLayer:new(map, name, color, opacity, prop) -- Create a new table for our object layer and do some error checking. local layer = setmetatable({}, ObjectLayer) layer.map = map -- The map this layer belongs to layer.name = name or "Unnamed ObjectLayer" -- The name of this layer layer.color = color or grey -- The color theme layer.opacity = opacity or 1 -- The opacity layer.objects = {} -- The layer's objects indexed numerically layer.properties = prop or {} -- Properties set by Tiled. layer.visible = true -- If false then the layer will not be drawn -- Return the new object layer return layer end --------------------------------------------------------------------------------------------------- -- Creates a new object, automatically inserts it into the layer, and then returns it function ObjectLayer:newObject(name, type, x, y, width, height, gid, prop) local obj = Object:new(self, name, type, x, y, width, height, gid, prop) self.objects[#self.objects+1] = obj return obj end --------------------------------------------------------------------------------------------------- -- Sorting function for objects. We'll use this below in ObjectLayer:draw() local function drawSort(o1, o2) return o1.drawInfo.order < o2.drawInfo.order end --------------------------------------------------------------------------------------------------- -- Draws the object layer. The way the objects are drawn depends on the map orientation and -- if the object has an associated tile. It tries to draw the objects as closely to the way -- Tiled does it as possible. local di, dr, drawList, r, g, b, a, line, obj, offsetX, offsetY function ObjectLayer:draw() -- Early exit if the layer is not visible. if not self.visible then return end -- Exit if objects are not suppose to be drawn if not self.map.drawObjects then return end di = nil -- The draw info dr = {self.map:getDrawRange()} -- The drawing range. [1-4] = x, y, width, height drawList = {} -- A list of the objects to be drawn r,g,b,a = 255, 255, 255, 255 ---love.graphics.getColor() -- Save the color so we can set it back at the end line = love.graphics.getLineWidth() -- Save the line width too self.color[4] = 255 * self.opacity -- Set the opacity -- Put only objects that are on the screen in the draw list. If the screen range isn't defined -- add all objects for i = 1, #self.objects do obj = self.objects[i] obj:updateDrawInfo() di = obj.drawInfo if dr[1] and dr[2] and dr[3] and dr[4] then if di.right > dr[1]-20 and di.bottom > dr[2]-20 and di.left < dr[1]+dr[3]+20 and di.top < dr[2]+dr[4]+20 then drawList[#drawList+1] = obj end else drawList[#drawList+1] = obj end end -- Sort the draw list by the object's draw order table.sort(drawList, drawSort) -- Draw all the objects in the draw list. offsetX, offsetY = self.map.offsetX, self.map.offsetY for i = 1, #drawList do obj = drawList[i] love.graphics.setColor(r,b,g,a) drawList[i]:draw(di.x, di.y, unpack(self.color or neutralColor)) end -- Reset the color and line width love.graphics.setColor(r,b,g,a) love.graphics.setLineWidth(line) end --------------------------------------------------------------------------------------------------- -- Changes an object layer into a custom layer. A function can be passed to convert objects. function ObjectLayer:toCustomLayer(convert) if convert then for i = 1, #self.objects do self.objects[i] = convert(self.objects[i]) end end self.class = "CustomLayer" return setmetatable(self, nil) end --------------------------------------------------------------------------------------------------- -- Return the ObjectLayer class return ObjectLayer --[[Copyright (c) 2011-2012 Casey Baxter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.--]]
gpl-3.0
liruqi/bigfoot
Interface/AddOns/Bagnon/libs/LibItemCache-1.1/Caches/BagBrother.lua
1
3916
--[[ Copyright 2011-2016 João Cardoso LibItemCache is distributed under the terms of the GNU General Public License. You can redistribute it and/or modify it under the terms of the license as published by the Free Software Foundation. This library 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 library. If not, see <http://www.gnu.org/licenses/>. This file is part of LibItemCache. --]] local Lib = LibStub('LibItemCache-1.1') if not BagBrother or Lib:HasCache() then return end local Cache = Lib:NewCache() local LAST_BANK_SLOT = NUM_BAG_SLOTS + NUM_BANKBAGSLOTS local FIRST_BANK_SLOT = NUM_BAG_SLOTS + 1 local ITEM_COUNT = ';(%d+)$' local ITEM_ID = '^(%d+)' --[[ Items ]]-- function Cache:GetBag(realm, player, bag, tab, slot) if tab then local tab = self:GetGuildTab(realm, player, tab) if tab then return tab.name, tab.icon, tab.view, tab.deposit, tab.withdraw, nil, true end elseif slot then return self:GetItem(realm, player, 'equip', nil, slot) else return self:GetNormalBag(realm, player, bag) end end function Cache:GetItem(realm, player, bag, tab, slot) if tab then bag = self:GetGuildTab(realm, player, tab) else bag = self:GetNormalBag(realm, player, bag) end local item = bag and bag[slot] if item then return strsplit(';', item) end end function Cache:GetGuildTab(realm, player, tab) local name = self:GetGuild(realm, player) local guild = name and BrotherBags[realm][name .. '*'] return guild and guild[tab] end function Cache:GetNormalBag(realm, player, bag) return realm and player and BrotherBags[realm][player][bag] end --[[ Item Counts ]]-- function Cache:GetItemCounts(realm, player, id) local player = BrotherBags[realm][player] local bank = self:GetItemCount(player[BANK_CONTAINER], id) + self:GetItemCount(player[REAGENTBANK_CONTAINER], id) local equipment = self:GetItemCount(player.equip, id, true) local vault = self:GetItemCount(player.vault, id, true) local bags = 0 for i = BACKPACK_CONTAINER, NUM_BAG_SLOTS do bags = bags + self:GetItemCount(player[i], id) end for i = FIRST_BANK_SLOT, LAST_BANK_SLOT do bank = bank + self:GetItemCount(player[i], id) end return equipment, bags, bank, vault end function Cache:GetItemCount(bag, id, unique) local i = 0 if bag then for _,item in pairs(bag) do if strmatch(item, ITEM_ID) == id then i = i + (not unique and tonumber(strmatch(item, ITEM_COUNT)) or 1) end end end return i end --[[ Others ]]-- function Cache:GetGuild(realm, player) return BrotherBags[realm][player].guild end function Cache:GetMoney(realm, player) return BrotherBags[realm][player].money end --[[ Players ]]-- function Cache:GetPlayer(realm, player) realm = BrotherBags[realm] player = realm and realm[player] if player then return player.class, player.race, player.sex, player.faction and 'Alliance' or 'Horde' end end function Cache:DeletePlayer(realm, player) local realm = BrotherBags[realm] local guild = realm[player].guild realm[player] = nil if guild then for _, actor in pairs(realm) do if actor.guild == guild then return end end realm[guild .. '*'] = nil end end function Cache:GetPlayers(realm) local players = {} for name in pairs(BrotherBags[realm] or {}) do if not name:find('*$') then tinsert(players, name) end end return players end --[[ Realms ]]-- function Cache:GetRealms() local realms = {} for name in pairs(BrotherBags) do tinsert(realms, name) end return realms end
mit
borromeotlhs/nodemcu-firmware
lua_examples/yet-another-ds18b20.lua
79
1924
------------------------------------------------------------------------------ -- DS18B20 query module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- dofile("ds18b20.lua").read(4, function(r) for k, v in pairs(r) do print(k, v) end end) ------------------------------------------------------------------------------ local M do local bit = bit local format_addr = function(a) return ("%02x-%02x%02x%02x%02x%02x%02x"):format( a:byte(1), a:byte(7), a:byte(6), a:byte(5), a:byte(4), a:byte(3), a:byte(2) ) end local read = function(pin, cb, delay) local ow = require("ow") -- get list of relevant devices local d = { } ow.setup(pin) ow.reset_search(pin) while true do tmr.wdclr() local a = ow.search(pin) if not a then break end if ow.crc8(a) == 0 and (a:byte(1) == 0x10 or a:byte(1) == 0x28) then d[#d + 1] = a end end -- conversion command for all ow.reset(pin) ow.skip(pin) ow.write(pin, 0x44, 1) -- wait a bit tmr.alarm(0, delay or 100, 0, function() -- iterate over devices local r = { } for i = 1, #d do tmr.wdclr() -- read rom command ow.reset(pin) ow.select(pin, d[i]) ow.write(pin, 0xBE, 1) -- read data local x = ow.read_bytes(pin, 9) if ow.crc8(x) == 0 then local t = (x:byte(1) + x:byte(2) * 256) -- negatives? if bit.isset(t, 15) then t = 1 - bit.bxor(t, 0xffff) end -- NB: temperature in Celsius * 10^4 t = t * 625 -- NB: due 850000 means bad pullup. ignore if t ~= 850000 then r[format_addr(d[i])] = t end d[i] = nil end end cb(r) end) end -- expose M = { read = read, } end return M
mit
handsomecheung/miniKanren.lua
sudoku_example.lua
1
3987
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 cond = MK.cond local fresh_vars = MK.fresh_vars local list = MK.list local car = MK.car local cdr = MK.cdr local E = require("extend") local nullo = E.nullo local mergeo = E.mergeo local conso = E.conso ---------------------------------------------------------------------- ---------------- different functions --------------------------------- ---------------------------------------------------------------------- local function different_others(x, o) local a, d = fresh_vars(2) return cond( nullo(o), all( conso(a, d, o), not_eq(x, a), function(s) return different_others(x, d)(s) end )) end local function fd_all_different1(c1, a, c2) local c, new_c1, new_a, new_c2 = fresh_vars(4) return cond( nullo(c2), all( mergeo(c1, c2, c), different_others(a, c), conso(a, c1, new_c1), conso(new_a, new_c2, c2), function(s) return fd_all_different1(new_c1, new_a, new_c2)(s) end ) ) end local function fd_all_different(c) local c1, a, c2 = fresh_vars(3) return all( conso(a, c2, c), eq(c1, {}), fd_all_different1(c1, a, c2) ) end local function all_different(l) local a, d = fresh_vars(2) return cond( nullo(l), all( conso(a, d, l), fd_all_different(a), function(s) return all_different(d)(s) end )) end ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------- domain function ------------------------------------- ---------------------------------------------------------------------- local function fd_domain_4(l) local a, d = fresh_vars(2) return cond( nullo(l), all( conso(a, d, l), cond( eq(a, 1), eq(a, 2), eq(a, 3), eq(a, 4)), function(s) return fd_domain_4(d)(s) end)) end ---------------------------------------------------------------------- local function v() return fresh_vars(1) end local function list2table(list, t) if #list == 0 then return t else table.insert(t, car(list)) return list2table(cdr(list), t) end end local function sudoku_4x4(puzzle) puzzle = list(unpack(puzzle)) local s11 , s12, s13, s14, s21 , s22, s23, s24, s31 , s32, s33, s34, s41 , s42, s43, s44, row1, row2, row3, row4, col1, col2, col3, col4, square1, square2, square3, square4 = fresh_vars(28) local r = run(1, puzzle, all( eq(puzzle, list(s11, s12, s13, s14, s21, s22, s23, s24, s31, s32, s33, s34, s41, s42, s43, s44)), eq(row1, list(s11, s12, s13, s14)), eq(row2, list(s21, s22, s23, s24)), eq(row3, list(s31, s32, s33, s34)), eq(row4, list(s41, s42, s43, s44)), eq(col1, list(s11, s21, s31, s41)), eq(col2, list(s12, s22, s32, s42)), eq(col3, list(s13, s23, s33, s43)), eq(col4, list(s14, s24, s34, s44)), eq(square1, list(s11, s12, s21, s22)), eq(square2, list(s13, s14, s23, s24)), eq(square3, list(s31, s32, s41, s42)), eq(square4, list(s33, s34, s43, s44)), all_different(list(row1, row2, row3, row4, col1, col2, col3, col4, square1, square2, square3, square4)), fd_domain_4(puzzle) )) return #r == 0 and r or list2table(r[1], {}) end local l = { v(), v(), 2 , 3 , v(), 2 , v(), v(), 2 , v(), v(), v(), v(), v(), 1 , 2 , } sudoku_4x4(l) -- { 1, 4, 2, 3, -- 3, 2, 4, 1, -- 2, 1, 3, 4, -- 4, 3, 1, 2 }
mit
liruqi/bigfoot
Interface/AddOns/WhisperPop/VirtualScrollList-1.0.lua
1
19203
----------------------------------------------------------- -- VirtualScrollList-1.0.lua ----------------------------------------------------------- -- A virtual scroll list is a scroll list frame that is capable of displaying infinite -- amount of user data with a fixed number of list buttons. Blizzard's FauxScrollFrame -- does basically the same thing, though this one is far more powerful and convenient to use. -- -- Abin (2010-1-27) ----------------------------------------------------------- -- API Documentation: ----------------------------------------------------------- -- frame = UICreateVirtualScrollList("name", parent, maxButtons [, selectable [, "buttonTemplate"]) -- Create a virtual scroll list frame -- frame:GetScrollOffset() -- Return current scroll offset (0-N) -- frame:SetScrollOffset(offset) -- Scroll the list -- frame:CheckVisible([position]) -- Check whether a position is visible in the list (nil-invalid, 0-visible, other-invisible), "position" defaults to current selection -- frame:EnsureVisible([position]) -- Ensure a position being visible, scroll the list if needed, "position" defaults to current selection -- frame:RefreshContents() -- Refresh the entire list, call only when necessary! -- frame:SetSelection(position) -- Select a data -- frame:GetSelection() -- Get current selection -- frame:GetDataCount() -- Return number of data in the list -- frame:GetData(position) -- Retrieve a particular data -- frame:SetData(position, data) -- Modify an existing data -- frame:FindData(data [, compareFunc]) == Search for the first match of a particular data -- frame:InsertData(data [, position]) -- Insert a new data to the list, by default the data is inserted at the end of list -- frame:RemoveData(position) -- Remove an existing data, by default it removes the last data from the list -- frame:ShiftData(position1, position2) -- Shift a data from position1 to position2 -- frame:SwapData(position1, position2) -- Swap 2 data in the list -- frame:UpdateData(position) -- Call frame:OnButtonUpdate(button, data) if the list button reflects to position is visible at the moment -- frame:Clear() -- Clear the list, all data are deleted ----------------------------------------------------------- -- Callback Methods: ----------------------------------------------------------- -- frame:OnButtonCreated(button) -- Called when a new list button is created -- frame:OnButtonUpdate(button, data) -- Called when a list button needs to be re-painted -- frame:OnButtonTooltip(button, data) -- Called when the mouse hovers a list button, you only need to populate texts into GameTooltip -- frame:OnButtonEnter(button, data, motion) -- Called when the mouse hovers a list button -- frame:OnButtonLeave(button, data, motion) -- Called when the mouse leaves a list button -- frame:OnButtonClick(button, data, flag, down) -- Called when a list button is clicked -- frame:OnSelectionChanged(position, data) -- Called when the selection changed ----------------------------------------------------------- local MAJOR_VERSION = 1 local MINOR_VERSION = 10 -- To prevent older libraries from over-riding newer ones... if type(UICreateVirtualScrollList_IsNewerVersion) == "function" and not UICreateVirtualScrollList_IsNewerVersion(MAJOR_VERSION, MINOR_VERSION) then return end local NIL = "!2BFF-1B787839!" local function EncodeData(data) return (data == nil) and NIL or data -- Must be nil, not false end local function DecodeData(data) return (data ~= NIL) and data or nil end local function SafeCall(func, ...) if type(func) == "function" then return func(...) end end -- Update slider buttons stats: enable/disable according to scroll range and offset local function Slider_UpdateSliderButtons(self) local low, high = self:GetMinMaxValues() local value = self:GetValue() local up = self:GetParent().Up local down = self:GetParent().Down if low and high and value then if value <= low then up:Disable() else up:Enable() end if value >= high then down:Disable() else down:Enable() end end end local function ScrollBar_Button_OnClick(self) local slider = self:GetParent().slider slider:SetValue(slider:GetValue() + self.value) end -- Create slider button: Up/Down local function ScrollBar_CreateScrollButton(self, value) local button = CreateFrame("Button", self:GetName()..value.."Button", self, "UIPanelScroll"..value.."ButtonTemplate") button.value = value == "Up" and -1 or 1 self[value] = button button:SetWidth(16) button:SetHeight(14) button:SetPoint(value == "Up" and "TOP" or "BOTTOM") button:Disable() button:SetScript("OnClick", ScrollBar_Button_OnClick) end -- Apply or remove a texture(highlight/checked) to/from a particular list button local function Frame_TextureButton(self, textureName, button) local texture = self[textureName] if texture then if button then if texture.button ~= button then texture.button = button texture:SetParent(button) texture:ClearAllPoints() texture:SetAllPoints(button) texture:Show() end else texture.button = nil texture:Hide() end end end -- Schedule a frame refresh local function Frame_ScheduleRefresh(self) self.needRefresh = 1 end local function Frame_GetScrollOffset(self) return self.slider:GetValue() end local function Frame_SetScrollOffset(self, offset) if type(offset) == "number" then self.slider:SetValue(offset) return Frame_GetScrollOffset(self) end end local function ListButton_OnEnter(self, motion) local parent = self:GetParent() Frame_TextureButton(parent, "highlightTexture", self) SafeCall(parent.OnButtonEnter, parent, self, self.data, motion) if type(parent.OnButtonTooltip) == "function" then GameTooltip:SetOwner(self, "ANCHOR_LEFT") GameTooltip:ClearLines() parent:OnButtonTooltip(self, self.data) GameTooltip:Show() end end local function ListButton_OnLeave(self, motion) local parent = self:GetParent() Frame_TextureButton(parent, "highlightTexture") -- if parent.OnButtonTooltip then GameTooltip:Hide() -- end SafeCall(parent.OnButtonLeave, parent, self, self.data, motion) end local function ListButton_OnClick(self, flag, down) local parent = self:GetParent() if flag == "LeftButton" and parent.selectable then local dataIndex = self:GetID() + Frame_GetScrollOffset(parent) if parent.selection ~= dataIndex then Frame_TextureButton(self:GetParent(), "checkedTexture", self) parent.selection = dataIndex SafeCall(parent.OnSelectionChanged, parent, dataIndex, self.data) end end SafeCall(parent.OnButtonClick, parent, self, self.data, flag, down) end -- Get the list button which is currently displaying the given data local function Frame_PositionToButton(self, position) return self.listButtons[position - Frame_GetScrollOffset(self)] end local function Frame_UpdateButtonData(self, position) local button = Frame_PositionToButton(self, position) if button then button.data = DecodeData(self.listData[position]) SafeCall(self.OnButtonUpdate, self, button, button.data) end end -- Create a list button local function Frame_CreateListButton(self, id) local button = CreateFrame("Button", self:GetName().."Button"..id, self, self.buttonTemplate) button:SetID(id) if button:GetHeight() == 0 then button:SetHeight(20) end local prev = self.listButtons[id - 1] if prev then button:SetPoint("TOPLEFT", prev, "BOTTOMLEFT") button:SetPoint("TOPRIGHT", prev, "BOTTOMRIGHT") else button:SetPoint("TOPLEFT") button:SetPoint("TOPRIGHT", self.scrollBar, "TOPLEFT") end tinsert(self.listButtons, button) SafeCall(self.OnButtonCreated, self, button, id) button:HookScript("OnEnter", ListButton_OnEnter) button:HookScript("OnLeave", ListButton_OnLeave) button:HookScript("OnClick", ListButton_OnClick) return button end local function Frame_CheckVisible(self, position) if not position then position = self.selection end if type(position) ~= "number" or not self.listData[position] then return end local low = Frame_GetScrollOffset(self) + 1 local high = low + self.maxButtons - 1 if position < low then return position - low elseif position > high then return position - high else return 0 end end local function Frame_EnsureVisible(self, position) local visible = Frame_CheckVisible(self, position) if visible then if visible ~= 0 then Frame_SetScrollOffset(self, Frame_GetScrollOffset(self) + visible) end return 1 end end -- Update list buttons' contents, gives the user a chance to re-paint buttons local function Frame_UpdateList(self) local offset = self.slider:GetValue() local i, checkedButton for i = 1, self.maxButtons do local button = self.listButtons[i] local dataIndex = i + offset local data = self.listData[dataIndex] if data ~= nil then if not button then button = Frame_CreateListButton(self, i) end if not checkedButton and self.selection == dataIndex then checkedButton = button end button.data = DecodeData(data) SafeCall(self.OnButtonUpdate, self, button, button.data) button:Hide() button:Show() elseif button then button.data = nil button:Hide() end end Frame_TextureButton(self, "checkedTexture", checkedButton) end -- Refresh list contents including scroll bar stats after the list frame is resized or data are inserted/removed local function Frame_RefreshContents(self) self.needRefresh = nil local scrollBar = self.scrollBar local slider = self.slider local maxButtons = self.maxButtons local dataCount = #(self.listData) local range = max(0, dataCount - maxButtons) if range > 0 then slider.thumb:SetHeight(max(6, slider:GetHeight() * (maxButtons / dataCount))) scrollBar:SetWidth(14) scrollBar:Show() else scrollBar:Hide() scrollBar:SetWidth(1) end slider:SetMinMaxValues(0, range) if slider:GetValue() > range then slider:SetValue(range) else Frame_UpdateList(self) end end local function Slider_OnValueChanged(self, value) Frame_UpdateList(self.listFrame) end local function Frame_GetDataCount(self) return #(self.listData) end local function Frame_FindData(self, data, compareFunc) compareFunc = type(compareFunc) == "function" and compareFunc local i, stored for i, stored in ipairs(self.listData) do local d = DecodeData(stored) if compareFunc then if compareFunc(d, data) then return i end else if d == data then return i end end end end local function Frame_GetData(self, position) return DecodeData(self.listData[position]) end local function Frame_SetData(self, position, data) if self.listData[position] then self.listData[position] = EncodeData(data) Frame_UpdateButtonData(self, position) return 1 end end local function Frame_InsertData(self, data, position) local limit = #(self.listData) + 1 position = type(position) == "number" and min(limit, max(1, floor(position))) or limit tinsert(self.listData, position, EncodeData(data)) if self.selection and self.selection >= position then self.selection = self.selection + 1 SafeCall(self.OnSelectionChanged, self, self.selection, Frame_GetData(self, self.selection)) end Frame_ScheduleRefresh(self) return position end local function Frame_RemoveData(self, position) local data if type(position) == "number" then data = tremove(self.listData, position) else position = #(self.listData) data = tremove(self.listData) end if not data then return end if self.selection and self.selection >= position then if self.selection == position then self.selection = nil else self.selection = self.selection - 1 end SafeCall(self.OnSelectionChanged, self, self.selection, Frame_GetData(self, self.selection)) end Frame_ScheduleRefresh(self) return DecodeData(data) end local function Frame_ShiftData(self, position1, position2) if type(position1) ~= "number" or type(position2) ~= "number" or position1 == position2 then return end if not self.listData[position1] or not self.listData[position2] then return end tinsert(self.listData, position2, tremove(self.listData, position1)) if self.selection then local selection = self.selection if selection == position1 then selection = position2 elseif position1 < position2 then if selection > position1 and selection <= position2 then selection = selection - 1 end elseif position1 > position2 then if selection >= position2 and selection < position1 then selection = selection + 1 end end if self.selection ~= selection then self.selection = selection SafeCall(self.OnSelectionChanged, self, selection, Frame_GetData(self, selection)) end end Frame_UpdateList(self) return 1 end local function Frame_SwapData(self, position1, position2) if type(position1) ~= "number" or type(position2) ~= "number" or position1 == position2 then return end local data1 = self.listData[position1] local data2 = self.listData[position2] if data1 and data2 then self.listData[position1] = data2 self.listData[position2] = data1 Frame_UpdateButtonData(self, position1) Frame_UpdateButtonData(self, position2) if self.selection == position1 then Frame_SetSelection(self, position2) elseif self.selection == position2 then Frame_SetSelection(self, position1) end return 1 end end local function Frame_UpdateData(self, position) if type(self.OnButtonUpdate) ~= "function" then return end local data = self.listData[position] if not data then return end local low = Frame_GetScrollOffset(self) + 1 local high = low + self.maxButtons - 1 if position < low or position > high then return end local button = Frame_PositionToButton(self, position) if button then self:OnButtonUpdate(button, DecodeData(data)) return 1 end end local function Frame_Clear(self) wipe(self.listData) Frame_SetScrollOffset(self, 0) if self.selection then self.selection = nil SafeCall(self.OnSelectionChanged, self) end Frame_RefreshContents(self) end local function Frame_GetSelection(self) if self.selection then local data = self.listData[self.selection] return self.selection, DecodeData(data) end end local function Frame_SetSelection(self, position) if not self.selectable or type(position) ~= "number" or not self.listData[position] then return end if self.selection ~= position then self.selection = position Frame_TextureButton(self, "checkedTexture", Frame_PositionToButton(self, position)) SafeCall(self.OnSelectionChanged, self, position, Frame_GetData(self, position)) end return 1 end local function Frame_OnMouseWheel(self, value) local slider = self.slider local _, range = slider:GetMinMaxValues() if range > 0 then slider:SetValue(slider:GetValue() - max(1, range / 10) * value) end end local function Frame_OnUpdate(self) if self.needRefresh then Frame_RefreshContents(self) end end -- Create the scroll list frame function UICreateVirtualScrollList(name, parent, maxButtons, selectable, buttonTemplate) if type(name) ~= "string" then error(format("bad argument #1 to 'UICreateVirtualScrollList' (string expected, got %s)", type(name))) return end local frame = CreateFrame("Frame", name, parent) if not frame then error("'UICreateVirtualScrollList' frame creation failed, check name and parent") return end frame:EnableMouseWheel(true) frame.maxButtons = type(maxButtons) == "number" and max(1, floor(maxButtons)) or 1 frame.selectable = selectable frame.buttonTemplate = type(buttonTemplate) == "string" and buttonTemplate or nil frame.listButtons = {} frame.listData = {} local scrollBar = CreateFrame("Frame", name.."ScrollBar", frame) frame.scrollBar = scrollBar scrollBar:Hide() scrollBar:SetWidth(1) scrollBar:SetPoint("TOPRIGHT") scrollBar:SetPoint("BOTTOMRIGHT") ScrollBar_CreateScrollButton(scrollBar, "Up") ScrollBar_CreateScrollButton(scrollBar, "Down") local slider = CreateFrame("Slider", scrollBar:GetName().."Slider", scrollBar) frame.slider = slider scrollBar.slider = slider slider.listFrame = frame slider:SetValueStep(1) slider:SetWidth(14) slider:SetPoint("TOP", scrollBar.Up, "BOTTOM", 0, -1) slider:SetPoint("BOTTOM", scrollBar.Down, "TOP", 0, 1) slider:SetMinMaxValues(0, 0) slider:SetValue(0) hooksecurefunc(slider, "SetMinMaxValues", Slider_UpdateSliderButtons) hooksecurefunc(slider, "SetValue", Slider_UpdateSliderButtons) local thumb = slider:CreateTexture(name.."SliderThumbTexture", "OVERLAY") slider.thumb = thumb thumb:SetTexture("Interface\\ChatFrame\\ChatFrameBackground") thumb:SetWidth(slider:GetWidth()) thumb:SetGradientAlpha("HORIZONTAL", 0.5, 0.5, 0.5, 0.75, 0.15, 0.15, 0.15, 1) slider:SetThumbTexture(thumb) slider:SetScript("OnValueChanged", Slider_OnValueChanged) frame.highlightTexture = frame:CreateTexture(name.."HighlightTexture", "BORDER") frame.highlightTexture:Hide() frame.highlightTexture:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight") frame.highlightTexture:SetBlendMode("ADD") frame.highlightTexture:SetVertexColor(1, 1, 1, 0.7) if selectable then frame.checkedTexture = frame:CreateTexture(name.."CheckedTexture", "BORDER") frame.checkedTexture:Hide() frame.checkedTexture:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight") frame.checkedTexture:SetBlendMode("ADD") frame.checkedTexture:SetVertexColor(1, 1, 1, 0.7) end frame:SetScript("OnShow", Frame_RefreshContents) frame:SetScript("OnSizeChanged", Frame_RefreshContents) frame:SetScript("OnMouseWheel", Frame_OnMouseWheel) frame:SetScript("OnUpdate", Frame_OnUpdate) frame.needRefresh = 1 -- Public API frame.GetSelection = Frame_GetSelection frame.SetSelection = Frame_SetSelection frame.GetScrollOffset = Frame_GetScrollOffset frame.SetScrollOffset = Frame_SetScrollOffset frame.CheckVisible = Frame_CheckVisible frame.EnsureVisible = Frame_EnsureVisible frame.GetDataCount = Frame_GetDataCount frame.GetData = Frame_GetData frame.SetData = Frame_SetData frame.FindData = Frame_FindData frame.InsertData = Frame_InsertData frame.RemoveData = Frame_RemoveData frame.ShiftData = Frame_ShiftData frame.SwapData = Frame_SwapData frame.UpdateData = Frame_UpdateData frame.Clear = Frame_Clear frame.RefreshContents = Frame_RefreshContents return frame end -- Provides version check function UICreateVirtualScrollList_IsNewerVersion(major, minor) if type(major) ~= "number" or type(minor) ~= "number" then return false end if major > MAJOR_VERSION then return true elseif major < MAJOR_VERSION then return false else -- major equal, check minor return minor > MINOR_VERSION end end
mit
Yonaba/Algorithm-Implementations
Breadth_First_Search/Lua/Yonaba/bfs_test.lua
26
2339
-- Tests for bfs.lua local BFS = require 'bfs' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function same(t, p, comp) for k,v in ipairs(t) do if not comp(v, p[k]) then return false end end return true end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Testing linear graph', function() local comp = function(a, b) return a.value == b end local ln_handler = require 'handlers.linear_handler' ln_handler.init(-2,5) local bfs = BFS(ln_handler) local start, goal = ln_handler.getNode(0), ln_handler.getNode(5) assert(same(bfs:findPath(start, goal), {0,1,2,3,4,5}, comp)) start, goal = ln_handler.getNode(-2), ln_handler.getNode(2) assert(same(bfs:findPath(start, goal), {-2,-1,0,1,2}, comp)) end) run('Testing grid graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local gm_handler = require 'handlers.gridmap_handler' local bfs = BFS(gm_handler) local map = {{0,0,0,0,0},{0,1,1,1,1},{0,0,0,0,0}} gm_handler.init(map) gm_handler.diagonal = false local start, goal = gm_handler.getNode(1,1), gm_handler.getNode(5,3) assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{1,3},{2,3},{3,3},{4,3},{5,3}}, comp)) gm_handler.diagonal = true assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{2,3},{3,3},{4,3},{5,3}}, comp)) end) run('Testing point graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local pg_handler = require 'handlers.point_graph_handler' local bfs = BFS(pg_handler) pg_handler.addNode('a') pg_handler.addNode('b') pg_handler.addNode('c') pg_handler.addNode('d') pg_handler.addEdge('a', 'b') pg_handler.addEdge('a', 'c') pg_handler.addEdge('b', 'd') local comp = function(a, b) return a.name == b end local start, goal = pg_handler.getNode('a'), pg_handler.getNode('d') assert(same(bfs:findPath(start, goal), {'a','b','d'}, comp)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
shiprabehera/kong
spec/03-plugins/25-response-rate-limiting/04-access_spec.lua
2
25338
local cjson = require "cjson" local helpers = require "spec.helpers" local timestamp = require "kong.tools.timestamp" local REDIS_HOST = "127.0.0.1" local REDIS_PORT = 6379 local REDIS_PASSWORD = "" local REDIS_DATABASE = 1 local SLEEP_TIME = 1 local function wait(second_offset) -- If the minute elapses in the middle of the test, then the test will -- fail. So we give it this test 30 seconds to execute, and if the second -- of the current minute is > 30, then we wait till the new minute kicks in local current_second = timestamp.get_timetable().sec if current_second > (second_offset or 0) then ngx.sleep(60 - current_second) end end wait() -- Wait before starting local function flush_redis() local redis = require "resty.redis" local red = redis:new() red:set_timeout(2000) local ok, err = red:connect(REDIS_HOST, REDIS_PORT) if not ok then error("failed to connect to Redis: " .. err) end if REDIS_PASSWORD and REDIS_PASSWORD ~= "" then local ok, err = red:auth(REDIS_PASSWORD) if not ok then error("failed to connect to Redis: " .. err) end end local ok, err = red:select(REDIS_DATABASE) if not ok then error("failed to change Redis database: " .. err) end red:flushall() red:close() end for i, policy in ipairs({"local", "cluster", "redis"}) do describe("#ci Plugin: response-ratelimiting (access) with policy: " .. policy, function() setup(function() flush_redis() helpers.dao:drop_schema() helpers.run_migrations() local consumer1 = assert(helpers.dao.consumers:insert {custom_id = "provider_123"}) assert(helpers.dao.keyauth_credentials:insert { key = "apikey123", consumer_id = consumer1.id }) local consumer2 = assert(helpers.dao.consumers:insert {custom_id = "provider_124"}) assert(helpers.dao.keyauth_credentials:insert { key = "apikey124", consumer_id = consumer2.id }) local consumer3 = assert(helpers.dao.consumers:insert {custom_id = "provider_125"}) assert(helpers.dao.keyauth_credentials:insert { key = "apikey125", consumer_id = consumer3.id }) local api = assert(helpers.dao.apis:insert { name = "test1_com", hosts = { "test1.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, config = { fault_tolerant = false, policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, redis_database = REDIS_DATABASE, limits = {video = {minute = 6}} } }) api = assert(helpers.dao.apis:insert { name = "test2_com", hosts = { "test2.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, config = { fault_tolerant = false, policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, redis_database = REDIS_DATABASE, limits = {video = {minute = 6, hour = 10}, image = {minute = 4}} } }) api = assert(helpers.dao.apis:insert { name = "test3_com", hosts = { "test3.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "key-auth", api_id = api.id }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, config = {limits = {video = {minute = 6}}} }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, consumer_id = consumer1.id, config = { fault_tolerant = false, policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, redis_database = REDIS_DATABASE, limits = {video = {minute = 2}} } }) api = assert(helpers.dao.apis:insert { name = "test4_com", hosts = { "test4.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, config = { fault_tolerant = false, policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, redis_database = REDIS_DATABASE, limits = {video = {minute = 6}, image = {minute = 4}} } }) api = assert(helpers.dao.apis:insert { name = "test7_com", hosts = { "test7.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, config = { fault_tolerant = false, policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, redis_database = REDIS_DATABASE, block_on_first_violation = true, limits = { video = { minute = 6, hour = 10 }, image = { minute = 4 } } } }) api = assert(helpers.dao.apis:insert { name = "test8_com", hosts = { "test8.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, config = { fault_tolerant = false, policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, redis_database = REDIS_DATABASE, limits = {video = {minute = 6, hour = 10}, image = {minute = 4}} } }) api = assert(helpers.dao.apis:insert { name = "test9_com", hosts = { "test9.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, config = { fault_tolerant = false, policy = policy, hide_client_headers = true, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, redis_database = REDIS_DATABASE, limits = {video = {minute = 6}} } }) assert(helpers.start_kong()) end) teardown(function() helpers.stop_kong() end) local client, admin_client before_each(function() wait(45) client = helpers.proxy_client() admin_client = helpers.admin_client() end) after_each(function() if client then client:close() end if admin_client then admin_client:close() end end) describe("Without authentication (IP address)", function() it("blocks if exceeding limit", function() for i = 1, 6 do local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=1, test=5", headers = { ["Host"] = "test1.com" } }) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit assert.res_status(200, res) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(6 - i, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) end local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=1", headers = { ["Host"] = "test1.com" } }) local body = assert.res_status(429, res) assert.equal([[]], body) end) it("handles multiple limits", function() for i = 1, 3 do local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=2, image=1", headers = { ["Host"] = "test2.com" } }) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit assert.res_status(200, res) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(6 - (i * 2), tonumber(res.headers["x-ratelimit-remaining-video-minute"])) assert.equal(10, tonumber(res.headers["x-ratelimit-limit-video-hour"])) assert.equal(10 - (i * 2), tonumber(res.headers["x-ratelimit-remaining-video-hour"])) assert.equal(4, tonumber(res.headers["x-ratelimit-limit-image-minute"])) assert.equal(4 - i, tonumber(res.headers["x-ratelimit-remaining-image-minute"])) end local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=2, image=1", headers = { ["Host"] = "test2.com" } }) local body = assert.res_status(429, res) assert.equal([[]], body) assert.equal(0, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) assert.equal(4, tonumber(res.headers["x-ratelimit-remaining-video-hour"])) assert.equal(1, tonumber(res.headers["x-ratelimit-remaining-image-minute"])) end) end) describe("With authentication", function() describe("API-specific plugin", function() it("blocks if exceeding limit and a per consumer setting", function() for i = 1, 2 do local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?apikey=apikey123&x-kong-limit=video=1", headers = { ["Host"] = "test3.com" } }) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit assert.res_status(200, res) assert.equal(2, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(2 - i, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) end -- Third query, while limit is 2/minute local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?apikey=apikey123&x-kong-limit=video=1", headers = { ["Host"] = "test3.com" } }) local body = assert.res_status(429, res) assert.equal([[]], body) assert.equal(0, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) assert.equal(2, tonumber(res.headers["x-ratelimit-limit-video-minute"])) end) it("blocks if exceeding limit and a per consumer setting", function() for i = 1, 6 do local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?apikey=apikey124&x-kong-limit=video=1", headers = { ["Host"] = "test3.com" } }) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit assert.res_status(200, res) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(6 - i, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) end local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?apikey=apikey124", headers = { ["Host"] = "test3.com" } }) assert.res_status(200, res) assert.equal(0, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) end) it("blocks if exceeding limit", function() for i = 1, 6 do local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?apikey=apikey125&x-kong-limit=video=1", headers = { ["Host"] = "test3.com" } }) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit assert.res_status(200, res) assert.are.same(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.are.same(6 - i, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) end -- Third query, while limit is 2/minute local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?apikey=apikey125&x-kong-limit=video=1", headers = { ["Host"] = "test3.com" } }) local body = assert.res_status(429, res) assert.equal([[]], body) assert.equal(0, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) end) end) end) describe("Upstream usage headers", function() it("should append the headers with multiple limits", function() local res = assert(helpers.proxy_client():send { method = "GET", path = "/get", headers = { ["Host"] = "test8.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(4, tonumber(body.headers["X-Ratelimit-Remaining-Image"])) assert.equal(6, tonumber(body.headers["X-Ratelimit-Remaining-Video"])) -- Actually consume the limits local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=2, image=1", headers = { ["Host"] = "test8.com" } }) assert.res_status(200, res) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit local res = assert(helpers.proxy_client():send { method = "GET", path = "/get", headers = { ["Host"] = "test8.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(3, tonumber(body.headers["X-Ratelimit-Remaining-Image"])) assert.equal(4, tonumber(body.headers["X-Ratelimit-Remaining-Video"])) end) it("combines multiple x-kong-limit headers from upstream", function() for i = 1, 3 do local res = assert(client:send { method = "GET", path = "/response-headers?x-kong-limit=video%3D2&x-kong-limit=image%3D1", headers = { ["Host"] = "test4.com" } }) assert.res_status(200, res) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(6 - (i * 2), tonumber(res.headers["x-ratelimit-remaining-video-minute"])) assert.equal(4, tonumber(res.headers["x-ratelimit-limit-image-minute"])) assert.equal(4 - i, tonumber(res.headers["x-ratelimit-remaining-image-minute"])) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit end local res = assert(client:send { method = "GET", path = "/response-headers?x-kong-limit=video%3D2&x-kong-limit=image%3D1", headers = { ["Host"] = "test4.com" } }) local body = assert.res_status(429, res) assert.equal("", body) assert.equal(0, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) assert.equal(1, tonumber(res.headers["x-ratelimit-remaining-image-minute"])) end) end) it("should block on first violation", function() local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=2, image=4", headers = { ["Host"] = "test7.com" } }) assert.res_status(200, res) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=2", headers = { ["Host"] = "test7.com" } }) local body = assert.res_status(429, res) local json = cjson.decode(body) assert.same({ message = "API rate limit exceeded for 'image'" }, json) end) describe("Config with hide_client_headers", function() it("does not send rate-limit headers when hide_client_headers==true", function() local res = assert(helpers.proxy_client():send { method = "GET", path = "/status/200", headers = { ["Host"] = "test9.com" } }) assert.res_status(200, res) assert.is_nil(res.headers["x-ratelimit-remaining-video-minute"]) assert.is_nil(res.headers["x-ratelimit-limit-video-minute"]) end) end) if policy == "cluster" then describe("Fault tolerancy", function() before_each(function() helpers.kill_all() helpers.dao:drop_schema() helpers.run_migrations() local api1 = assert(helpers.dao.apis:insert { name = "failtest1_com", hosts = { "failtest1.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api1.id, config = { fault_tolerant = false, policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, limits = {video = {minute = 6}} } }) local api2 = assert(helpers.dao.apis:insert { name = "failtest2_com", hosts = { "failtest2.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api2.id, config = { fault_tolerant = true, policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, limits = {video = {minute = 6}} } }) assert(helpers.start_kong()) end) teardown(function() helpers.kill_all() helpers.dao:drop_schema() helpers.run_migrations() end) it("does not work if an error occurs", function() local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=1", headers = { ["Host"] = "failtest1.com" } }) assert.res_status(200, res) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(5, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) -- Simulate an error on the database assert(helpers.dao.db:drop_table("response_ratelimiting_metrics")) -- Make another request local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=1", headers = { ["Host"] = "failtest1.com" } }) local body = assert.res_status(500, res) local json = cjson.decode(body) assert.same({ message = "An unexpected error occurred" }, json) end) it("keeps working if an error occurs", function() local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=1", headers = { ["Host"] = "failtest2.com" } }) assert.res_status(200, res) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(5, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) -- Simulate an error on the database assert(helpers.dao.db:drop_table("response_ratelimiting_metrics")) -- Make another request local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=1", headers = { ["Host"] = "failtest2.com" } }) assert.res_status(200, res) assert.is_nil(res.headers["x-ratelimit-limit-video-minute"]) assert.is_nil(res.headers["x-ratelimit-remaining-video-minute"]) end) end) elseif policy == "redis" then describe("Fault tolerancy", function() before_each(function() local api1 = assert(helpers.dao.apis:insert { name = "failtest3_com", hosts = { "failtest3.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api1.id, config = { fault_tolerant = false, policy = policy, redis_host = "5.5.5.5", limits = {video = {minute = 6}} } }) local api2 = assert(helpers.dao.apis:insert { name = "failtest4_com", hosts = { "failtest4.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api2.id, config = { fault_tolerant = true, policy = policy, redis_host = "5.5.5.5", limits = {video = {minute = 6}} } }) end) it("does not work if an error occurs", function() -- Make another request local res = assert(helpers.proxy_client():send { method = "GET", path = "/status/200/", headers = { ["Host"] = "failtest3.com" } }) local body = assert.res_status(500, res) local json = cjson.decode(body) assert.same({ message = "An unexpected error occurred" }, json) end) it("keeps working if an error occurs", function() -- Make another request local res = assert(helpers.proxy_client():send { method = "GET", path = "/status/200/", headers = { ["Host"] = "failtest4.com" } }) assert.res_status(200, res) assert.falsy(res.headers["x-ratelimit-limit-video-minute"]) assert.falsy(res.headers["x-ratelimit-remaining-video-minute"]) end) end) end describe("Expirations", function() local api setup(function() helpers.stop_kong() helpers.dao:drop_schema() helpers.run_migrations() assert(helpers.start_kong()) api = assert(helpers.dao.apis:insert { name = "expire1_com", hosts = { "expire1.com" }, upstream_url = "http://httpbin.org" }) assert(helpers.dao.plugins:insert { name = "response-ratelimiting", api_id = api.id, config = { policy = policy, redis_host = REDIS_HOST, redis_port = REDIS_PORT, redis_password = REDIS_PASSWORD, fault_tolerant = false, limits = {video = {minute = 6}} } }) end) it("expires a counter", function() local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=1", headers = { ["Host"] = "expire1.com" } }) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit assert.res_status(200, res) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(5, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) ngx.sleep(61) -- Wait for counter to expire local res = assert(helpers.proxy_client():send { method = "GET", path = "/response-headers?x-kong-limit=video=1", headers = { ["Host"] = "expire1.com" } }) ngx.sleep(SLEEP_TIME) -- Wait for async timer to increment the limit assert.res_status(200, res) assert.equal(6, tonumber(res.headers["x-ratelimit-limit-video-minute"])) assert.equal(5, tonumber(res.headers["x-ratelimit-remaining-video-minute"])) end) end) end) end
apache-2.0
Ghor/LoveEngineCore
src/libraries/luasocket/libluasocket/socket.lua
146
4061
----------------------------------------------------------------------------- -- LuaSocket helper module -- Author: Diego Nehab -- RCS ID: $Id: socket.lua,v 1.22 2005/11/22 08:33:29 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local string = require("string") local math = require("math") local socket = require("socket.core") module("socket") ----------------------------------------------------------------------------- -- Exported auxiliar functions ----------------------------------------------------------------------------- function connect(address, port, laddress, lport) local sock, err = socket.tcp() if not sock then return nil, err end if laddress then local res, err = sock:bind(laddress, lport, -1) if not res then return nil, err end end local res, err = sock:connect(address, port) if not res then return nil, err end return sock end function bind(host, port, backlog) local sock, err = socket.tcp() if not sock then return nil, err end sock:setoption("reuseaddr", true) local res, err = sock:bind(host, port) if not res then return nil, err end res, err = sock:listen(backlog) if not res then return nil, err end return sock end try = newtry() function choose(table) return function(name, opt1, opt2) if base.type(name) ~= "string" then name, opt1, opt2 = "default", name, opt1 end local f = table[name or "nil"] if not f then base.error("unknown key (".. base.tostring(name) ..")", 3) else return f(opt1, opt2) end end end ----------------------------------------------------------------------------- -- Socket sources and sinks, conforming to LTN12 ----------------------------------------------------------------------------- -- create namespaces inside LuaSocket namespace sourcet = {} sinkt = {} BLOCKSIZE = 2048 sinkt["close-when-done"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if not chunk then sock:close() return 1 else return sock:send(chunk) end end }) end sinkt["keep-open"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if chunk then return sock:send(chunk) else return 1 end end }) end sinkt["default"] = sinkt["keep-open"] sink = choose(sinkt) sourcet["by-length"] = function(sock, length) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() if length <= 0 then return nil end local size = math.min(socket.BLOCKSIZE, length) local chunk, err = sock:receive(size) if err then return nil, err end length = length - string.len(chunk) return chunk end }) end sourcet["until-closed"] = function(sock) local done return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() if done then return nil end local chunk, err, partial = sock:receive(socket.BLOCKSIZE) if not err then return chunk elseif err == "closed" then sock:close() done = 1 return partial else return nil, err end end }) end sourcet["default"] = sourcet["until-closed"] source = choose(sourcet)
gpl-3.0
bjornbytes/RxLua
src/operators/flatMapLatest.lua
2
1352
local Observable = require 'observable' local Subscription = require 'subscription' local util = require 'util' --- Returns a new Observable that uses a callback to create Observables from the values produced by -- the source, then produces values from the most recent of these Observables. -- @arg {function=identity} callback - The function used to convert values to Observables. -- @returns {Observable} function Observable:flatMapLatest(callback) callback = callback or util.identity return Observable.create(function(observer) local innerSubscription local function onNext(...) observer:onNext(...) end local function onError(e) return observer:onError(e) end local function onCompleted() return observer:onCompleted() end local function subscribeInner(...) if innerSubscription then innerSubscription:unsubscribe() end return util.tryWithObserver(observer, function(...) innerSubscription = callback(...):subscribe(onNext, onError) end, ...) end local subscription = self:subscribe(subscribeInner, onError, onCompleted) return Subscription.create(function() if innerSubscription then innerSubscription:unsubscribe() end if subscription then subscription:unsubscribe() end end) end) end
mit
AngelBaltar/RenegadeKlingon
Utils/Animation.lua
1
5879
--[[ Copyright (c) 2009-2010 Bart Bes 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 animation = {} animation.__index = animation --- Create a new animation -- Replaces love.graphics.newAnimation -- @param image The image that contains the frames -- @param fw The frame width -- @param fh The frame height -- @param delay The delay between two frames -- @param frames The number of frames, 0 for autodetect -- @return The created animation function newAnimation(image, fw, fh, delay, frames, img) local a = {} a.img = image a.frames = {} a.delays = {} a.timer = 0 a.position = 1 a.fw = fw a.fh = fh a.playing = true a.speed = 1 a.mode = 1 a.direction = 1 local imgw = image:getWidth() local imgh = image:getHeight() if frames == 0 then frames = imgw / fw * imgh / fh end local rowsize = imgw/fw for i = 1, frames do local row = math.floor((i-1)/rowsize) local column = (i-1)%rowsize local frame = love.graphics.newQuad(column*fw, row*fh, fw, fh, imgw, imgh) table.insert(a.frames, frame) table.insert(a.delays, delay) end return setmetatable(a, animation) end --- Update the animation -- @param dt Time that has passed since last call function animation:update(dt) if not self.playing then return end self.timer = self.timer + dt * self.speed if self.timer > self.delays[self.position] then self.timer = self.timer - self.delays[self.position] self.position = self.position + 1 * self.direction if self.position > #self.frames then if self.mode == 1 then self.position = 1 elseif self.mode == 2 then self.position = self.position - 1 self:stop() elseif self.mode == 3 then self.direction = -1 self.position = self.position - 1 end elseif self.position < 1 and self.mode == 3 then self.direction = 1 self.position = self.position + 1 end end end --- Draw the animation -- @param x The X coordinate -- @param y The Y coordinate -- @param angle The angle to draw at (radians) -- @param sx The scale on the X axis -- @param sy The scale on the Y axis -- @param ox The X coordinate of the origin -- @param oy The Y coordinate of the origin function animation:draw(x, y, angle, sx, sy, ox, oy) love.graphics.draw(self.img, self.frames[self.position], x, y, angle, sx, sy, ox, oy) end --- Add a frame -- @param x The X coordinate of the frame on the original image -- @param y The Y coordinate of the frame on the original image -- @param w The width of the frame -- @param h The height of the frame -- @param delay The delay before the next frame is shown function animation:addFrame(x, y, w, h, delay) local frame = love.graphics.newQuad(x, y, w, h, a.img:getWidth(), a.img:getHeight()) table.insert(self.frames, frame) table.insert(self.delays, delay) end --- Play the animation -- Starts it if it was stopped. -- Basically makes sure it uses the delays -- to switch to the next frame. function animation:play() self.playing = true end --- Stop the animation function animation:stop() self.playing = false end --- Reset -- Go back to the first frame. function animation:reset() self:seek(0) end --- Seek to a frame -- @param frame The frame to display now function animation:seek(frame) self.position = frame self.timer = 0 end --- Get the currently shown frame -- @return The current frame function animation:getCurrentFrame() return self.position end --- Get the number of frames -- @return The number of frames function animation:getSize() return #self.frames end --- Set the delay between frames -- @param frame Which frame to set the delay for -- @param delay The delay function animation:setDelay(frame, delay) self.delays[frame] = delay end --- Set the speed -- @param speed The speed to play at (1 is normal, 2 is double, etc) function animation:setSpeed(speed) self.speed = speed end --- Get the width of the current frame -- @return The width of the current frame function animation:getWidth() return self.fw end --- Get the height of the current frame -- @return The height of the current frame function animation:getHeight() return self.fh end function animation:isPlaying() return self.playing end --- Set the play mode -- Could be "loop" to loop it, "once" to play it once, or "bounce" to play it, reverse it, and play it again (looping) -- @param mode The mode: one of the above function animation:setMode(mode) if mode == "loop" then self.mode = 1 elseif mode == "once" then self.mode = 2 elseif mode == "bounce" then self.mode = 3 end end --- Animations_legacy_support -- @usage Add legacy support, basically set love.graphics.newAnimation again, and allow you to use love.graphics.draw if Animations_legacy_support then love.graphics.newAnimation = newAnimation local oldLGDraw = love.graphics.draw function love.graphics.draw(item, ...) if type(item) == "table" and item.draw then item:draw(...) else oldLGDraw(item, ...) end end end
gpl-3.0
devm11/DEV_M1
plugins/TH3BOSS6.lua
1
1566
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀ ▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀ ▀▄ ▄▀ dev : dev ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do function run(msg, matches) return [[ االبوت الذي يعمل على مجوعات السوبر 🔺 يعمل البوت على مجموعات سوبر تصل الى 5 k عضو 🔺 ≪تم صنع البوت بواسطة المطور≫ 『 @TH3BOSS 』 🔻 DEV : @TH3BOSS 🔺 🔺 تابعونا ماهو كل جديد على قناه السورس 🔻 [ @llDEV1ll ] 🔺 للاستفسار :- @TH3BOSS 🔻 🔻 DEV:- @TH3BOSS 🔺 🔻 SUPPORTBOT :- @ll60Kllbot🔺 ]] end return { description = "Shows bot q", usage = "spam Shows bot q", patterns = { "^(المطور)$", }, run = run } end
gpl-2.0
Nitroteam/a
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Alikey2ali/Alitaki5
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
agpl-3.0
Yonaba/Algorithm-Implementations
Average/Lua/Yonaba/average_test.lua
26
1557
-- Tests for average.lua local mean = require 'average' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end local function fuzzyEqual(a, b, eps) return math.abs(a - b) < eps end local x = {1, 2, 3, 4, 5} run('Arithmetic mean', function() assert(mean.arithmetic(x) == 3) end) run('Geometric mean', function() assert(fuzzyEqual(mean.geometric(x), 2.60517108,1e-8)) end) run('Harmonic mean', function() assert(fuzzyEqual(mean.harmonic(x), 2.18978102,1e-8)) end) run('Quadratic mean', function() assert(fuzzyEqual(mean.quadratic(x), 3.31662479,1e-8)) end) run('Generalized mean', function() assert(fuzzyEqual(mean.generalized(x,1), mean.arithmetic(x),1e-8)) assert(fuzzyEqual(mean.generalized(x,2), mean.quadratic(x),1e-8)) assert(fuzzyEqual(mean.generalized(x,-1), mean.harmonic(x),1e-8)) end) run('Weighted mean', function() local w = { 0.1, 0.2, 0.2, 0.3, 0.2} assert(mean.weighted(x, w) == 3.3) end) run('Midrange mean', function() assert(mean.midrange(x) == 3) end) run('Energetic mean', function() assert(fuzzyEqual(mean.energetic(x), 3.22766781,1e-8)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
mario0582/devenserver
data/creaturescripts/scripts/raffle.lua
2
1056
local modaldialog = { title = "Want to try your luck?", message = "Select what you want to try to win:", buttons = { { id = 1, text = "Try" }, { id = 2, text = "Cancel" }, }, buttonEnter = 1, buttonEscape = 2, choices = { { id = 1, text = "2 premium days!" }, { id = 2, text = "any Item!" } }, popup = true } function onLogin(player) if player:getStorageValue(11000) == -1 then if math.random(100) <= 50 then modalWindow = ModalWindow(1000, modaldialog.title, modaldialog.message) if modalWindow:getId() == 1000 then for _, v in ipairs(modaldialog.buttons) do modalWindow:addButton(v.id, v.text) end for _, v in ipairs(modaldialog.choices) do modalWindow:addChoice(v.id, v.text) end modalWindow:setDefaultEnterButton(modaldialog.buttonEnter) modalWindow:setPriority(modaldialog.popup) modalWindow:setDefaultEscapeButton(modaldialog.buttonEscape) end modalWindow:sendToPlayer(player) player:registerEvent("ModalRaffle") end player:setStorageValue(11000, 1) end return true end
gpl-2.0
RUlanowicz/MyBreakout
cocos2d/cocos/scripting/lua/script/DeprecatedOpenglEnum.lua
148
11934
-- This is the DeprecatedEnum DeprecatedClass = {} or DeprecatedClass _G.GL_RENDERBUFFER_INTERNAL_FORMAT = gl.RENDERBUFFER_INTERNAL_FORMAT _G.GL_LINE_WIDTH = gl.LINE_WIDTH _G.GL_CONSTANT_ALPHA = gl.CONSTANT_ALPHA _G.GL_BLEND_SRC_ALPHA = gl.BLEND_SRC_ALPHA _G.GL_GREEN_BITS = gl.GREEN_BITS _G.GL_STENCIL_REF = gl.STENCIL_REF _G.GL_ONE_MINUS_SRC_ALPHA = gl.ONE_MINUS_SRC_ALPHA _G.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE _G.GL_CCW = gl.CCW _G.GL_MAX_TEXTURE_IMAGE_UNITS = gl.MAX_TEXTURE_IMAGE_UNITS _G.GL_BACK = gl.BACK _G.GL_ACTIVE_ATTRIBUTES = gl.ACTIVE_ATTRIBUTES _G.GL_TEXTURE_CUBE_MAP_POSITIVE_X = gl.TEXTURE_CUBE_MAP_POSITIVE_X _G.GL_STENCIL_BACK_VALUE_MASK = gl.STENCIL_BACK_VALUE_MASK _G.GL_TEXTURE_CUBE_MAP_POSITIVE_Z = gl.TEXTURE_CUBE_MAP_POSITIVE_Z _G.GL_ONE = gl.ONE _G.GL_TRUE = gl.TRUE _G.GL_TEXTURE12 = gl.TEXTURE12 _G.GL_LINK_STATUS = gl.LINK_STATUS _G.GL_BLEND = gl.BLEND _G.GL_LESS = gl.LESS _G.GL_TEXTURE16 = gl.TEXTURE16 _G.GL_BOOL_VEC2 = gl.BOOL_VEC2 _G.GL_KEEP = gl.KEEP _G.GL_DST_COLOR = gl.DST_COLOR _G.GL_VERTEX_ATTRIB_ARRAY_ENABLED = gl.VERTEX_ATTRIB_ARRAY_ENABLED _G.GL_EXTENSIONS = gl.EXTENSIONS _G.GL_FRONT = gl.FRONT _G.GL_DST_ALPHA = gl.DST_ALPHA _G.GL_ATTACHED_SHADERS = gl.ATTACHED_SHADERS _G.GL_STENCIL_BACK_FUNC = gl.STENCIL_BACK_FUNC _G.GL_ONE_MINUS_DST_COLOR = gl.ONE_MINUS_DST_COLOR _G.GL_BLEND_EQUATION = gl.BLEND_EQUATION _G.GL_RENDERBUFFER_DEPTH_SIZE = gl.RENDERBUFFER_DEPTH_SIZE _G.GL_PACK_ALIGNMENT = gl.PACK_ALIGNMENT _G.GL_VENDOR = gl.VENDOR _G.GL_NEAREST_MIPMAP_LINEAR = gl.NEAREST_MIPMAP_LINEAR _G.GL_TEXTURE_CUBE_MAP_POSITIVE_Y = gl.TEXTURE_CUBE_MAP_POSITIVE_Y _G.GL_NEAREST = gl.NEAREST _G.GL_RENDERBUFFER_WIDTH = gl.RENDERBUFFER_WIDTH _G.GL_ARRAY_BUFFER_BINDING = gl.ARRAY_BUFFER_BINDING _G.GL_ARRAY_BUFFER = gl.ARRAY_BUFFER _G.GL_LEQUAL = gl.LEQUAL _G.GL_VERSION = gl.VERSION _G.GL_COLOR_CLEAR_VALUE = gl.COLOR_CLEAR_VALUE _G.GL_RENDERER = gl.RENDERER _G.GL_STENCIL_BACK_PASS_DEPTH_PASS = gl.STENCIL_BACK_PASS_DEPTH_PASS _G.GL_STENCIL_BACK_PASS_DEPTH_FAIL = gl.STENCIL_BACK_PASS_DEPTH_FAIL _G.GL_STENCIL_BACK_WRITEMASK = gl.STENCIL_BACK_WRITEMASK _G.GL_BOOL = gl.BOOL _G.GL_VIEWPORT = gl.VIEWPORT _G.GL_FRAGMENT_SHADER = gl.FRAGMENT_SHADER _G.GL_LUMINANCE = gl.LUMINANCE _G.GL_DECR_WRAP = gl.DECR_WRAP _G.GL_FUNC_ADD = gl.FUNC_ADD _G.GL_ONE_MINUS_DST_ALPHA = gl.ONE_MINUS_DST_ALPHA _G.GL_OUT_OF_MEMORY = gl.OUT_OF_MEMORY _G.GL_BOOL_VEC4 = gl.BOOL_VEC4 _G.GL_POLYGON_OFFSET_FACTOR = gl.POLYGON_OFFSET_FACTOR _G.GL_STATIC_DRAW = gl.STATIC_DRAW _G.GL_DITHER = gl.DITHER _G.GL_TEXTURE31 = gl.TEXTURE31 _G.GL_TEXTURE30 = gl.TEXTURE30 _G.GL_UNSIGNED_BYTE = gl.UNSIGNED_BYTE _G.GL_DEPTH_COMPONENT16 = gl.DEPTH_COMPONENT16 _G.GL_TEXTURE23 = gl.TEXTURE23 _G.GL_DEPTH_TEST = gl.DEPTH_TEST _G.GL_STENCIL_PASS_DEPTH_FAIL = gl.STENCIL_PASS_DEPTH_FAIL _G.GL_BOOL_VEC3 = gl.BOOL_VEC3 _G.GL_POLYGON_OFFSET_UNITS = gl.POLYGON_OFFSET_UNITS _G.GL_TEXTURE_BINDING_2D = gl.TEXTURE_BINDING_2D _G.GL_TEXTURE21 = gl.TEXTURE21 _G.GL_UNPACK_ALIGNMENT = gl.UNPACK_ALIGNMENT _G.GL_DONT_CARE = gl.DONT_CARE _G.GL_BUFFER_SIZE = gl.BUFFER_SIZE _G.GL_FLOAT_MAT3 = gl.FLOAT_MAT3 _G.GL_UNSIGNED_SHORT_5_6_5 = gl.UNSIGNED_SHORT_5_6_5 _G.GL_INT_VEC2 = gl.INT_VEC2 _G.GL_UNSIGNED_SHORT_4_4_4_4 = gl.UNSIGNED_SHORT_4_4_4_4 _G.GL_NONE = gl.NONE _G.GL_BLEND_DST_ALPHA = gl.BLEND_DST_ALPHA _G.GL_VERTEX_ATTRIB_ARRAY_SIZE = gl.VERTEX_ATTRIB_ARRAY_SIZE _G.GL_SRC_COLOR = gl.SRC_COLOR _G.GL_COMPRESSED_TEXTURE_FORMATS = gl.COMPRESSED_TEXTURE_FORMATS _G.GL_STENCIL_ATTACHMENT = gl.STENCIL_ATTACHMENT _G.GL_MAX_VERTEX_ATTRIBS = gl.MAX_VERTEX_ATTRIBS _G.GL_NUM_COMPRESSED_TEXTURE_FORMATS = gl.NUM_COMPRESSED_TEXTURE_FORMATS _G.GL_BLEND_EQUATION_RGB = gl.BLEND_EQUATION_RGB _G.GL_TEXTURE = gl.TEXTURE _G.GL_LINEAR_MIPMAP_LINEAR = gl.LINEAR_MIPMAP_LINEAR _G.GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING _G.GL_CURRENT_PROGRAM = gl.CURRENT_PROGRAM _G.GL_COLOR_BUFFER_BIT = gl.COLOR_BUFFER_BIT _G.GL_TEXTURE20 = gl.TEXTURE20 _G.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = gl.ACTIVE_ATTRIBUTE_MAX_LENGTH _G.GL_TEXTURE28 = gl.TEXTURE28 _G.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE _G.GL_TEXTURE22 = gl.TEXTURE22 _G.GL_ELEMENT_ARRAY_BUFFER_BINDING = gl.ELEMENT_ARRAY_BUFFER_BINDING _G.GL_STREAM_DRAW = gl.STREAM_DRAW _G.GL_SCISSOR_BOX = gl.SCISSOR_BOX _G.GL_TEXTURE26 = gl.TEXTURE26 _G.GL_TEXTURE27 = gl.TEXTURE27 _G.GL_TEXTURE24 = gl.TEXTURE24 _G.GL_TEXTURE25 = gl.TEXTURE25 _G.GL_NO_ERROR = gl.NO_ERROR _G.GL_TEXTURE29 = gl.TEXTURE29 _G.GL_FLOAT_MAT4 = gl.FLOAT_MAT4 _G.GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = gl.VERTEX_ATTRIB_ARRAY_NORMALIZED _G.GL_SAMPLE_COVERAGE_INVERT = gl.SAMPLE_COVERAGE_INVERT _G.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL _G.GL_FLOAT_VEC3 = gl.FLOAT_VEC3 _G.GL_STENCIL_CLEAR_VALUE = gl.STENCIL_CLEAR_VALUE _G.GL_UNSIGNED_SHORT_5_5_5_1 = gl.UNSIGNED_SHORT_5_5_5_1 _G.GL_ACTIVE_UNIFORMS = gl.ACTIVE_UNIFORMS _G.GL_INVALID_OPERATION = gl.INVALID_OPERATION _G.GL_DEPTH_ATTACHMENT = gl.DEPTH_ATTACHMENT _G.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS _G.GL_FRAMEBUFFER_COMPLETE = gl.FRAMEBUFFER_COMPLETE _G.GL_ONE_MINUS_CONSTANT_COLOR = gl.ONE_MINUS_CONSTANT_COLOR _G.GL_TEXTURE2 = gl.TEXTURE2 _G.GL_TEXTURE1 = gl.TEXTURE1 _G.GL_GEQUAL = gl.GEQUAL _G.GL_TEXTURE7 = gl.TEXTURE7 _G.GL_TEXTURE6 = gl.TEXTURE6 _G.GL_TEXTURE5 = gl.TEXTURE5 _G.GL_TEXTURE4 = gl.TEXTURE4 _G.GL_GENERATE_MIPMAP_HINT = gl.GENERATE_MIPMAP_HINT _G.GL_ONE_MINUS_SRC_COLOR = gl.ONE_MINUS_SRC_COLOR _G.GL_TEXTURE9 = gl.TEXTURE9 _G.GL_STENCIL_TEST = gl.STENCIL_TEST _G.GL_COLOR_WRITEMASK = gl.COLOR_WRITEMASK _G.GL_DEPTH_COMPONENT = gl.DEPTH_COMPONENT _G.GL_STENCIL_INDEX8 = gl.STENCIL_INDEX8 _G.GL_VERTEX_ATTRIB_ARRAY_TYPE = gl.VERTEX_ATTRIB_ARRAY_TYPE _G.GL_FLOAT_VEC2 = gl.FLOAT_VEC2 _G.GL_BLUE_BITS = gl.BLUE_BITS _G.GL_VERTEX_SHADER = gl.VERTEX_SHADER _G.GL_SUBPIXEL_BITS = gl.SUBPIXEL_BITS _G.GL_STENCIL_WRITEMASK = gl.STENCIL_WRITEMASK _G.GL_FLOAT_VEC4 = gl.FLOAT_VEC4 _G.GL_TEXTURE17 = gl.TEXTURE17 _G.GL_ONE_MINUS_CONSTANT_ALPHA = gl.ONE_MINUS_CONSTANT_ALPHA _G.GL_TEXTURE15 = gl.TEXTURE15 _G.GL_TEXTURE14 = gl.TEXTURE14 _G.GL_TEXTURE13 = gl.TEXTURE13 _G.GL_SAMPLES = gl.SAMPLES _G.GL_TEXTURE11 = gl.TEXTURE11 _G.GL_TEXTURE10 = gl.TEXTURE10 _G.GL_FUNC_SUBTRACT = gl.FUNC_SUBTRACT _G.GL_STENCIL_BUFFER_BIT = gl.STENCIL_BUFFER_BIT _G.GL_TEXTURE19 = gl.TEXTURE19 _G.GL_TEXTURE18 = gl.TEXTURE18 _G.GL_NEAREST_MIPMAP_NEAREST = gl.NEAREST_MIPMAP_NEAREST _G.GL_SHORT = gl.SHORT _G.GL_RENDERBUFFER_BINDING = gl.RENDERBUFFER_BINDING _G.GL_REPEAT = gl.REPEAT _G.GL_TEXTURE_MIN_FILTER = gl.TEXTURE_MIN_FILTER _G.GL_RED_BITS = gl.RED_BITS _G.GL_FRONT_FACE = gl.FRONT_FACE _G.GL_BLEND_COLOR = gl.BLEND_COLOR _G.GL_MIRRORED_REPEAT = gl.MIRRORED_REPEAT _G.GL_INT_VEC4 = gl.INT_VEC4 _G.GL_MAX_CUBE_MAP_TEXTURE_SIZE = gl.MAX_CUBE_MAP_TEXTURE_SIZE _G.GL_RENDERBUFFER_BLUE_SIZE = gl.RENDERBUFFER_BLUE_SIZE _G.GL_SAMPLE_COVERAGE = gl.SAMPLE_COVERAGE _G.GL_SRC_ALPHA = gl.SRC_ALPHA _G.GL_FUNC_REVERSE_SUBTRACT = gl.FUNC_REVERSE_SUBTRACT _G.GL_DEPTH_WRITEMASK = gl.DEPTH_WRITEMASK _G.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT _G.GL_POLYGON_OFFSET_FILL = gl.POLYGON_OFFSET_FILL _G.GL_STENCIL_FUNC = gl.STENCIL_FUNC _G.GL_REPLACE = gl.REPLACE _G.GL_LUMINANCE_ALPHA = gl.LUMINANCE_ALPHA _G.GL_DEPTH_RANGE = gl.DEPTH_RANGE _G.GL_FASTEST = gl.FASTEST _G.GL_STENCIL_FAIL = gl.STENCIL_FAIL _G.GL_UNSIGNED_SHORT = gl.UNSIGNED_SHORT _G.GL_RENDERBUFFER_HEIGHT = gl.RENDERBUFFER_HEIGHT _G.GL_STENCIL_BACK_FAIL = gl.STENCIL_BACK_FAIL _G.GL_BLEND_SRC_RGB = gl.BLEND_SRC_RGB _G.GL_TEXTURE3 = gl.TEXTURE3 _G.GL_RENDERBUFFER = gl.RENDERBUFFER _G.GL_RGB5_A1 = gl.RGB5_A1 _G.GL_RENDERBUFFER_ALPHA_SIZE = gl.RENDERBUFFER_ALPHA_SIZE _G.GL_RENDERBUFFER_STENCIL_SIZE = gl.RENDERBUFFER_STENCIL_SIZE _G.GL_NOTEQUAL = gl.NOTEQUAL _G.GL_BLEND_DST_RGB = gl.BLEND_DST_RGB _G.GL_FRONT_AND_BACK = gl.FRONT_AND_BACK _G.GL_TEXTURE_BINDING_CUBE_MAP = gl.TEXTURE_BINDING_CUBE_MAP _G.GL_MAX_RENDERBUFFER_SIZE = gl.MAX_RENDERBUFFER_SIZE _G.GL_ZERO = gl.ZERO _G.GL_TEXTURE0 = gl.TEXTURE0 _G.GL_SAMPLE_ALPHA_TO_COVERAGE = gl.SAMPLE_ALPHA_TO_COVERAGE _G.GL_BUFFER_USAGE = gl.BUFFER_USAGE _G.GL_ACTIVE_TEXTURE = gl.ACTIVE_TEXTURE _G.GL_BYTE = gl.BYTE _G.GL_CW = gl.CW _G.GL_DYNAMIC_DRAW = gl.DYNAMIC_DRAW _G.GL_RENDERBUFFER_RED_SIZE = gl.RENDERBUFFER_RED_SIZE _G.GL_FALSE = gl.FALSE _G.GL_GREATER = gl.GREATER _G.GL_RGBA4 = gl.RGBA4 _G.GL_VALIDATE_STATUS = gl.VALIDATE_STATUS _G.GL_STENCIL_BITS = gl.STENCIL_BITS _G.GL_RGB = gl.RGB _G.GL_INT = gl.INT _G.GL_DEPTH_FUNC = gl.DEPTH_FUNC _G.GL_SAMPLER_2D = gl.SAMPLER_2D _G.GL_NICEST = gl.NICEST _G.GL_MAX_VIEWPORT_DIMS = gl.MAX_VIEWPORT_DIMS _G.GL_CULL_FACE = gl.CULL_FACE _G.GL_INT_VEC3 = gl.INT_VEC3 _G.GL_ALIASED_POINT_SIZE_RANGE = gl.ALIASED_POINT_SIZE_RANGE _G.GL_INVALID_ENUM = gl.INVALID_ENUM _G.GL_INVERT = gl.INVERT _G.GL_CULL_FACE_MODE = gl.CULL_FACE_MODE _G.GL_TEXTURE8 = gl.TEXTURE8 _G.GL_VERTEX_ATTRIB_ARRAY_POINTER = gl.VERTEX_ATTRIB_ARRAY_POINTER _G.GL_TEXTURE_WRAP_S = gl.TEXTURE_WRAP_S _G.GL_VERTEX_ATTRIB_ARRAY_STRIDE = gl.VERTEX_ATTRIB_ARRAY_STRIDE _G.GL_LINES = gl.LINES _G.GL_EQUAL = gl.EQUAL _G.GL_LINE_LOOP = gl.LINE_LOOP _G.GL_TEXTURE_WRAP_T = gl.TEXTURE_WRAP_T _G.GL_DEPTH_BUFFER_BIT = gl.DEPTH_BUFFER_BIT _G.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS _G.GL_SHADER_TYPE = gl.SHADER_TYPE _G.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_X = gl.TEXTURE_CUBE_MAP_NEGATIVE_X _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = gl.TEXTURE_CUBE_MAP_NEGATIVE_Y _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = gl.TEXTURE_CUBE_MAP_NEGATIVE_Z _G.GL_DECR = gl.DECR _G.GL_DELETE_STATUS = gl.DELETE_STATUS _G.GL_DEPTH_BITS = gl.DEPTH_BITS _G.GL_INCR = gl.INCR _G.GL_SAMPLE_COVERAGE_VALUE = gl.SAMPLE_COVERAGE_VALUE _G.GL_ALPHA_BITS = gl.ALPHA_BITS _G.GL_FLOAT_MAT2 = gl.FLOAT_MAT2 _G.GL_LINE_STRIP = gl.LINE_STRIP _G.GL_SHADER_SOURCE_LENGTH = gl.SHADER_SOURCE_LENGTH _G.GL_INVALID_VALUE = gl.INVALID_VALUE _G.GL_NEVER = gl.NEVER _G.GL_INCR_WRAP = gl.INCR_WRAP _G.GL_BLEND_EQUATION_ALPHA = gl.BLEND_EQUATION_ALPHA _G.GL_TEXTURE_MAG_FILTER = gl.TEXTURE_MAG_FILTER _G.GL_POINTS = gl.POINTS _G.GL_COLOR_ATTACHMENT0 = gl.COLOR_ATTACHMENT0 _G.GL_RGBA = gl.RGBA _G.GL_SRC_ALPHA_SATURATE = gl.SRC_ALPHA_SATURATE _G.GL_SAMPLER_CUBE = gl.SAMPLER_CUBE _G.GL_FRAMEBUFFER = gl.FRAMEBUFFER _G.GL_TEXTURE_CUBE_MAP = gl.TEXTURE_CUBE_MAP _G.GL_SAMPLE_BUFFERS = gl.SAMPLE_BUFFERS _G.GL_LINEAR = gl.LINEAR _G.GL_LINEAR_MIPMAP_NEAREST = gl.LINEAR_MIPMAP_NEAREST _G.GL_ACTIVE_UNIFORM_MAX_LENGTH = gl.ACTIVE_UNIFORM_MAX_LENGTH _G.GL_STENCIL_BACK_REF = gl.STENCIL_BACK_REF _G.GL_ELEMENT_ARRAY_BUFFER = gl.ELEMENT_ARRAY_BUFFER _G.GL_CLAMP_TO_EDGE = gl.CLAMP_TO_EDGE _G.GL_TRIANGLE_STRIP = gl.TRIANGLE_STRIP _G.GL_CONSTANT_COLOR = gl.CONSTANT_COLOR _G.GL_COMPILE_STATUS = gl.COMPILE_STATUS _G.GL_RENDERBUFFER_GREEN_SIZE = gl.RENDERBUFFER_GREEN_SIZE _G.GL_UNSIGNED_INT = gl.UNSIGNED_INT _G.GL_DEPTH_CLEAR_VALUE = gl.DEPTH_CLEAR_VALUE _G.GL_ALIASED_LINE_WIDTH_RANGE = gl.ALIASED_LINE_WIDTH_RANGE _G.GL_SHADING_LANGUAGE_VERSION = gl.SHADING_LANGUAGE_VERSION _G.GL_FRAMEBUFFER_UNSUPPORTED = gl.FRAMEBUFFER_UNSUPPORTED _G.GL_INFO_LOG_LENGTH = gl.INFO_LOG_LENGTH _G.GL_STENCIL_PASS_DEPTH_PASS = gl.STENCIL_PASS_DEPTH_PASS _G.GL_STENCIL_VALUE_MASK = gl.STENCIL_VALUE_MASK _G.GL_ALWAYS = gl.ALWAYS _G.GL_MAX_TEXTURE_SIZE = gl.MAX_TEXTURE_SIZE _G.GL_FLOAT = gl.FLOAT _G.GL_FRAMEBUFFER_BINDING = gl.FRAMEBUFFER_BINDING _G.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT _G.GL_TRIANGLE_FAN = gl.TRIANGLE_FAN _G.GL_INVALID_FRAMEBUFFER_OPERATION = gl.INVALID_FRAMEBUFFER_OPERATION _G.GL_TEXTURE_2D = gl.TEXTURE_2D _G.GL_ALPHA = gl.ALPHA _G.GL_CURRENT_VERTEX_ATTRIB = gl.CURRENT_VERTEX_ATTRIB _G.GL_SCISSOR_TEST = gl.SCISSOR_TEST _G.GL_TRIANGLES = gl.TRIANGLES
gpl-2.0
liruqi/bigfoot
Interface/AddOns/BigFoot/Library/BigFootSecureHook.lua
1
8348
local BLSH_dbdf11f5b07258936fb1c5a31eaa969c = 1; local BLSH_1b5523f0adb45c4b8ee51f89ebf6f2b2 = 0; local BLSH_6dc50cf393baa8395c3f8b6cd575c5d9 = { _F = {}, }; function BLSH_6dc50cf393baa8395c3f8b6cd575c5d9:Hook(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006, BLSH_c31af5fd9021206e921af3d99e5a90af, BLSH_9ed8bd8a19b94f73925daece17a05623) if (BLSH_9ed8bd8a19b94f73925daece17a05623) then assert(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006 and type(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006) == "table", "BSecureHook: Invalid ui object"); assert(BLSH_c31af5fd9021206e921af3d99e5a90af and type(BLSH_c31af5fd9021206e921af3d99e5a90af) == "string", "BSecureHook: Invalid function to hook"); assert(BLSH_9ed8bd8a19b94f73925daece17a05623 and type(BLSH_9ed8bd8a19b94f73925daece17a05623) == "function", "BSecureHook: Invalid hookfunc"); self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] = self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] or {}; self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af] = true; if (BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] and BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af] and BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af][BLSH_9ed8bd8a19b94f73925daece17a05623]) then else hooksecurefunc(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006, BLSH_c31af5fd9021206e921af3d99e5a90af, function(...) if (self.enable and self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af]) then BLSH_9ed8bd8a19b94f73925daece17a05623(...) end end); BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] = BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] or {}; BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af] = BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af] or {}; BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af][BLSH_9ed8bd8a19b94f73925daece17a05623] = true; end else BLSH_9ed8bd8a19b94f73925daece17a05623 = BLSH_c31af5fd9021206e921af3d99e5a90af; BLSH_c31af5fd9021206e921af3d99e5a90af = BLSH_89d99bb0d06dd535e6d6f6d9b3f04006; self._E[BLSH_c31af5fd9021206e921af3d99e5a90af] = true; assert(BLSH_c31af5fd9021206e921af3d99e5a90af and type(BLSH_c31af5fd9021206e921af3d99e5a90af) == "string", "BSecureHook: Invalid function to hook"); assert(BLSH_9ed8bd8a19b94f73925daece17a05623 and type(BLSH_9ed8bd8a19b94f73925daece17a05623) == "function", "BSecureHook: Invalid hookfunc"); if (BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_c31af5fd9021206e921af3d99e5a90af] and BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_c31af5fd9021206e921af3d99e5a90af][BLSH_9ed8bd8a19b94f73925daece17a05623]) then else hooksecurefunc(BLSH_c31af5fd9021206e921af3d99e5a90af, function(...) if (self.enable and self._E[BLSH_c31af5fd9021206e921af3d99e5a90af]) then BLSH_9ed8bd8a19b94f73925daece17a05623(...) end end); BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_c31af5fd9021206e921af3d99e5a90af] = BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_c31af5fd9021206e921af3d99e5a90af] or {}; BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_c31af5fd9021206e921af3d99e5a90af][BLSH_9ed8bd8a19b94f73925daece17a05623] = true; end end end function BLSH_6dc50cf393baa8395c3f8b6cd575c5d9:Unhook(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006, BLSH_c31af5fd9021206e921af3d99e5a90af) if (BLSH_c31af5fd9021206e921af3d99e5a90af) then if (self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] and self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af]) then self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_c31af5fd9021206e921af3d99e5a90af] = false; end else BLSH_c31af5fd9021206e921af3d99e5a90af = BLSH_89d99bb0d06dd535e6d6f6d9b3f04006; if (self._E[BLSH_c31af5fd9021206e921af3d99e5a90af]) then self._E[BLSH_c31af5fd9021206e921af3d99e5a90af] = false; end end end function BLSH_6dc50cf393baa8395c3f8b6cd575c5d9:HookScript(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006, BLSH_57ad665d0e8800ab56a0e07f8ae9c063, BLSH_9ed8bd8a19b94f73925daece17a05623) assert(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006 and type(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006) == "table", "BSecureHook: Invalid ui object"); assert(BLSH_57ad665d0e8800ab56a0e07f8ae9c063 and type(BLSH_57ad665d0e8800ab56a0e07f8ae9c063) == "string", "BSecureHook: Invalid handler"); assert(BLSH_9ed8bd8a19b94f73925daece17a05623 and type(BLSH_9ed8bd8a19b94f73925daece17a05623) == "function", "BSecureHook: Invalid hookfunc"); self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] = self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] or {}; self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063] = true; if (BLSH_89d99bb0d06dd535e6d6f6d9b3f04006:GetScript(BLSH_57ad665d0e8800ab56a0e07f8ae9c063)) then if (BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] and BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063] and BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063][BLSH_9ed8bd8a19b94f73925daece17a05623]) then else BLSH_89d99bb0d06dd535e6d6f6d9b3f04006:HookScript(BLSH_57ad665d0e8800ab56a0e07f8ae9c063, function(...) if (self.enable and self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063]) then BLSH_9ed8bd8a19b94f73925daece17a05623(...) end end); BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] = BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] or {}; BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063] = BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063] or {}; BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063][BLSH_9ed8bd8a19b94f73925daece17a05623] = true; end else BLSH_89d99bb0d06dd535e6d6f6d9b3f04006:SetScript(BLSH_57ad665d0e8800ab56a0e07f8ae9c063, function(...) if (self.enable and self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063]) then BLSH_9ed8bd8a19b94f73925daece17a05623(...) end end); BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] = BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] or {}; BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063] = BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063] or {}; BLSH_6dc50cf393baa8395c3f8b6cd575c5d9._F[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063][BLSH_9ed8bd8a19b94f73925daece17a05623] = true; end end function BLSH_6dc50cf393baa8395c3f8b6cd575c5d9:UnhookScript(BLSH_89d99bb0d06dd535e6d6f6d9b3f04006, BLSH_57ad665d0e8800ab56a0e07f8ae9c063) if (self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006] and self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063]) then self._E[BLSH_89d99bb0d06dd535e6d6f6d9b3f04006][BLSH_57ad665d0e8800ab56a0e07f8ae9c063] = false; end end function BLSH_6dc50cf393baa8395c3f8b6cd575c5d9:Enable() self.enable = true; end function BLSH_6dc50cf393baa8395c3f8b6cd575c5d9:Disable() self.enable = false; end function BLSH_6dc50cf393baa8395c3f8b6cd575c5d9:constructor() self.enable = true; self._E = {}; end BLibrary:Register(BLSH_6dc50cf393baa8395c3f8b6cd575c5d9, "BSecureHook", BLSH_dbdf11f5b07258936fb1c5a31eaa969c, BLSH_1b5523f0adb45c4b8ee51f89ebf6f2b2); --[[ SECURE = BLibrary("BSecureHook"); local echoHook = function (...) local msg = ""; for k, v in pairs({...}) do msg = msg .. "[" .. k .. "] =" .. tostring(v) .. "\n"; end DEFAULT_CHAT_FRAME:AddMessage("[BF Secure Hook]: " .. msg); end SECURE:Hook("UnitName", echoHook); SECURE:Unhook("UnitName"); SECURE:Hook(GameTooltip, "SetUnitBuff", echoHook); SECURE:Unhook(GameTooltip, "SetUnitBuff"); SECURE:HookScript(TargetofTargetFrame, "OnEvent", echoHook); ]]
mit
Alikey2ali/Alitaki5
plugins/ingroup.lua
371
44212
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'] local user_info = redis:hgetall('user:'..group_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") if user_info.username then return "Group onwer is @"..user_info.username.." ["..group_owner.."]" else return "Group owner is ["..group_owner..']' end 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
agpl-3.0
nurv/lirec
scenarios/MyFriend/MyPleo/tags/version-1.05/workspace/viPleoShivaModule/Resources/Scripts/MainAI_Handler_onChangeStates.lua
2
3035
-------------------------------------------------------------------------------- -- Handler.......... : onChangeStates -- Authors.......... : Tiago Paiva and Paulo F. Gomes -- Description...... : Handler that redirects events to MyPleoAI. It also -- hides/shows interface elements that are -- irrelevant/relevant to the situation. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function MainAI.onChangeStates ( state ) -------------------------------------------------------------------------------- local obj = application.getCurrentUserSceneTaggedObject ( "MyCharacter" ) if(state == "eat") then object.sendEvent ( obj, "MyPleoAI", "onChangeStates", "eat" ) end if(state == "drink") then object.sendEvent ( obj, "MyPleoAI", "onChangeStates", "drink" ) end if(state == "sit") then log.message ( "SITTT" ) object.sendEvent ( obj, "MyPleoAI", "onChangeStates", "sit" ) end if(state == "cleanPoop") then object.sendEvent ( obj, "MyPleoAI", "onChangeStates", "cleanPoop" ) end if(state == "wash") then log.message ( "WASHH" ) object.sendEvent ( obj, "MyPleoAI", "onChangeStates", "wash" ) end if(state == "petting") then object.sendEvent ( obj, "MyPleoAI", "onChangeStates", "petting" ) end if(state == "stick") then log.message ( "STICK" ) object.sendEvent ( obj, "MyPleoAI", "onChangeStates", "stick" ) end if(state == "pill") then log.message ( "PILL" ) local hUser = application.getCurrentUser ( ) local festas = hud.getComponent ( hUser, "myHUD.Botao_Festas" ) hud.setComponentVisible ( festas, false) application.setCurrentUserScene ( "Game_Principal" ) end if(state == "good_exit") then log.message ( "GOOOD EXIST" ) local hUser = application.getCurrentUser ( ) local win = hud.getComponent ( hUser, "myHIT.win" ) hud.setComponentVisible ( win, false ) local festas = hud.getComponent ( hUser, "myHUD.Botao_Festas" ) hud.setComponentVisible ( festas, true ) local bar_prog = hud.getComponent ( hUser, "myHIT.bar_prog" ) hud.setComponentVisible ( bar_prog, false ) application.setCurrentUserEnvironmentVariable ( "bTrainingFinished", true ) application.setCurrentUserScene ( "Cena_Principal" ) end if(state == "ball") then log.message ( "BALL" ) object.sendEvent ( obj, "MyPleoAI", "onChangeStates", "ball" ) end -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
gpl-3.0
shiprabehera/kong
kong/plugins/aws-lambda/handler.lua
1
2747
-- Copyright (C) Mashape, Inc. local BasePlugin = require "kong.plugins.base_plugin" local aws_v4 = require "kong.plugins.aws-lambda.v4" local responses = require "kong.tools.responses" local utils = require "kong.tools.utils" local http = require "resty.http" local cjson = require "cjson.safe" local public_utils = require "kong.tools.public" local ngx_req_read_body = ngx.req.read_body local ngx_req_get_uri_args = ngx.req.get_uri_args local AWS_PORT = 443 local AWSLambdaHandler = BasePlugin:extend() function AWSLambdaHandler:new() AWSLambdaHandler.super.new(self, "aws-lambda") end local function retrieve_parameters() ngx_req_read_body() return utils.table_merge(ngx_req_get_uri_args(), public_utils.get_body_args()) end function AWSLambdaHandler:access(conf) AWSLambdaHandler.super.access(self) local bodyJson = cjson.encode(retrieve_parameters()) local host = string.format("lambda.%s.amazonaws.com", conf.aws_region) local path = string.format("/2015-03-31/functions/%s/invocations", conf.function_name) local opts = { region = conf.aws_region, service = "lambda", method = "POST", headers = { ["X-Amz-Target"] = "invoke", ["X-Amz-Invocation-Type"] = conf.invocation_type, ["X-Amx-Log-Type"] = conf.log_type, ["Content-Type"] = "application/x-amz-json-1.1", ["Content-Length"] = tostring(#bodyJson) }, body = bodyJson, path = path, access_key = conf.aws_key, secret_key = conf.aws_secret, query = conf.qualifier and "Qualifier=" .. conf.qualifier } local request, err = aws_v4(opts) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end -- Trigger request local client = http.new() client:connect(host, conf.port or AWS_PORT) client:set_timeout(conf.timeout) local ok, err = client:ssl_handshake() if not ok then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end local res, err = client:request { method = "POST", path = request.url, body = request.body, headers = request.headers } if not res then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end local body = res:read_body() local headers = res.headers local ok, err = client:set_keepalive(conf.keepalive) if not ok then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end if conf.unhandled_status and headers["X-Amz-Function-Error"] == "Unhandled" then ngx.status = conf.unhandled_status else ngx.status = res.status end -- Send response to client for k, v in pairs(headers) do ngx.header[k] = v end ngx.say(body) return ngx.exit(res.status) end AWSLambdaHandler.PRIORITY = 750 return AWSLambdaHandler
apache-2.0
liruqi/bigfoot
Interface/AddOns/Skada/lib/SpecializedLibBars-1.0/SpecializedLibBars-1.0.lua
2
40560
-- LibBars-1.0 by Antiarc, all glory to him, ripped into pieces for Skada. local MAJOR = "SpecializedLibBars-1.0" local MINOR = 900000 + tonumber(("$Revision: 1 $"):match("%d+")) local lib, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end -- No Upgrade needed. local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") local GetTime = _G.GetTime local sin, cos, rad = _G.math.sin, _G.math.cos, _G.math.rad local abs, min, max, floor = _G.math.abs, _G.math.min, _G.math.max, _G.math.floor local table_sort, tinsert, tremove, tconcat = _G.table.sort, tinsert, tremove, _G.table.concat local next, pairs, assert, error, type, xpcall = next, pairs, assert, error, type, xpcall --[[ xpcall safecall implementation ]] 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 dummyFrame, barFrameMT, barPrototype, barPrototype_mt, barListPrototype local barListPrototype_mt lib.LEFT_TO_RIGHT = 1 lib.BOTTOM_TO_TOP = 2 lib.RIGHT_TO_LEFT = 3 lib.TOP_TO_BOTTOM = 4 lib.dummyFrame = lib.dummyFrame or CreateFrame("Frame") lib.barFrameMT = lib.barFrameMT or {__index = lib.dummyFrame} lib.barPrototype = lib.barPrototype or setmetatable({}, lib.barFrameMT) lib.barPrototype_mt = lib.barPrototype_mt or {__index = lib.barPrototype} lib.barListPrototype = lib.barListPrototype or setmetatable({}, lib.barFrameMT) lib.barListPrototype_mt = lib.barListPrototype_mt or {__index = lib.barListPrototype} dummyFrame = lib.dummyFrame barFrameMT = lib.barFrameMT barPrototype = lib.barPrototype barPrototype_mt = lib.barPrototype_mt barListPrototype = lib.barListPrototype barListPrototype_mt = lib.barListPrototype_mt barPrototype.prototype = barPrototype barPrototype.metatable = barPrototype_mt barPrototype.super = dummyFrame barListPrototype.prototype = barListPrototype barListPrototype.metatable = barListPrototype_mt barListPrototype.super = dummyFrame lib.bars = lib.bars or {} lib.barLists = lib.barLists or {} lib.recycledBars = lib.recycledBars or {} lib.embeds = lib.embeds or {} local bars = lib.bars local barLists = lib.barLists local recycledBars = lib.recycledBars local frame_defaults = { bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", inset = 4, edgeSize = 8, tile = true, insets = {left = 2, right = 2, top = 2, bottom = 2} } do local mixins = { "NewCounterBar", "NewBarFromPrototype", "GetBar", "GetBars", "HasBar", "IterateBars", "NewBarGroup", "ReleaseBar", "GetBarGroup", "GetBarGroups" } function lib:Embed(target) for k, v in pairs( mixins ) do target[v] = self[v] end lib.embeds[target] = true return target end end local ComputeGradient do local new, del do local list = lib.garbageList or setmetatable({}, {__mode='k'}) lib.garbageList = list -- new is always called with the exact same arguments, no need to -- iterate over a vararg function new(a1, a2, a3, a4, a5) local t = next(list) if t then list[t] = nil t[1] = a1 t[2] = a2 t[3] = a3 t[4] = a4 t[5] = a5 else t = {a1, a2, a3, a4, a5} end return t end -- del is called over the same tables produced from new, no need for -- fancy stuff function del(t) t[1] = nil t[2] = nil t[3] = nil t[4] = nil t[5] = nil t[''] = true t[''] = nil list[t] = true return nil end end local function sort_colors(a, b) return a[1] < b[1] end local colors = {} local function getColor(point) local lowerBound = colors[1] local upperBound = colors[#colors] local lowerBoundIndex, upperBoundIndex = 0, 1 for i = 1, #colors do if colors[i][1] >= point then if i > 1 then lowerBound = colors[i-1] lowerBoundIndex = colors[i-1][1] end upperBound = colors[i] upperBoundIndex = colors[i][1] break end end --local pct = (point - lowerBoundIndex) / (upperBoundIndex - lowerBoundIndex) local diff = (upperBoundIndex - lowerBoundIndex) local pct = 1 if diff ~= 0 then pct = (point - lowerBoundIndex) / diff end local r = lowerBound[2] + ((upperBound[2] - lowerBound[2]) * pct) local g = lowerBound[3] + ((upperBound[3] - lowerBound[3]) * pct) local b = lowerBound[4] + ((upperBound[4] - lowerBound[4]) * pct) local a = lowerBound[5] + ((upperBound[5] - lowerBound[5]) * pct) return r, g, b, a end function ComputeGradient(self) self.gradMap = self.gradMap or {} if not self.colors then return end if #self.colors == 0 then for k in pairs(self.gradMap) do self.gradMap[k] = nil end return end for i = 1, #colors do del(tremove(colors)) end for i = 1, #self.colors, 5 do tinsert(colors, new(self.colors[i], self.colors[i+1], self.colors[i+2], self.colors[i+3], self.colors[i+4])) end table_sort(colors, sort_colors) for i = 0, 200 do local r, g, b, a = getColor(i / 200) self.gradMap[(i*4)] = r self.gradMap[(i*4)+1] = g self.gradMap[(i*4)+2] = b self.gradMap[(i*4)+3] = a end end end function lib:GetBar(name) return bars[self] and bars[self][name] end function lib:GetBars(name) return bars[self] end function lib:HasAnyBar() return not not (bars[self] and next(bars[self])) end do local function NOOP() end function lib:IterateBars() if bars[self] then return pairs(bars[self]) else return NOOP end end end -- Convenient method to create a new, empty bar prototype function lib:NewBarPrototype(super) assert(super == nil or (type(super) == "table" and type(super.metatable) == "table"), "!NewBarPrototype: super must either be nil or a valid prototype") super = super or barPrototype local prototype = setmetatable({}, super.metatable) prototype.prototype = prototype prototype.super = super prototype.metatable = { __index = prototype } return prototype end --[[ Individual bars ]]-- function lib:NewBarFromPrototype(prototype, name, ...) assert(self ~= lib, "You may only call :NewBar as an embedded function") assert(type(prototype) == "table" and type(prototype.metatable) == "table", "Invalid bar prototype") bars[self] = bars[self] or {} local bar = bars[self][name] local isNew = false if not bar then isNew = true bar = tremove(recycledBars) if not bar then bar = CreateFrame("Frame") else bar:Show() end end bar = setmetatable(bar, prototype.metatable) bar.name = name bar:Create(...) bar:SetFont(self.font, self.fontSize, self.fontFlags) bars[self][name] = bar return bar, isNew end function lib:NewCounterBar(name, text, value, maxVal, icon, orientation, length, thickness) return self:NewBarFromPrototype(barPrototype, name, text, value, maxVal, icon, orientation, length, thickness) end function lib:ReleaseBar(name) if not bars[self] then return end local bar if type(name) == "string" then bar = bars[self][name] elseif type(name) == "table" then if name.name and bars[self][name.name] == name then bar = name end end if bar then bar:SetScript("OnEnter", nil) bar:SetScript("OnLeave", nil) bar:OnBarReleased() bars[self][bar.name] = nil tinsert(recycledBars, bar) end end ---[[ Bar Groups ]]--- function barListPrototype:AddButton(title, description, normaltex, highlighttex, clickfunc) -- Create button frame. local btn = CreateFrame("Button", nil, self.button) btn.title = title btn:SetFrameLevel(5) btn:ClearAllPoints() btn:SetHeight(12) btn:SetWidth(12) btn:SetNormalTexture(normaltex) btn:SetHighlightTexture(highlighttex, 1.0) btn:SetAlpha(0.25) btn:RegisterForClicks("LeftButtonUp", "RightButtonUp") btn:SetScript("OnClick", clickfunc) btn:SetScript("OnEnter", function(this) GameTooltip_SetDefaultAnchor(GameTooltip, this) GameTooltip:SetText(title) GameTooltip:AddLine(description, 1, 1, 1, true) GameTooltip:Show() end) btn:SetScript("OnLeave", function() GameTooltip:Hide() end) btn:Show() -- Add to our list of buttons. tinsert(self.buttons, btn) self:AdjustButtons() end function barListPrototype:SetSmoothing(smoothing) self.smoothing = smoothing if smoothing then self:SetScript("OnUpdate", function() if bars[self] then for k, v in pairs(bars[self]) do if v.targetamount and v:IsShown() then local amt if v.targetamount > v.lastamount then amt = min(((v.targetamount - v.lastamount) / 10) + v.lastamount, v.targetamount) else amt = max(v.lastamount - ((v.lastamount - v.targetamount) / 10), v.targetamount) end v.lastamount = amt if amt == v.targetamount then v.targetamount = nil end v:SetTextureValue(amt, v.targetdist) end end end end) else self:SetScript("OnUpdate", nil) end end function barListPrototype:SetButtonsOpacity(alpha) for i, btn in ipairs(self.buttons) do btn:SetAlpha(alpha) end end function barListPrototype:AdjustButtons() local nr = 0 local lastbtn = nil for i, btn in ipairs(self.buttons) do btn:ClearAllPoints() if btn:IsShown() then if nr == 0 then btn:SetPoint("TOPRIGHT", self.button, "TOPRIGHT", -5, 0 - (max(self.button:GetHeight() - btn:GetHeight(), 0) / 2)) else btn:SetPoint("TOPRIGHT", lastbtn, "TOPLEFT", 0, 0) end lastbtn = btn nr = nr + 1 end end if lastbtn then self.button:GetFontString():SetPoint("RIGHT", lastbtn, "LEFT") else self.button:GetFontString():SetPoint("RIGHT", self.button, "RIGHT") end end function barListPrototype:SetBarBackgroundColor(r, g, b, a) self.barbackgroundcolor = {r,g,b,a} for i, bar in pairs(self:GetBars()) do bar.bgtexture:SetVertexColor(unpack(self.barbackgroundcolor)) end end function barListPrototype:ShowButton(title, visible) for i, b in ipairs(self.buttons) do if b.title == title then if visible then b:Show() else b:Hide() end end end self:AdjustButtons() end do local function move(self) if not self:GetParent().locked then self.startX = self:GetParent():GetLeft() self.startY = self:GetParent():GetTop() self:GetParent():StartMoving() end end local function stopMove(self) if not self:GetParent().locked then self:GetParent():StopMovingOrSizing() local endX = self:GetParent():GetLeft() local endY = self:GetParent():GetTop() if self.startX ~= endX or self.startY ~= endY then self:GetParent().callbacks:Fire("AnchorMoved", self:GetParent(), endX, endY) end end end local DEFAULT_TEXTURE = [[Interface\TARGETINGFRAME\UI-StatusBar]] function lib:NewBarGroup(name, orientation, height, length, thickness, frameName) if self == lib then error("You may only call :NewBarGroup as an embedded function") end barLists[self] = barLists[self] or {} if barLists[self][name] then error("A bar list named " .. name .. " already exists.") end orientation = orientation or lib.LEFT_TO_RIGHT orientation = orientation == "LEFT" and lib.LEFT_TO_RIGHT or orientation orientation = orientation == "RIGHT" and lib.RIGHT_TO_LEFT or orientation local list = setmetatable(CreateFrame("Frame", frameName, UIParent), barListPrototype_mt) list:SetMovable(true) list:SetClampedToScreen(true) list.enablemouse = true list.callbacks = list.callbacks or CallbackHandler:New(list) barLists[self][name] = list list.name = name --[[ list:SetBackdrop({ bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", inset = 0, edgeSize = 12, tile = true }) --]] local myfont = CreateFont("MyTitleFont") myfont:CopyFontObject(ChatFontSmall) list.button = CreateFrame("Button", nil, list) list.button:SetText(name) list.button:SetBackdrop(frame_defaults) list.button:SetNormalFontObject(myfont) list.length = length or 200 list.thickness = thickness or 15 list:SetOrientation(orientation) list:UpdateOrientationLayout() list.button:SetScript("OnMouseDown", move) list.button:SetScript("OnMouseUp", stopMove) list.button:SetBackdropColor(0,0,0,1) list.button:RegisterForClicks("LeftButtonUp", "RightButtonUp", "MiddleButtonUp", "Button4Up", "Button5Up") list.buttons = {} list.barbackgroundcolor = {0.3, 0.3, 0.3, 0.6}, list:SetPoint("TOPLEFT", UIParent, "CENTER", 0, 0) list:SetHeight(height) list:SetWidth(length) list:SetResizable(true) list:SetMinResize(60,40) list:SetMaxResize(800,800) list.showIcon = true list.showLabel = true list.showTimerLabel = true list.lastBar = list list.locked = false list.texture = DEFAULT_TEXTURE list.spacing = 0 list.offset = 0 list.resizebutton = CreateFrame("Button", "BarGroupResizeButton", list) list.resizebutton:Show() list.resizebutton:SetFrameLevel(11) list.resizebutton:SetWidth(16) list.resizebutton:SetHeight(16) list.resizebutton:EnableMouse(true) list.resizebutton:SetScript("OnMouseDown", function(self,button) local p = self:GetParent() if(button == "LeftButton") then p.isResizing = true if p.growup then p:StartSizing("TOPRIGHT") else p:StartSizing("BOTTOMRIGHT") end p:SetScript("OnUpdate", function() if p.isResizing then -- Adjust bar sizes. p:SetLength(p:GetWidth()) else p:SetScript("OnUpdate", nil) end end) end end) list.resizebutton:SetScript("OnMouseUp", function(self,button) local p = self:GetParent() local top, left = p:GetTop(), p:GetLeft() if p.isResizing == true then p:StopMovingOrSizing() p:SetLength(p:GetWidth()) p.callbacks:Fire("WindowResized", self:GetParent()) p.isResizing = false p:SortBars() end end) list:ReverseGrowth(false) return list end end function lib:GetBarGroups() return barLists[self] end function lib:GetBarGroup(name) return barLists[self] and barLists[self][name] end --[[ BarList prototype ]]-- function barListPrototype:NewBarFromPrototype(prototype, ...) local bar, isNew = lib.NewBarFromPrototype(self, prototype, ...) bar:SetTexture(self.texture) bar:SetFill(self.fill) -- if isNew then bar:SetValue(0) end if self.showIcon then bar:ShowIcon() else bar:HideIcon(bar) end if self.showLabel then bar:ShowLabel() else bar:HideLabel(bar) end if self.showTimerLabel then bar:ShowTimerLabel() else bar:HideTimerLabel(bar) end self:SortBars() bar.ownerGroup = self bar:SetParent(self) bar:EnableMouse(self.enablemouse) return bar, isNew end function barListPrototype:SetEnableMouse(enablemouse) self.enablemouse = enablemouse self:EnableMouse(enablemouse) for i, bar in pairs(self:GetBars()) do bar:EnableMouse(enablemouse) end end function barListPrototype:SetBarWidth(width) self:SetLength(width) end function barListPrototype:SetBarHeight(height) self:SetThickness(height) end function barListPrototype:NewCounterBar(name, text, value, maxVal, icon) local bar = self:NewBarFromPrototype(barPrototype, name, text, value, maxVal, icon, self.orientation, self.length, self.thickness) -- Apply barlist settings. bar.bgtexture:SetVertexColor(unpack(self.barbackgroundcolor)) return bar end function barListPrototype:Lock() -- Hide resize button. self.resizebutton:Hide() self.locked = true end function barListPrototype:Unlock() -- Show resize button. self.resizebutton:Show() self.locked = false end function barListPrototype:IsLocked() return self.locked end -- Max number of bars to display. nil to display all. function barListPrototype:SetMaxBars(num) self.maxBars = num end function barListPrototype:GetMaxBars() return self.maxBars end function barListPrototype:SetTexture(tex) self.texture = tex if bars[self] then for k, v in pairs(bars[self]) do v:SetTexture(tex) end end end function barListPrototype:SetFont(f, s, m) self.font, self.fontSize, self.fontFlags = f, s, m if bars[self] then for k, v in pairs(bars[self]) do v:SetFont(f, s, m) end end end function barListPrototype:SetFill(fill) self.fill = fill if bars[self] then for k, v in pairs(bars[self]) do v:SetFill(fill) end end end function barListPrototype:IsFilling() return self.fill end function barListPrototype:ShowIcon() self.showIcon = true if not bars[self] then return end for name,bar in pairs(bars[self]) do bar:ShowIcon() end end function barListPrototype:HideIcon() self.showIcon = false if not bars[self] then return end for name, bar in pairs(bars[self]) do bar:HideIcon() end end function barListPrototype:IsIconShown() return self.showIcon end function barListPrototype:ShowLabel() self.showLabel = true for name,bar in pairs(bars[self]) do bar:ShowLabel() end end function barListPrototype:HideLabel() self.showLabel = false for name,bar in pairs(bars[self]) do bar:HideLabel() end end function barListPrototype:IsLabelShown() return self.showLabel end function barListPrototype:ShowTimerLabel() self.showTimerLabel = true for name,bar in pairs(bars[self]) do bar:ShowTimerLabel() end end function barListPrototype:HideTimerLabel() self.showTimerLabel = false for name,bar in pairs(bars[self]) do bar:HideTimerLabel() end end function barListPrototype:IsValueLabelShown() return self.showTimerLabel end function barListPrototype:SetSpacing(spacing) self.spacing = spacing self:SortBars() end function barListPrototype:GetSpacing() return self.spacing end barListPrototype.GetBar = lib.GetBar barListPrototype.GetBars = lib.GetBars barListPrototype.HasAnyBar = lib.HasAnyBar barListPrototype.IterateBars = lib.IterateBars function barListPrototype:RemoveBar(bar) lib.ReleaseBar(self, bar) end function barListPrototype:SetDisplayMax(val) self.displayMax = val end function barListPrototype:UpdateColors() -- Force a color update on all the bars, particularly the counter bars if bars[self] then for k, v in pairs(bars[self]) do v:UpdateColor() -- if not v.isTimer then -- v:UpdateColor() -- end end end end function barListPrototype:SetColorAt(at, r, g, b, a) self.colors = self.colors or {} tinsert(self.colors, at) tinsert(self.colors, r) tinsert(self.colors, g) tinsert(self.colors, b) tinsert(self.colors, a) ComputeGradient(self) self:UpdateColors() end function barListPrototype:UnsetColorAt(at) if not self.colors then return end for i = 1, #self.colors, 5 do if self.colors[i] == at then for j = 1, 5 do tremove(self.colors, i) end ComputeGradient(self) self:UpdateColors() return end end end function barListPrototype:UnsetAllColors() if not self.colors then return end for i = 1, #self.colors do tremove(self.colors) end return end function barListPrototype:ShowAnchor() self.button:Show() self:SortBars() end function barListPrototype:HideAnchor() self.button:Hide() self:SortBars() end function barListPrototype:IsAnchorVisible() return self.button:IsVisible() end function barListPrototype:ToggleAnchor() if self.button:IsVisible() then self.button:Hide() else self.button:Show() end self:SortBars() end function barListPrototype:GetBarAttachPoint() local growup, lastBar = self.growup, self.lastBar if growup then return lastBar:GetLeft(), lastBar:GetTop() + lastBar:GetHeight() else return lastBar:GetLeft(), lastBar:GetBottom() - lastBar:GetHeight() end end function barListPrototype:ReverseGrowth(reverse) self.growup = reverse self.button:ClearAllPoints() if reverse then self.button:SetPoint("TOPLEFT", self, "BOTTOMLEFT") self.button:SetPoint("TOPRIGHT", self, "BOTTOMRIGHT") else self.button:SetPoint("BOTTOMLEFT", self, "TOPLEFT") self.button:SetPoint("BOTTOMRIGHT", self, "TOPRIGHT") end if self.resizebutton then self.resizebutton:SetNormalTexture("Interface\\CHATFRAME\\UI-ChatIM-SizeGrabber-Up") self.resizebutton:SetHighlightTexture("Interface\\CHATFRAME\\UI-ChatIM-SizeGrabber-Down") self.resizebutton:ClearAllPoints() if reverse then self.resizebutton:GetNormalTexture():SetRotation(math.pi/2) self.resizebutton:GetHighlightTexture():SetRotation(math.pi/2) self.resizebutton:SetPoint("TOPRIGHT", self, "TOPRIGHT", 0, 0) else self.resizebutton:GetNormalTexture():SetRotation(0) self.resizebutton:GetHighlightTexture():SetRotation(0) self.resizebutton:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", 0, 0) end end self:SortBars() end function barListPrototype:HasReverseGrowth() return self.growup end function barListPrototype:UpdateOrientationLayout() local length, thickness = self.length, self.thickness barListPrototype.super.SetWidth(self, length) self.button:SetWidth(length) self:ReverseGrowth(self.growup) end function barListPrototype:SetLength(length) self.length = length if bars[self] then for k, v in pairs(bars[self]) do v:SetLength(length) v:OnSizeChanged() -- widget fires this before .length is set, do it again to ensure update end end self:UpdateOrientationLayout() end function barListPrototype:GetLength() return self.length end function barListPrototype:SetThickness(thickness) self.thickness = thickness if bars[self] then for k, v in pairs(bars[self]) do v:SetThickness(thickness) end end self:UpdateOrientationLayout() end function barListPrototype:GetThickness() return self.thickness end function barListPrototype:SetOrientation(orientation) self.orientation = orientation if bars[self] then for k, v in pairs(bars[self]) do v:SetOrientation(orientation) end end self:UpdateOrientationLayout() end function barListPrototype:GetOrientation() return self.orientation end -- MODIFIED -- Allows nil sort function. function barListPrototype:SetSortFunction(func) if func then assert(type(func) == "function") end self.sortFunc = func end function barListPrototype:GetSortFunction(func) return self.sortFunc end -- MODIFIED function barListPrototype:SetBarOffset(offset) self.offset = offset self:SortBars() end -- MODIFIED function barListPrototype:GetBarOffset() return self.offset end -- group:SetSortFunction(group.NOOP) to disable sorting function barListPrototype.NOOP() end do local values = {} local function sortFunc(a, b) local apct, bpct = a.value / a.maxValue, b.value / b.maxValue if apct == bpct then if a.maxValue == b.maxValue then return a.name > b.name else return a.maxValue > b.maxValue end else return apct > bpct end end function barListPrototype:SortBars() local lastBar = self local ct = 0 local has_fixed = false if not bars[self] then return end for k, v in pairs(bars[self]) do ct = ct + 1 values[ct] = v v:Hide() if v.fixed then has_fixed = true end end for i = ct + 1, #values do values[i] = nil end if #values == 0 then return end table_sort(values, self.sortFunc or sortFunc) local orientation = self.orientation local growup = self.growup local spacing = self.spacing local from, to local thickness, showIcon = self.thickness, self.showIcon local offset = self.offset local x1, y1, x2, y2 = 0, 0, 0, 0 local maxbars = min(#values, floor(self:GetHeight() / (thickness + spacing))) local start, stop, step if growup then from = "BOTTOM" to = "TOP" start = min(#values, maxbars + offset) stop = min(#values, 1 + offset) step = -1 else from = "TOP" to = "BOTTOM" start = min(1 + offset, #values) stop = min(maxbars + offset, #values) step = 1 end -- Fixed bar replaces the last bar if has_fixed and stop < #values then for i = stop + 1, #values, 1 do if values[i].fixed then tinsert(values, stop, values[i]) break end end end local shown = 0 local last_icon = false for i = start, stop, step do local origTo = to local v = values[i] if lastBar == self then to = from y1, y2 = 0, 0 else if growup then y1, y2 = spacing, spacing else y1, y2 = -spacing, -spacing end end x1, x2 = 0, 0 -- Silly hack to fix icon positions. I should just rewrite the whole thing, really. WTB energy. if showIcon and lastBar == self then if orientation == 1 then x1 = thickness else x2 = -thickness end end if shown <= maxbars then v:ClearAllPoints() v:SetPoint(from.."LEFT", lastBar, to.."LEFT", x1, y1) v:SetPoint(from.."RIGHT", lastBar, to.."RIGHT", x2, y2) v:Show() shown = shown + 1 if v.showIcon then last_icon = true end lastBar = v end to = origTo end self.lastBar = lastBar end end --[[ **************************************************************** *** Bar methods **************************************************************** ]]-- --[[ Bar Prototype ]]-- do local function barClick(self, button) self:GetParent().callbacks:Fire("BarClick", self:GetParent(), button) end local function barEnter(self, button) self:GetParent().callbacks:Fire("BarEnter", self:GetParent(), button) end local function barLeave(self, button) self:GetParent().callbacks:Fire("BarLeave", self:GetParent(), button) end local DEFAULT_ICON = 134400 function barPrototype:Create(text, value, maxVal, icon, orientation, length, thickness) self.callbacks = self.callbacks or CallbackHandler:New(self) self:SetScript("OnSizeChanged", self.OnSizeChanged) self.texture = self.texture or self:CreateTexture(nil, "ARTWORK") self.bgtexture = self.bgtexture or self:CreateTexture(nil, "BACKGROUND") self.bgtexture:SetAllPoints() self.bgtexture:SetVertexColor(0.3, 0.3, 0.3, 0.6) self.icon = self.icon or self:CreateTexture(nil, "OVERLAY") self.icon:SetPoint("LEFT", self, "LEFT", 0, 0) self:SetIcon(icon or DEFAULT_ICON) if icon then self:ShowIcon() end self.icon:SetTexCoord(0.07,0.93,0.07,0.93); -- Lame frame solely used for handling mouse input on icon. self.iconFrame = self.iconFrame or CreateFrame("Frame", nil, self) self.iconFrame:SetAllPoints(self.icon) self.label = self.label or self:CreateFontString(nil, "OVERLAY", "ChatFontNormal") self.label:SetWordWrap(false); self.label:SetText(text) self.label:ClearAllPoints() self.label:SetPoint("LEFT", self, "LEFT", 3, 0) self:ShowLabel() local f, s, m = self.label:GetFont() self.label:SetFont(f, s or 10, m) self.timerLabel = self.timerLabel or self:CreateFontString(nil, "OVERLAY", "ChatFontNormal") self:SetTimerLabel("") self.timerLabel:ClearAllPoints() self.timerLabel:SetPoint("RIGHT", self, "RIGHT", -6, 0) self:HideTimerLabel() local f, s, m = self.timerLabel:GetFont() self.timerLabel:SetFont(f, s or 10, m) self:SetScale(1) self:SetAlpha(1) self.length = length or 200 self.thickness = thickness or 15 self:SetOrientation(orientation or 1) value = value or 1 maxVal = maxVal or value self.value = value self.maxValue = maxVal self:SetMaxValue(maxVal) self:SetValue(value) end end barPrototype.SetWidth = barListPrototype.SetBarWidth barPrototype.SetHeight = barListPrototype.SetBarHeight function barPrototype:OnBarReleased() self.callbacks:Fire('BarReleased', self, self.name) -- Reset our attributes self.ownerGroup = nil self.fill = false if self.colors then for k, v in pairs(self.colors) do self.colors[k] = nil end end if self.gradMap then for k, v in pairs(self.gradMap) do self.gradMap[k] = nil end end -- Reset widget self.texture:SetVertexColor(1, 1, 1, 0) self:SetScript("OnUpdate", nil) self:SetParent(UIParent) self:ClearAllPoints() self:Hide() local f, s, m = ChatFontNormal:GetFont() self.label:SetFont(f, s or 10, m) self.timerLabel:SetFont(f, s or 10, m) -- Cancel all registered callbacks. CBH doesn't seem to provide a method to do this. if self.callbacks.insertQueue then for eventname, callbacks in pairs(self.callbacks.insertQueue) do for k, v in pairs(callbacks) do callbacks[k] = nil end end end for eventname, callbacks in pairs(self.callbacks.events) do for k, v in pairs(callbacks) do callbacks[k] = nil end if self.callbacks.OnUnused then self.callbacks.OnUnused(self.callbacks, target, eventname) end end end function barPrototype:GetGroup() return self.ownerGroup end function barPrototype:OnSizeChanged() self:SetValue(self.value) end function barPrototype:SetFont(newFont, newSize, newFlags) local t, font, size, flags t = self.label font, size, flags = t:GetFont() t:SetFont(newFont or font, newSize or size, newFlags or flags) t = self.timerLabel font, size, flags = t:GetFont() t:SetFont(newFont or font, newSize or size, newFlags or flags) end function barPrototype:SetIconWithCoord(icon, coord) if icon then self.icon:SetTexture(icon) self.icon:SetTexCoord(unpack(coord)) if self.showIcon then self.icon:Show() end else self.icon:Hide() end self.iconTexture = icon or nil end function barPrototype:SetIcon(icon) if icon then self.icon:SetTexture(icon) if self.showIcon then self.icon:Show() end else self.icon:Hide() end self.iconTexture = icon or nil end function barPrototype:ShowIcon() self.showIcon = true if self.iconTexture then self.icon:Show() end end function barPrototype:HideIcon() self.showIcon = false self.icon:Hide() end function barPrototype:IsIconShown() return self.showIcon end function barPrototype:SetLabel(text) self.label:SetText(text) end function barPrototype:GetLabel(text) return self.label:GetText(text) end barPrototype.SetText = barPrototype.SetLabel -- for API compatibility barPrototype.GetText = barPrototype.GetLabel -- for API compatibility function barPrototype:ShowLabel() self.showLabel = true self.label:Show() end function barPrototype:HideLabel() self.showLabel = false self.label:Hide() end function barPrototype:IsLabelShown() return self.showLabel end function barPrototype:SetTimerLabel(text) self.timerLabel:SetText(text) end function barPrototype:GetTimerLabel(text) return self.timerLabel:GetText(text) end function barPrototype:ShowTimerLabel() self.showTimerLabel = true self.timerLabel:Show() end function barPrototype:HideTimerLabel() self.showTimerLabel = false self.timerLabel:Hide() end function barPrototype:IsValueLabelShown() return self.showTimerLabel end function barPrototype:SetTexture(texture) self.texture:SetTexture(texture) self.bgtexture:SetTexture(texture) end -- Added by Ulic -- Allows for the setting of background colors for a specific bar -- Someday I'll figure out to do it at the group level function barPrototype:SetBackgroundColor(r, g, b, a) a = a or .6 if r and g and b and a then self.bgtexture:SetVertexColor(r, g, b, a) end end function barPrototype:SetColorAt(at, r, g, b, a) self.colors = self.colors or {} tinsert(self.colors, at) tinsert(self.colors, r) tinsert(self.colors, g) tinsert(self.colors, b) tinsert(self.colors, a) ComputeGradient(self) self:UpdateColor() end function barPrototype:UnsetColorAt(at) if not self.colors then return end for i = 1, #self.colors, 5 do if self.colors[i] == at then for j = 1, 5 do tremove(self.colors, i) end ComputeGradient(self) self:UpdateColor() return end end end function barPrototype:UnsetAllColors() if not self.colors then return end for i = 1, #self.colors do tremove(self.colors) end end do function barPrototype:UpdateOrientationLayout() local o = self.orientation local t if o == lib.LEFT_TO_RIGHT then self.icon:ClearAllPoints() self.icon:SetPoint("RIGHT", self, "LEFT", 0, 0) t = self.texture t.SetValue = t.SetWidth t:ClearAllPoints() t:SetPoint("TOPLEFT", self, "TOPLEFT") t:SetPoint("BOTTOMLEFT", self, "BOTTOMLEFT") -- t:SetTexCoord(0, 1, 0, 1) t = self.timerLabel t:ClearAllPoints() t:SetPoint("RIGHT", self, "RIGHT", -6, 0) t:SetJustifyH("RIGHT") t:SetJustifyV("MIDDLE") t = self.label t:ClearAllPoints() t:SetPoint("LEFT", self, "LEFT", 6, 0) t:SetPoint("RIGHT", self.timerLabel, "LEFT", 0, 0) t:SetJustifyH("LEFT") t:SetJustifyV("MIDDLE") self.bgtexture:SetTexCoord(0, 1, 0, 1) elseif o == lib.BOTTOM_TO_TOP then self.icon:ClearAllPoints() self.icon:SetPoint("TOP", self, "BOTTOM", 0, 0) t = self.texture t.SetValue = t.SetHeight t:ClearAllPoints() t:SetPoint("BOTTOMLEFT", self, "BOTTOMLEFT") t:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT") -- t:SetTexCoord(0, 1, 1, 1, 0, 0, 1, 0) t = self.timerLabel t:ClearAllPoints() t:SetPoint("TOPLEFT", self, "TOPLEFT", 3, -3) t:SetPoint("TOPRIGHT", self, "TOPRIGHT", -3, -3) t:SetJustifyH("CENTER") t:SetJustifyV("TOP") t = self.label t:ClearAllPoints() t:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", -3, 3) t:SetPoint("TOPLEFT", self.Label, "BOTTOMLEFT", 0, 0) t:SetJustifyH("CENTER") t:SetJustifyV("BOTTOM") self.bgtexture:SetTexCoord(0, 1, 1, 1, 0, 0, 1, 0) elseif o == lib.RIGHT_TO_LEFT then self.icon:ClearAllPoints() self.icon:SetPoint("LEFT", self, "RIGHT", 0, 0) t = self.texture t.SetValue = t.SetWidth t:ClearAllPoints() t:SetPoint("TOPRIGHT", self, "TOPRIGHT") t:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT") -- t:SetTexCoord(0, 1, 0, 1) t = self.timerLabel t:ClearAllPoints() t:SetPoint("LEFT", self, "LEFT", 6, 0) t:SetJustifyH("LEFT") t:SetJustifyV("MIDDLE") t = self.label t:ClearAllPoints() t:SetPoint("RIGHT", self, "RIGHT", -6, 0) t:SetPoint("LEFT", self.timerLabel, "RIGHT", 0, 0) t:SetJustifyH("RIGHT") t:SetJustifyV("MIDDLE") self.bgtexture:SetTexCoord(0, 1, 0, 1) elseif o == lib.TOP_TO_BOTTOM then self.icon:ClearAllPoints() self.icon:SetPoint("BOTTOM", self, "TOP", 0, 0) t = self.texture t.SetValue = t.SetHeight t:ClearAllPoints() t:SetPoint("TOPLEFT", self, "TOPLEFT") t:SetPoint("TOPRIGHT", self, "TOPRIGHT") -- t:SetTexCoord(0, 1, 1, 1, 0, 0, 1, 0) t = self.timerLabel t:ClearAllPoints() t:SetPoint("BOTTOMLEFT", self, "BOTTOMLEFT", 3, 3) t:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", -3, 3) t:SetJustifyH("CENTER") t:SetJustifyV("BOTTOM") t = self.label t:ClearAllPoints() t:SetPoint("TOPLEFT", self, "TOPLEFT", 3, -3) t:SetPoint("BOTTOMRIGHT", self.timerLabel, "TOPRIGHT", 0, 0) t:SetJustifyH("CENTER") t:SetJustifyV("TOP") self.bgtexture:SetTexCoord(0, 1, 1, 1, 0, 0, 1, 0) end self:SetValue(self.value or 0) end end function barPrototype:GetLength() return self.length end do local function updateSize(self) local thickness, length = self.thickness, self.length local iconSize = self.showIcon and thickness or 0 local width = max(0.0001, length - iconSize) local height = thickness barPrototype.super.SetWidth(self, width) barPrototype.super.SetHeight(self, height) self.icon:SetWidth(thickness) self.icon:SetHeight(thickness) end function barPrototype:SetLength(length) self.length = length updateSize(self) end function barPrototype:SetThickness(thickness) self.thickness = thickness updateSize(self) end end function barPrototype:GetThickness() return self.thickness end function barPrototype:SetOrientation(orientation) self.orientation = orientation self:UpdateOrientationLayout() self:SetThickness(self.thickness) end function barPrototype:GetOrientation() return self.orientation end function barPrototype:SetValue(val) assert(val ~= nil, "Value cannot be nil!") self.value = val if not self.maxValue or val > self.maxValue then self.maxValue = val end local ownerGroup = self.ownerGroup local displayMax = ownerGroup and ownerGroup.displayMax or self.displayMax if displayMax then displayMax = min(displayMax, self.maxValue) else displayMax = self.maxValue end local amt = min(1, val / max(displayMax, 0.000001)) local dist = (ownerGroup and ownerGroup:GetLength()) or self.length amt = max(amt, 0.000001) if ownerGroup and ownerGroup.smoothing and self.lastamount then self:SetTextureTarget(amt, dist) else self.lastamount = amt self:SetTextureValue(amt, dist) end self:UpdateColor() end function barPrototype:SetTextureTarget(amt, dist) self.targetamount = amt self.targetdist = dist end function barPrototype:SetTextureValue(amt, dist) dist = max(0.0001, dist - (self.showIcon and self.thickness or 0)) local t, o = self.texture, self.orientation t:SetValue(amt * dist) if o == 1 then t:SetTexCoord(0, amt, 0, 1) elseif o == 2 then t:SetTexCoord(1 - amt, 1, 1, 1, 1 - amt, 0, 1, 0) elseif o == 3 then t:SetTexCoord(1 - amt, 1, 0, 1) elseif o == 4 then t:SetTexCoord(0, 1, amt, 1, 0, 0, amt, 0) end end function barPrototype:SetDisplayMax(val) self.displayMax = val end function barPrototype:SetMaxValue(val) self.maxValue = val self:SetValue(self.value) end function barPrototype:SetFill(fill) self.fill = fill end function barPrototype:UpdateColor() local amt = floor(self.value / max(self.maxValue,0.000001) * 200) * 4 local map if self.gradMap and #self.gradMap > 0 then map = self.gradMap elseif self.ownerGroup and self.ownerGroup.gradMap and #self.ownerGroup.gradMap > 0 then map = self.ownerGroup.gradMap end if map then self.texture:SetVertexColor(map[amt], map[amt+1], map[amt+2], map[amt+3]) end end --- Finally: upgrade our old embeds for target, v in pairs(lib.embeds) do lib:Embed(target) end
mit
Datamats/ServerContent
notagain/lua/notagain/aowl/commands/kick_ban.lua
1
6802
local easylua = requirex("easylua") aowl.AddCommand("kick", function(ply, line, target, reason) local ent = easylua.FindEntity(target) if ent:IsPlayer() then -- clean them up at least this well... if cleanup and cleanup.CC_Cleanup then cleanup.CC_Cleanup(ent,"gmod_cleanup",{}) end local rsn = reason or "byebye!!" aowlMsg("kick", tostring(ply).. " kicked " .. tostring(ent) .. " for " .. rsn) hook.Run("AowlTargetCommand", ply, "kick", ent, rsn) return ent:Kick(rsn or "byebye!!") end return false, aowl.TargetNotFound(target) end, "developers") local ok={d=true,m=true,y=true,s=true,h=true,w=true} local function parselength_en(line) -- no months. There has to be a ready made version of this. local res={} line=line:Trim():lower() if tonumber(line)~=nil then res.m=tonumber(line) elseif #line>1 then line=line:gsub("%s","") for dat,what in line:gmatch'([%d]+)(.)' do if res[what] then return false,"bad format" end if not ok[what] then return false,("bad type: "..what) end res[what]=tonumber(dat) or -1 end else return false,"empty string" end local len = 0 local d=res local ok if d.y then ok=true len = len + d.y*31556926 end if d.w then ok=true len = len + d.w*604800 end if d.d then ok=true len = len + d.d*86400 end if d.h then ok=true len = len + d.h*3600 end if d.m then ok=true len = len + d.m*60 end if d.s then ok=true len = len + d.s*1 end if not ok then return false,"nothing specified" end return len end aowl.AddCommand("ban", function(ply, line, target, length, reason) local id = easylua.FindEntity(target) local ip if banni then if not length then length = 60*10 else local len,err = parselength_en(length) if not len then return false,"Invalid ban length: "..tostring(err) end length = len end if length==0 then return false,"invalid ban length" end local whenunban = banni.UnixTime()+length local ispl=id:IsPlayer() and not id:IsBot() if not ispl then if not banni.ValidSteamID(target) then return false,"invalid steamid" end end local banID = ispl and id:SteamID() or target local banName = ispl and id:Name() or target local banner = IsValid(ply) and ply:SteamID() or "Console" if IsValid(ply) and length >= 172800 then -- >= 2 days if not isstring(reason) or reason:len() < 10 then return false,"ban time over 2 days, specify a longer, descriptive ban reason" end end reason = reason or "Banned by admin" banni.Ban( banID, banName, banner, reason, whenunban) hook.Run("AowlTargetCommand", ply, "ban", id, banName, banID, length, reason) return end if id:IsPlayer() then if id.SetRestricted then id:ChatPrint("You have been banned for " .. (reason or "being fucking annoying") .. ". Welcome to the ban bubble.") id:SetRestricted(true) return else ip = id:IPAddress():match("(.-):") id = id:SteamID() end else id = target end local t={"banid", tostring(length or 0), id} game.ConsoleCommand(table.concat(t," ")..'\n') --if ip then RunConsoleCommand("addip", length or 0, ip) end -- unban ip?? timer.Simple(0.1, function() local t={"kickid",id, tostring(reason or "no reason")} game.ConsoleCommand(table.concat(t," ")..'\n') game.ConsoleCommand("writeid\n") end) end, "developers") aowl.AddCommand("unban", function(ply, line, target,reason) local id = easylua.FindEntity(target) if id:IsPlayer() then if banni then banni.UnBan(id:SteamID(),IsValid(ply) and ply:SteamID() or "Console",reason or "Admin unban") return end if id.SetRestricted then id:SetRestricted(false) return else id = id:SteamID() end else id = target if banni then local unbanned = banni.UnBan(target,IsValid(ply) and ply:SteamID() or "Console",reason or "Quick unban by steamid") if not unbanned then local extra="" if not banni.ValidSteamID(target) then extra="(invalid steamid?)" end return false,"unable to unban "..tostring(id)..extra end return end end local t={"removeid",id} game.ConsoleCommand(table.concat(t," ")..'\n') game.ConsoleCommand("writeid\n") end, "developers") aowl.AddCommand("baninfo", function(ply, line, target) if not banni then return false,"no banni" end local id = easylua.FindEntity(target) local ip local steamid if id:IsPlayer() then steamid=id:SteamID() else steamid=target end local d = banni.ReadBanData(steamid) if not d then return false,"no ban data found" end local t={ ["whenunban"] = 1365779132, ["unbanreason"] = "Quick unban ingame", ["banreason"] = "Quick ban ingame", ["sid"] = "STEAM_0:1:33124674", ["numbans"] = 1, ["bannersid"] = "STEAM_0:0:13073749", ["whenunbanned"] = 1365779016, ["b"] = false, ["whenbanned"] = 1365779012, ["name"] = "β?μηζε ®", ["unbannersid"] = "STEAM_0:0:13073749", } ply:ChatPrint("Ban info: "..tostring(d.name)..' ('..tostring(d.sid)..')') ply:ChatPrint("Ban: "..(d.b and "YES" or "unbanned").. (d.numbans and ' (ban count: '..tostring(d.numbans)..')' or "") ) if not d.b then ply:ChatPrint("UnBan reason: "..tostring(d.unbanreason)) ply:ChatPrint("UnBan by "..tostring(d.unbannersid).." ( http://steamcommunity.com/profiles/"..tostring(util.SteamID64(d.unbannersid))..' )') end ply:ChatPrint("Ban reason: "..tostring(d.banreason)) ply:ChatPrint("Ban by "..tostring(d.bannersid).." ( http://steamcommunity.com/profiles/"..tostring(util.SteamID64(d.bannersid))..' )') local time = d.whenbanned and banni.DateString(d.whenbanned) if time then ply:ChatPrint("Ban start: "..tostring(time)) end local time = d.whenunban and banni.DateString(d.whenunban) if time then ply:ChatPrint("Ban end: "..tostring(time)) end local time = d.whenunban and d.whenbanned and d.whenunban-d.whenbanned if time then ply:ChatPrint("Ban length: "..string.NiceTime(time)) end local time = d.b and d.whenunban and d.whenunban-os.time() if time then ply:ChatPrint("Remaining: "..string.NiceTime(time)) end local time = d.whenunbanned and banni.DateString(d.whenunbanned) if time then ply:ChatPrint("Unbanned: "..tostring(time)) end end, "players", true) aowl.AddCommand("exit", function(ply, line, target, reason) local ent = easylua.FindEntity(target) if not ply:IsAdmin() and ply ~= ent then return false, "Since you are not an admin, you can only !exit yourself!" end if ent:IsPlayer() then hook.Run("AowlTargetCommand", ply, "exit", ent, reason) ent:SendLua([[RunConsoleCommand("gamemenucommand","quitnoconfirm")]]) timer.Simple(0.09+(ent:Ping()*0.001), function() if not IsValid(ent) then return end ent:Kick("Exit: "..(reason and string.Left(reason, 128) or "Leaving")) end) return end return false, aowl.TargetNotFound(target) end, "players")
mit
liruqi/bigfoot
Interface/AddOns/DBM-Party-MoP/JadeSerpentTemple/LiuFlameheart.lua
1
2730
local mod = DBM:NewMod(658, "DBM-Party-MoP", 1, 313) local L = mod:GetLocalizedStrings() local sndWOP = mod:SoundMM("SoundWOP") mod:SetRevision(("$Revision: 9469 $"):sub(12, -3)) mod:SetCreatureID(56732) mod:SetZone() mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_CAST_SUCCESS", "SPELL_AURA_REMOVED", "SPELL_CAST_START", "SPELL_DAMAGE", "SPELL_MISSED", "SPELL_PERIODIC_DAMAGE", "SPELL_PERIODIC_MISSED", "UNIT_DIED" ) local warnDragonStrike = mod:NewSpellAnnounce(106823, 2) local warnPhase2 = mod:NewPhaseAnnounce(2) local warnJadeDragonStrike = mod:NewSpellAnnounce(106841, 3) local warnPhase3 = mod:NewPhaseAnnounce(3) local specWarnJadeDragonWave = mod:NewSpecialWarningMove(118540) local specWarnJadeFire = mod:NewSpecialWarningMove(107110) local timerDragonStrikeCD = mod:NewNextTimer(10.5, 106823) local timerJadeDragonStrikeCD = mod:NewNextTimer(10.5, 106841) local timerJadeFireCD = mod:NewNextTimer(3.5, 107045) function mod:OnCombatStart(delay) -- timerDragonStrikeCD:Start(-delay)--Unknown, tank pulled before i could start a log to get an accurate first timer. end function mod:SPELL_CAST_SUCCESS(args) if args.spellId == 106823 then--Phase 1 dragonstrike warnDragonStrike:Show() sndWOP:Play("firewall")--^^ timerDragonStrikeCD:Start() elseif args.spellId == 106841 then--phase 2 dragonstrike warnJadeDragonStrike:Show() sndWOP:Play("firewall")--^^ timerJadeDragonStrikeCD:Start() end end function mod:SPELL_AURA_REMOVED(args) if args.spellId == 106797 then--Jade Essence removed, (Phase 3 trigger) warnPhase3:Show() sndWOP:Play("pthree")--階段轉換 timerJadeDragonStrikeCD:Cancel() end end function mod:SPELL_CAST_START(args) if args.spellId == 106797 then--Jade Essence (Phase 2 trigger) warnPhase2:Show() sndWOP:Play("ptwo")--階段轉換 timerDragonStrikeCD:Cancel() elseif args.spellId == 107045 then timerJadeFireCD:Start() end end function mod:SPELL_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId) if spellId == 107110 and destGUID == UnitGUID("player") and self:AntiSpam() then specWarnJadeFire:Show() sndWOP:Play("runaway")--快躲開 end end mod.SPELL_MISSED = mod.SPELL_DAMAGE function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId) if spellId == 118540 and destGUID == UnitGUID("player") and self:AntiSpam() then specWarnJadeFire:Show() sndWOP:Play("runaway")--快躲開 end end mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 56762 then--Fight ends when Yu'lon dies. DBM:EndCombat(self) end end
mit
mario0582/devenserver
data/actions/scripts/quests/solaraxequest.lua
2
1375
function onUse(player, item, fromPosition, target, toPosition, isHotkey) if item.uid == 15901 then if player:getStorageValue(50089) == -1 then player:sendTextMessage(MESSAGE_INFO_DESCR, "You have found Solar Axe.") player:addItem(8925, 1) player:setStorageValue(50089, 1) else player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.") end elseif item.uid == 15902 then if player:getStorageValue(50091) == -1 then player:sendTextMessage(MESSAGE_INFO_DESCR, "You have found a The Devileye.") player:addItem(8852, 1) player:setStorageValue(50091, 1) else player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.") end elseif item.uid == 15903 then if player:getStorageValue(50092) == -1 then player:sendTextMessage(MESSAGE_INFO_DESCR, "You have found a Infernal bolt.") player:addItem(6529, 1) player:setStorageValue(50092, 1) else player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.") end elseif item.uid == 15904 then if player:getStorageValue(50093) == -1 then player:sendTextMessage(MESSAGE_INFO_DESCR, "You have found a spellscroll of prophecies.") player:addItem(8904, 1) player:setStorageValue(50093, 1) else player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.") end end return true end
gpl-2.0
thecodethinker/CyberEngine
include/luaJIT/jit/dis_ppc.lua
15
20319
---------------------------------------------------------------------------- -- LuaJIT PPC disassembler module. -- -- Copyright (C) 2005-2012 Mike Pall. All rights reserved. -- Released under the MIT/X license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles all common, non-privileged 32/64 bit PowerPC instructions -- plus the e500 SPE instructions and some Cell/Xenon extensions. -- -- NYI: VMX, VMX128 ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local concat = table.concat local bit = require("bit") local band, bor, tohex = bit.band, bit.bor, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Primary and extended opcode maps ------------------------------------------------------------------------------ local map_crops = { shift = 1, mask = 1023, [0] = "mcrfXX", [33] = "crnor|crnotCCC=", [129] = "crandcCCC", [193] = "crxor|crclrCCC%", [225] = "crnandCCC", [257] = "crandCCC", [289] = "creqv|crsetCCC%", [417] = "crorcCCC", [449] = "cror|crmoveCCC=", [16] = "b_lrKB", [528] = "b_ctrKB", [150] = "isync", } local map_rlwinm = setmetatable({ shift = 0, mask = -1, }, { __index = function(t, x) local rot = band(rshift(x, 11), 31) local mb = band(rshift(x, 6), 31) local me = band(rshift(x, 1), 31) if mb == 0 and me == 31-rot then return "slwiRR~A." elseif me == 31 and mb == 32-rot then return "srwiRR~-A." else return "rlwinmRR~AAA." end end }) local map_rld = { shift = 2, mask = 7, [0] = "rldiclRR~HM.", "rldicrRR~HM.", "rldicRR~HM.", "rldimiRR~HM.", { shift = 1, mask = 1, [0] = "rldclRR~RM.", "rldcrRR~RM.", }, } local map_ext = setmetatable({ shift = 1, mask = 1023, [0] = "cmp_YLRR", [32] = "cmpl_YLRR", [4] = "twARR", [68] = "tdARR", [8] = "subfcRRR.", [40] = "subfRRR.", [104] = "negRR.", [136] = "subfeRRR.", [200] = "subfzeRR.", [232] = "subfmeRR.", [520] = "subfcoRRR.", [552] = "subfoRRR.", [616] = "negoRR.", [648] = "subfeoRRR.", [712] = "subfzeoRR.", [744] = "subfmeoRR.", [9] = "mulhduRRR.", [73] = "mulhdRRR.", [233] = "mulldRRR.", [457] = "divduRRR.", [489] = "divdRRR.", [745] = "mulldoRRR.", [969] = "divduoRRR.", [1001] = "divdoRRR.", [10] = "addcRRR.", [138] = "addeRRR.", [202] = "addzeRR.", [234] = "addmeRR.", [266] = "addRRR.", [522] = "addcoRRR.", [650] = "addeoRRR.", [714] = "addzeoRR.", [746] = "addmeoRR.", [778] = "addoRRR.", [11] = "mulhwuRRR.", [75] = "mulhwRRR.", [235] = "mullwRRR.", [459] = "divwuRRR.", [491] = "divwRRR.", [747] = "mullwoRRR.", [971] = "divwouRRR.", [1003] = "divwoRRR.", [15] = "iselltRRR", [47] = "iselgtRRR", [79] = "iseleqRRR", [144] = { shift = 20, mask = 1, [0] = "mtcrfRZ~", "mtocrfRZ~", }, [19] = { shift = 20, mask = 1, [0] = "mfcrR", "mfocrfRZ", }, [371] = { shift = 11, mask = 1023, [392] = "mftbR", [424] = "mftbuR", }, [339] = { shift = 11, mask = 1023, [32] = "mferR", [256] = "mflrR", [288] = "mfctrR", [16] = "mfspefscrR", }, [467] = { shift = 11, mask = 1023, [32] = "mtxerR", [256] = "mtlrR", [288] = "mtctrR", [16] = "mtspefscrR", }, [20] = "lwarxRR0R", [84] = "ldarxRR0R", [21] = "ldxRR0R", [53] = "lduxRRR", [149] = "stdxRR0R", [181] = "stduxRRR", [341] = "lwaxRR0R", [373] = "lwauxRRR", [23] = "lwzxRR0R", [55] = "lwzuxRRR", [87] = "lbzxRR0R", [119] = "lbzuxRRR", [151] = "stwxRR0R", [183] = "stwuxRRR", [215] = "stbxRR0R", [247] = "stbuxRRR", [279] = "lhzxRR0R", [311] = "lhzuxRRR", [343] = "lhaxRR0R", [375] = "lhauxRRR", [407] = "sthxRR0R", [439] = "sthuxRRR", [54] = "dcbst-R0R", [86] = "dcbf-R0R", [150] = "stwcxRR0R.", [214] = "stdcxRR0R.", [246] = "dcbtst-R0R", [278] = "dcbt-R0R", [310] = "eciwxRR0R", [438] = "ecowxRR0R", [470] = "dcbi-RR", [598] = { shift = 21, mask = 3, [0] = "sync", "lwsync", "ptesync", }, [758] = "dcba-RR", [854] = "eieio", [982] = "icbi-R0R", [1014] = "dcbz-R0R", [26] = "cntlzwRR~", [58] = "cntlzdRR~", [122] = "popcntbRR~", [154] = "prtywRR~", [186] = "prtydRR~", [28] = "andRR~R.", [60] = "andcRR~R.", [124] = "nor|notRR~R=.", [284] = "eqvRR~R.", [316] = "xorRR~R.", [412] = "orcRR~R.", [444] = "or|mrRR~R=.", [476] = "nandRR~R.", [508] = "cmpbRR~R", [512] = "mcrxrX", [532] = "ldbrxRR0R", [660] = "stdbrxRR0R", [533] = "lswxRR0R", [597] = "lswiRR0A", [661] = "stswxRR0R", [725] = "stswiRR0A", [534] = "lwbrxRR0R", [662] = "stwbrxRR0R", [790] = "lhbrxRR0R", [918] = "sthbrxRR0R", [535] = "lfsxFR0R", [567] = "lfsuxFRR", [599] = "lfdxFR0R", [631] = "lfduxFRR", [663] = "stfsxFR0R", [695] = "stfsuxFRR", [727] = "stfdxFR0R", [759] = "stfduxFR0R", [855] = "lfiwaxFR0R", [983] = "stfiwxFR0R", [24] = "slwRR~R.", [27] = "sldRR~R.", [536] = "srwRR~R.", [792] = "srawRR~R.", [824] = "srawiRR~A.", [794] = "sradRR~R.", [826] = "sradiRR~H.", [827] = "sradiRR~H.", [922] = "extshRR~.", [954] = "extsbRR~.", [986] = "extswRR~.", [539] = "srdRR~R.", }, { __index = function(t, x) if band(x, 31) == 15 then return "iselRRRC" end end }) local map_ld = { shift = 0, mask = 3, [0] = "ldRRE", "lduRRE", "lwaRRE", } local map_std = { shift = 0, mask = 3, [0] = "stdRRE", "stduRRE", } local map_fps = { shift = 5, mask = 1, { shift = 1, mask = 15, [0] = false, false, "fdivsFFF.", false, "fsubsFFF.", "faddsFFF.", "fsqrtsF-F.", false, "fresF-F.", "fmulsFF-F.", "frsqrtesF-F.", false, "fmsubsFFFF~.", "fmaddsFFFF~.", "fnmsubsFFFF~.", "fnmaddsFFFF~.", } } local map_fpd = { shift = 5, mask = 1, [0] = { shift = 1, mask = 1023, [0] = "fcmpuXFF", [32] = "fcmpoXFF", [64] = "mcrfsXX", [38] = "mtfsb1A.", [70] = "mtfsb0A.", [134] = "mtfsfiA>>-A>", [8] = "fcpsgnFFF.", [40] = "fnegF-F.", [72] = "fmrF-F.", [136] = "fnabsF-F.", [264] = "fabsF-F.", [12] = "frspF-F.", [14] = "fctiwF-F.", [15] = "fctiwzF-F.", [583] = "mffsF.", [711] = "mtfsfZF.", [392] = "frinF-F.", [424] = "frizF-F.", [456] = "fripF-F.", [488] = "frimF-F.", [814] = "fctidF-F.", [815] = "fctidzF-F.", [846] = "fcfidF-F.", }, { shift = 1, mask = 15, [0] = false, false, "fdivFFF.", false, "fsubFFF.", "faddFFF.", "fsqrtF-F.", "fselFFFF~.", "freF-F.", "fmulFF-F.", "frsqrteF-F.", false, "fmsubFFFF~.", "fmaddFFFF~.", "fnmsubFFFF~.", "fnmaddFFFF~.", } } local map_spe = { shift = 0, mask = 2047, [512] = "evaddwRRR", [514] = "evaddiwRAR~", [516] = "evsubwRRR~", [518] = "evsubiwRAR~", [520] = "evabsRR", [521] = "evnegRR", [522] = "evextsbRR", [523] = "evextshRR", [524] = "evrndwRR", [525] = "evcntlzwRR", [526] = "evcntlswRR", [527] = "brincRRR", [529] = "evandRRR", [530] = "evandcRRR", [534] = "evxorRRR", [535] = "evor|evmrRRR=", [536] = "evnor|evnotRRR=", [537] = "eveqvRRR", [539] = "evorcRRR", [542] = "evnandRRR", [544] = "evsrwuRRR", [545] = "evsrwsRRR", [546] = "evsrwiuRRA", [547] = "evsrwisRRA", [548] = "evslwRRR", [550] = "evslwiRRA", [552] = "evrlwRRR", [553] = "evsplatiRS", [554] = "evrlwiRRA", [555] = "evsplatfiRS", [556] = "evmergehiRRR", [557] = "evmergeloRRR", [558] = "evmergehiloRRR", [559] = "evmergelohiRRR", [560] = "evcmpgtuYRR", [561] = "evcmpgtsYRR", [562] = "evcmpltuYRR", [563] = "evcmpltsYRR", [564] = "evcmpeqYRR", [632] = "evselRRR", [633] = "evselRRRW", [634] = "evselRRRW", [635] = "evselRRRW", [636] = "evselRRRW", [637] = "evselRRRW", [638] = "evselRRRW", [639] = "evselRRRW", [640] = "evfsaddRRR", [641] = "evfssubRRR", [644] = "evfsabsRR", [645] = "evfsnabsRR", [646] = "evfsnegRR", [648] = "evfsmulRRR", [649] = "evfsdivRRR", [652] = "evfscmpgtYRR", [653] = "evfscmpltYRR", [654] = "evfscmpeqYRR", [656] = "evfscfuiR-R", [657] = "evfscfsiR-R", [658] = "evfscfufR-R", [659] = "evfscfsfR-R", [660] = "evfsctuiR-R", [661] = "evfsctsiR-R", [662] = "evfsctufR-R", [663] = "evfsctsfR-R", [664] = "evfsctuizR-R", [666] = "evfsctsizR-R", [668] = "evfststgtYRR", [669] = "evfststltYRR", [670] = "evfststeqYRR", [704] = "efsaddRRR", [705] = "efssubRRR", [708] = "efsabsRR", [709] = "efsnabsRR", [710] = "efsnegRR", [712] = "efsmulRRR", [713] = "efsdivRRR", [716] = "efscmpgtYRR", [717] = "efscmpltYRR", [718] = "efscmpeqYRR", [719] = "efscfdR-R", [720] = "efscfuiR-R", [721] = "efscfsiR-R", [722] = "efscfufR-R", [723] = "efscfsfR-R", [724] = "efsctuiR-R", [725] = "efsctsiR-R", [726] = "efsctufR-R", [727] = "efsctsfR-R", [728] = "efsctuizR-R", [730] = "efsctsizR-R", [732] = "efststgtYRR", [733] = "efststltYRR", [734] = "efststeqYRR", [736] = "efdaddRRR", [737] = "efdsubRRR", [738] = "efdcfuidR-R", [739] = "efdcfsidR-R", [740] = "efdabsRR", [741] = "efdnabsRR", [742] = "efdnegRR", [744] = "efdmulRRR", [745] = "efddivRRR", [746] = "efdctuidzR-R", [747] = "efdctsidzR-R", [748] = "efdcmpgtYRR", [749] = "efdcmpltYRR", [750] = "efdcmpeqYRR", [751] = "efdcfsR-R", [752] = "efdcfuiR-R", [753] = "efdcfsiR-R", [754] = "efdcfufR-R", [755] = "efdcfsfR-R", [756] = "efdctuiR-R", [757] = "efdctsiR-R", [758] = "efdctufR-R", [759] = "efdctsfR-R", [760] = "efdctuizR-R", [762] = "efdctsizR-R", [764] = "efdtstgtYRR", [765] = "efdtstltYRR", [766] = "efdtsteqYRR", [768] = "evlddxRR0R", [769] = "evlddRR8", [770] = "evldwxRR0R", [771] = "evldwRR8", [772] = "evldhxRR0R", [773] = "evldhRR8", [776] = "evlhhesplatxRR0R", [777] = "evlhhesplatRR2", [780] = "evlhhousplatxRR0R", [781] = "evlhhousplatRR2", [782] = "evlhhossplatxRR0R", [783] = "evlhhossplatRR2", [784] = "evlwhexRR0R", [785] = "evlwheRR4", [788] = "evlwhouxRR0R", [789] = "evlwhouRR4", [790] = "evlwhosxRR0R", [791] = "evlwhosRR4", [792] = "evlwwsplatxRR0R", [793] = "evlwwsplatRR4", [796] = "evlwhsplatxRR0R", [797] = "evlwhsplatRR4", [800] = "evstddxRR0R", [801] = "evstddRR8", [802] = "evstdwxRR0R", [803] = "evstdwRR8", [804] = "evstdhxRR0R", [805] = "evstdhRR8", [816] = "evstwhexRR0R", [817] = "evstwheRR4", [820] = "evstwhoxRR0R", [821] = "evstwhoRR4", [824] = "evstwwexRR0R", [825] = "evstwweRR4", [828] = "evstwwoxRR0R", [829] = "evstwwoRR4", [1027] = "evmhessfRRR", [1031] = "evmhossfRRR", [1032] = "evmheumiRRR", [1033] = "evmhesmiRRR", [1035] = "evmhesmfRRR", [1036] = "evmhoumiRRR", [1037] = "evmhosmiRRR", [1039] = "evmhosmfRRR", [1059] = "evmhessfaRRR", [1063] = "evmhossfaRRR", [1064] = "evmheumiaRRR", [1065] = "evmhesmiaRRR", [1067] = "evmhesmfaRRR", [1068] = "evmhoumiaRRR", [1069] = "evmhosmiaRRR", [1071] = "evmhosmfaRRR", [1095] = "evmwhssfRRR", [1096] = "evmwlumiRRR", [1100] = "evmwhumiRRR", [1101] = "evmwhsmiRRR", [1103] = "evmwhsmfRRR", [1107] = "evmwssfRRR", [1112] = "evmwumiRRR", [1113] = "evmwsmiRRR", [1115] = "evmwsmfRRR", [1127] = "evmwhssfaRRR", [1128] = "evmwlumiaRRR", [1132] = "evmwhumiaRRR", [1133] = "evmwhsmiaRRR", [1135] = "evmwhsmfaRRR", [1139] = "evmwssfaRRR", [1144] = "evmwumiaRRR", [1145] = "evmwsmiaRRR", [1147] = "evmwsmfaRRR", [1216] = "evaddusiaawRR", [1217] = "evaddssiaawRR", [1218] = "evsubfusiaawRR", [1219] = "evsubfssiaawRR", [1220] = "evmraRR", [1222] = "evdivwsRRR", [1223] = "evdivwuRRR", [1224] = "evaddumiaawRR", [1225] = "evaddsmiaawRR", [1226] = "evsubfumiaawRR", [1227] = "evsubfsmiaawRR", [1280] = "evmheusiaawRRR", [1281] = "evmhessiaawRRR", [1283] = "evmhessfaawRRR", [1284] = "evmhousiaawRRR", [1285] = "evmhossiaawRRR", [1287] = "evmhossfaawRRR", [1288] = "evmheumiaawRRR", [1289] = "evmhesmiaawRRR", [1291] = "evmhesmfaawRRR", [1292] = "evmhoumiaawRRR", [1293] = "evmhosmiaawRRR", [1295] = "evmhosmfaawRRR", [1320] = "evmhegumiaaRRR", [1321] = "evmhegsmiaaRRR", [1323] = "evmhegsmfaaRRR", [1324] = "evmhogumiaaRRR", [1325] = "evmhogsmiaaRRR", [1327] = "evmhogsmfaaRRR", [1344] = "evmwlusiaawRRR", [1345] = "evmwlssiaawRRR", [1352] = "evmwlumiaawRRR", [1353] = "evmwlsmiaawRRR", [1363] = "evmwssfaaRRR", [1368] = "evmwumiaaRRR", [1369] = "evmwsmiaaRRR", [1371] = "evmwsmfaaRRR", [1408] = "evmheusianwRRR", [1409] = "evmhessianwRRR", [1411] = "evmhessfanwRRR", [1412] = "evmhousianwRRR", [1413] = "evmhossianwRRR", [1415] = "evmhossfanwRRR", [1416] = "evmheumianwRRR", [1417] = "evmhesmianwRRR", [1419] = "evmhesmfanwRRR", [1420] = "evmhoumianwRRR", [1421] = "evmhosmianwRRR", [1423] = "evmhosmfanwRRR", [1448] = "evmhegumianRRR", [1449] = "evmhegsmianRRR", [1451] = "evmhegsmfanRRR", [1452] = "evmhogumianRRR", [1453] = "evmhogsmianRRR", [1455] = "evmhogsmfanRRR", [1472] = "evmwlusianwRRR", [1473] = "evmwlssianwRRR", [1480] = "evmwlumianwRRR", [1481] = "evmwlsmianwRRR", [1491] = "evmwssfanRRR", [1496] = "evmwumianRRR", [1497] = "evmwsmianRRR", [1499] = "evmwsmfanRRR", } local map_pri = { [0] = false, false, "tdiARI", "twiARI", map_spe, false, false, "mulliRRI", "subficRRI", false, "cmpl_iYLRU", "cmp_iYLRI", "addicRRI", "addic.RRI", "addi|liRR0I", "addis|lisRR0I", "b_KBJ", "sc", "bKJ", map_crops, "rlwimiRR~AAA.", map_rlwinm, false, "rlwnmRR~RAA.", "oriNRR~U", "orisRR~U", "xoriRR~U", "xorisRR~U", "andi.RR~U", "andis.RR~U", map_rld, map_ext, "lwzRRD", "lwzuRRD", "lbzRRD", "lbzuRRD", "stwRRD", "stwuRRD", "stbRRD", "stbuRRD", "lhzRRD", "lhzuRRD", "lhaRRD", "lhauRRD", "sthRRD", "sthuRRD", "lmwRRD", "stmwRRD", "lfsFRD", "lfsuFRD", "lfdFRD", "lfduFRD", "stfsFRD", "stfsuFRD", "stfdFRD", "stfduFRD", false, false, map_ld, map_fps, false, false, map_std, map_fpd, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31", } local map_cond = { [0] = "lt", "gt", "eq", "so", "ge", "le", "ne", "ns", } -- Format a condition bit. local function condfmt(cond) if cond <= 3 then return map_cond[band(cond, 3)] else return format("4*cr%d+%s", rshift(cond, 2), map_cond[band(cond, 3)]) end end ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-7s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-7s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end -- Disassemble a single instruction. local function disass_ins(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) local op = bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3) local operands = {} local last = nil local rs = 21 ctx.op = op ctx.rel = nil local opat = map_pri[rshift(b0, 2)] while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] end local name, pat = match(opat, "^([a-z0-9_.]*)(.*)") local altname, pat2 = match(pat, "|([a-z0-9_.]*)(.*)") if altname then pat = pat2 end for p in gmatch(pat, ".") do local x = nil if p == "R" then x = map_gpr[band(rshift(op, rs), 31)] rs = rs - 5 elseif p == "F" then x = "f"..band(rshift(op, rs), 31) rs = rs - 5 elseif p == "A" then x = band(rshift(op, rs), 31) rs = rs - 5 elseif p == "S" then x = arshift(lshift(op, 27-rs), 27) rs = rs - 5 elseif p == "I" then x = arshift(lshift(op, 16), 16) elseif p == "U" then x = band(op, 0xffff) elseif p == "D" or p == "E" then local disp = arshift(lshift(op, 16), 16) if p == "E" then disp = band(disp, -4) end if last == "r0" then last = "0" end operands[#operands] = format("%d(%s)", disp, last) elseif p >= "2" and p <= "8" then local disp = band(rshift(op, rs), 31) * p if last == "r0" then last = "0" end operands[#operands] = format("%d(%s)", disp, last) elseif p == "H" then x = band(rshift(op, rs), 31) + lshift(band(op, 2), 4) rs = rs - 5 elseif p == "M" then x = band(rshift(op, rs), 31) + band(op, 0x20) elseif p == "C" then x = condfmt(band(rshift(op, rs), 31)) rs = rs - 5 elseif p == "B" then local bo = rshift(op, 21) local cond = band(rshift(op, 16), 31) local cn = "" rs = rs - 10 if band(bo, 4) == 0 then cn = band(bo, 2) == 0 and "dnz" or "dz" if band(bo, 0x10) == 0 then cn = cn..(band(bo, 8) == 0 and "f" or "t") end if band(bo, 0x10) == 0 then x = condfmt(cond) end name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+") elseif band(bo, 0x10) == 0 then cn = map_cond[band(cond, 3) + (band(bo, 8) == 0 and 4 or 0)] if cond > 3 then x = "cr"..rshift(cond, 2) end name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+") end name = gsub(name, "_", cn) elseif p == "J" then x = arshift(lshift(op, 27-rs), 29-rs)*4 if band(op, 2) == 0 then x = ctx.addr + pos + x end ctx.rel = x x = "0x"..tohex(x) elseif p == "K" then if band(op, 1) ~= 0 then name = name.."l" end if band(op, 2) ~= 0 then name = name.."a" end elseif p == "X" or p == "Y" then x = band(rshift(op, rs+2), 7) if x == 0 and p == "Y" then x = nil else x = "cr"..x end rs = rs - 5 elseif p == "W" then x = "cr"..band(op, 7) elseif p == "Z" then x = band(rshift(op, rs-4), 255) rs = rs - 10 elseif p == ">" then operands[#operands] = rshift(operands[#operands], 1) elseif p == "0" then if last == "r0" then operands[#operands] = nil if altname then name = altname end end elseif p == "L" then name = gsub(name, "_", band(op, 0x00200000) ~= 0 and "d" or "w") elseif p == "." then if band(op, 1) == 1 then name = name.."." end elseif p == "N" then if op == 0x60000000 then name = "nop"; break end elseif p == "~" then local n = #operands operands[n-1], operands[n] = operands[n], operands[n-1] elseif p == "=" then local n = #operands if last == operands[n-1] then operands[n] = nil name = altname end elseif p == "%" then local n = #operands if last == operands[n-1] and last == operands[n-2] then operands[n] = nil operands[n-1] = nil name = altname end elseif p == "-" then rs = rs - 5 else assert(false) end if x then operands[#operands+1] = x; last = x end end return putop(ctx, name, operands) 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 stop = stop - stop % 4 ctx.pos = ofs - ofs % 4 ctx.rel = nil while ctx.pos < stop do disass_ins(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 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 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 -- Return register name for RID. local function regname_(r) if r < 32 then return map_gpr[r] end return "f"..(r-32) end -- Public module functions. module(...) create = create_ disass = disass_ regname = regname_
mit
liruqi/bigfoot
Interface/AddOns/BigFoot/AceLibs/Ace3/AceGUI-3.0/widgets/AceGUIWidget-EditBox.lua
1
7538
--[[----------------------------------------------------------------------------- EditBox Widget -------------------------------------------------------------------------------]] local Type, Version = "EditBox", 27 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local tostring, pairs = tostring, pairs -- WoW APIs local PlaySound = PlaySound local GetCursorInfo, ClearCursor, GetSpellInfo = GetCursorInfo, ClearCursor, GetSpellInfo local CreateFrame, UIParent = CreateFrame, UIParent local _G = _G -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: AceGUIEditBoxInsertLink, ChatFontNormal, OKAY --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] if not AceGUIEditBoxInsertLink then -- upgradeable hook hooksecurefunc("ChatEdit_InsertLink", function(...) return _G.AceGUIEditBoxInsertLink(...) end) end function _G.AceGUIEditBoxInsertLink(text) for i = 1, AceGUI:GetWidgetCount(Type) do local editbox = _G["AceGUI-3.0EditBox"..i] if editbox and editbox:IsVisible() and editbox:HasFocus() then editbox:Insert(text) return true end end end local function ShowButton(self) if not self.disablebutton then self.button:Show() self.editbox:SetTextInsets(0, 20, 3, 3) end end local function HideButton(self) self.button:Hide() self.editbox:SetTextInsets(0, 0, 3, 3) end --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Frame_OnShowFocus(frame) frame.obj.editbox:SetFocus() frame:SetScript("OnShow", nil) end local function EditBox_OnEscapePressed(frame) AceGUI:ClearFocus() end local function EditBox_OnEnterPressed(frame) local self = frame.obj local value = frame:GetText() local cancel = self:Fire("OnEnterPressed", value) if not cancel then PlaySound(856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON HideButton(self) end end local function EditBox_OnReceiveDrag(frame) local self = frame.obj local type, id, info = GetCursorInfo() if type == "item" then self:SetText(info) self:Fire("OnEnterPressed", info) ClearCursor() elseif type == "spell" then local name = GetSpellInfo(id, info) self:SetText(name) self:Fire("OnEnterPressed", name) ClearCursor() elseif type == "macro" then local name = GetMacroInfo(id) self:SetText(name) self:Fire("OnEnterPressed", name) ClearCursor() end HideButton(self) AceGUI:ClearFocus() end local function EditBox_OnTextChanged(frame) local self = frame.obj local value = frame:GetText() if tostring(value) ~= tostring(self.lasttext) then self:Fire("OnTextChanged", value) self.lasttext = value ShowButton(self) end end local function EditBox_OnFocusGained(frame) AceGUI:SetFocus(frame.obj) end local function Button_OnClick(frame) local editbox = frame.obj.editbox editbox:ClearFocus() EditBox_OnEnterPressed(editbox) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) -- height is controlled by SetLabel self:SetWidth(200) self:SetDisabled(false) self:SetLabel() self:SetText() self:DisableButton(false) self:SetMaxLetters(0) end, ["OnRelease"] = function(self) self:ClearFocus() end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.editbox:EnableMouse(false) self.editbox:ClearFocus() self.editbox:SetTextColor(0.5,0.5,0.5) self.label:SetTextColor(0.5,0.5,0.5) else self.editbox:EnableMouse(true) self.editbox:SetTextColor(1,1,1) self.label:SetTextColor(1,.82,0) end end, ["SetText"] = function(self, text) self.lasttext = text or "" self.editbox:SetText(text or "") self.editbox:SetCursorPosition(0) HideButton(self) end, ["GetText"] = function(self, text) return self.editbox:GetText() end, ["SetLabel"] = function(self, text) if text and text ~= "" then self.label:SetText(text) self.label:Show() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,-18) self:SetHeight(44) self.alignoffset = 30 else self.label:SetText("") self.label:Hide() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,0) self:SetHeight(26) self.alignoffset = 12 end end, ["DisableButton"] = function(self, disabled) self.disablebutton = disabled if disabled then HideButton(self) end end, ["SetMaxLetters"] = function (self, num) self.editbox:SetMaxLetters(num or 0) end, ["ClearFocus"] = function(self) self.editbox:ClearFocus() self.frame:SetScript("OnShow", nil) end, ["SetFocus"] = function(self) self.editbox:SetFocus() if not self.frame:IsShown() then self.frame:SetScript("OnShow", Frame_OnShowFocus) end end, ["HighlightText"] = function(self, from, to) self.editbox:HighlightText(from, to) end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local num = AceGUI:GetNextWidgetNum(Type) local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local editbox = CreateFrame("EditBox", "AceGUI-3.0EditBox"..num, frame, "InputBoxTemplate") editbox:SetAutoFocus(false) editbox:SetFontObject(ChatFontNormal) editbox:SetScript("OnEnter", Control_OnEnter) editbox:SetScript("OnLeave", Control_OnLeave) editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed) editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed) editbox:SetScript("OnTextChanged", EditBox_OnTextChanged) editbox:SetScript("OnReceiveDrag", EditBox_OnReceiveDrag) editbox:SetScript("OnMouseDown", EditBox_OnReceiveDrag) editbox:SetScript("OnEditFocusGained", EditBox_OnFocusGained) editbox:SetTextInsets(0, 0, 3, 3) editbox:SetMaxLetters(256) editbox:SetPoint("BOTTOMLEFT", 6, 0) editbox:SetPoint("BOTTOMRIGHT") editbox:SetHeight(19) local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") label:SetPoint("TOPLEFT", 0, -2) label:SetPoint("TOPRIGHT", 0, -2) label:SetJustifyH("LEFT") label:SetHeight(18) local button = CreateFrame("Button", nil, editbox, "UIPanelButtonTemplate") button:SetWidth(40) button:SetHeight(20) button:SetPoint("RIGHT", -2, 0) button:SetText(OKAY) button:SetScript("OnClick", Button_OnClick) button:Hide() local widget = { alignoffset = 30, editbox = editbox, label = label, button = button, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end editbox.obj, button.obj = widget, widget return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
MaliceTurtle/gamecode4
Extra/UtilityDemo/PreInit.lua
44
2196
-- PreInit.lua -- Note: This file only defines the class() function from assets\scripts\PreInit.lua. The other stuff isn't needed -- for this simple demo. ----------------------------------------------------------------------------------------------------------------------- -- Classes & Inheritance ----------------------------------------------------------------------------------------------------------------------- function class(baseClass, body) local ret = body or {}; -- if there's a base class, attach our new class to it if (baseClass ~= nil) then setmetatable(ret, ret); ret.__index = baseClass; ret.base = baseClass; end -- Add the Create() function. This will end up being added to each subclass which isn't ideal. This -- function should probably be stored in a single place so we only have to create it once. -- -self: The self pointer that's calling this function. -- -constructionData: The table sent in as construction data. Think of it like a constructor. -- -originalSubClass: Used for recursion. Don't pass anything into this parameter, it's filled -- automatically. It's used in case the C++ side needs access to the leaf -- subclass that is being instantiated. For an example, see ScriptProcess -- in C++. ret.Create = function(self, constructionData, originalSubClass) local obj; if (self.__index ~= nil) then if (originalSubClass ~= nil) then obj = self.__index:Create(constructionData, originalSubClass); else obj = self.__index:Create(constructionData, self); end else obj = constructionData or {}; end setmetatable(obj, obj); obj.__index = self; -- copy any operators over if (self.__operators ~= nil) then for key, val in pairs(self.__operators) do obj[key] = val; end end return obj; end -- Returns true if otherClass appears in this objects class hierarchy anywhere. ret.IsInstance = function(self, otherClass) local cls = self.__index; while cls do if cls == otherClass then return true end cls = cls.base end return false end return ret; end
lgpl-3.0
shiprabehera/kong
spec/02-integration/05-proxy/12-server_tokens_spec.lua
4
7331
local helpers = require "spec.helpers" local constants = require "kong.constants" local default_server_header = _KONG._NAME .. "/" .. _KONG._VERSION local function start(config) return function() helpers.dao.apis:insert { name = "api-1", upstream_url = "http://localhost:9999/headers-inspect", hosts = { "headers-inspect.com", } } config = config or {} config.nginx_conf = "spec/fixtures/custom_nginx.template" assert(helpers.start_kong(config)) end end describe("Server Tokens", function() local client before_each(function() client = helpers.proxy_client() end) after_each(function() if client then client:close() end end) describe("(with default configration values)", function() setup(start { nginx_conf = "spec/fixtures/custom_nginx.template", }) teardown(helpers.stop_kong) it("should return Kong 'Via' header but not change the 'Server' header when request was proxied", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "headers-inspect.com", } }) assert.res_status(200, res) assert.not_equal(default_server_header, res.headers["server"]) assert.equal(default_server_header, res.headers["via"]) end) it("should return Kong 'Server' header but not the Kong 'Via' header when no API matched (no proxy)", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "404.com", } }) assert.res_status(404, res) assert.equal(default_server_header, res.headers["server"]) assert.is_nil(res.headers["via"]) end) end) describe("(with server_tokens = on)", function() setup(start { nginx_conf = "spec/fixtures/custom_nginx.template", server_tokens = "on", }) teardown(helpers.stop_kong) it("should return Kong 'Via' header but not change the 'Server' header when request was proxied", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "headers-inspect.com", } }) assert.res_status(200, res) assert.not_equal(default_server_header, res.headers["server"]) assert.equal(default_server_header, res.headers["via"]) end) it("should return Kong 'Server' header but not the Kong 'Via' header when no API matched (no proxy)", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "404.com", } }) assert.res_status(404, res) assert.equal(default_server_header, res.headers["server"]) assert.is_nil(res.headers["via"]) end) end) describe("(with server_tokens = off)", function() setup(start { nginx_conf = "spec/fixtures/custom_nginx.template", server_tokens = "off", }) teardown(helpers.stop_kong) it("should not return Kong 'Via' header but it should forward the 'Server' header when request was proxied", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "headers-inspect.com", } }) assert.res_status(200, res) assert.response(res).has.header "server" assert.response(res).has_not.header "via" assert.not_equal(default_server_header, res.headers["server"]) end) it("should not return Kong 'Server' or 'Via' headers when no API matched (no proxy)", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "404.com", } }) assert.res_status(404, res) assert.is_nil(res.headers["server"]) assert.is_nil(res.headers["via"]) end) end) end) describe("Latency Tokens", function() local client before_each(function() client = helpers.proxy_client() end) after_each(function() if client then client:close() end end) describe("(with default configration values)", function() setup(start { nginx_conf = "spec/fixtures/custom_nginx.template", }) teardown(helpers.stop_kong) it("should be returned when request was proxied", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "headers-inspect.com", } }) assert.res_status(200, res) assert.is_not_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY]) assert.is_not_nil(res.headers[constants.HEADERS.PROXY_LATENCY]) end) it("should not be returned when no API matched (no proxy)", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "404.com", } }) assert.res_status(404, res) assert.is_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY]) assert.is_nil(res.headers[constants.HEADERS.PROXY_LATENCY]) end) end) describe("(with latency_tokens = on)", function() setup(start { nginx_conf = "spec/fixtures/custom_nginx.template", latency_tokens = "on", }) teardown(helpers.stop_kong) it("should be returned when request was proxied", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "headers-inspect.com" } }) assert.res_status(200, res) assert.is_not_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY]) assert.is_not_nil(res.headers[constants.HEADERS.PROXY_LATENCY]) end) it("should not be returned when no API matched (no proxy)", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "404.com", } }) assert.res_status(404, res) assert.is_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY]) assert.is_nil(res.headers[constants.HEADERS.PROXY_LATENCY]) end) end) describe("(with latency_tokens = off)", function() setup(start { nginx_conf = "spec/fixtures/custom_nginx.template", latency_tokens = "off", }) teardown(function() helpers.stop_kong() end) it("should not be returned when request was proxied", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "headers-inspect.com", } }) assert.res_status(200, res) assert.is_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY]) assert.is_nil(res.headers[constants.HEADERS.PROXY_LATENCY]) end) it("should not be returned when no API matched (no proxy)", function() local res = assert(client:send { method = "GET", path = "/get", headers = { host = "404.com", } }) assert.res_status(404, res) assert.is_nil(res.headers[constants.HEADERS.UPSTREAM_LATENCY]) assert.is_nil(res.headers[constants.HEADERS.PROXY_LATENCY]) end) end) end)
apache-2.0
Datamats/ServerContent
notagain/lua/notagain/essential/autorun/player_grab.lua
1
2808
local tag = "player_grab" do -- meta local PLAYER = FindMetaTable("Player") function PLAYER:IsBeingPhysgunned() local pl = self._is_being_physgunned if pl then if isentity(pl) and not IsValid(pl) then return false end return true end end function PLAYER:SetPhysgunImmune(bool) self._physgun_immune = bool end function PLAYER:IsPhysgunImmune() return self._physgun_immune == true end end if CLIENT then CreateClientConVar(tag .. "_dont_touch_me", "0", true, true) end hook.Add("PhysgunPickup", tag, function(ply, ent) local canphysgun = ent:IsPlayer() and not ent:IsPhysgunImmune() and not ent:IsBeingPhysgunned() if not canphysgun then return end if ent.IsFriend then canphysgun = ent:IsFriend(ply) and ent:GetInfoNum(tag .. "_dont_touch_me", 0) == 0 and ply:GetInfoNum(tag .. "_dont_touch_me", 0) == 0 else canphysgun = ply:IsAdmin() end canphysgun = canphysgun or ent:IsBot() canphysgun = canphysgun or ( ent.IsBanned and ent:IsBanned()) if not canphysgun then return end if IsValid(ent._is_being_physgunned) then if ent._is_being_physgunned~=ply then return end end ent._is_being_physgunned = ply ent:SetMoveType(MOVETYPE_NONE) ent:SetOwner(ply) return true end) hook.Add("PhysgunDrop", tag, function(ply, ent) if ent:IsPlayer() and ent._is_being_physgunned==ply then ent._pos_velocity = {} ent._is_being_physgunned = false ent:SetMoveType(ply:KeyDown(IN_ATTACK2) and ply:CheckUserGroupLevel("moderators") and MOVETYPE_NOCLIP or MOVETYPE_WALK) ent:SetOwner() return true end end) -- attempt to stop suicides during physgun hook.Add("CanPlayerSuicide", tag, function(ply) if ply:IsBeingPhysgunned() then return false end end) hook.Add("PlayerDeath", tag, function(ply) if ply:IsBeingPhysgunned() then return false end end) hook.Add("PlayerNoClip", tag, function(ply) if ply:IsBeingPhysgunned() then return false end end) do -- throw local function GetAverage(tbl) if #tbl == 1 then return tbl[1] end local average = vector_origin for key, vec in pairs(tbl) do average = average + vec end return average / #tbl end local function CalcVelocity(self, pos) self._pos_velocity = self._pos_velocity or {} if #self._pos_velocity > 10 then table.remove(self._pos_velocity, 1) end table.insert(self._pos_velocity, pos) return GetAverage(self._pos_velocity) end hook.Add("Move", tag, function(ply, data) if ply:IsBeingPhysgunned() then local vel = CalcVelocity(ply, data:GetOrigin()) if vel:Length() > 10 then data:SetVelocity((data:GetOrigin() - vel) * 8) end local owner = ply:GetOwner() if owner:IsPlayer() then if owner:KeyDown(IN_USE) then local ang = ply:GetAngles() ply:SetEyeAngles(Angle(ang.p, ang.y, 0)) end end end end) end
mit
shiprabehera/kong
kong/plugins/file-log/handler.lua
1
2232
-- Copyright (C) Mashape, Inc. local ffi = require "ffi" local cjson = require "cjson" local system_constants = require "lua_system_constants" local basic_serializer = require "kong.plugins.log-serializers.basic" local BasePlugin = require "kong.plugins.base_plugin" local ngx_timer = ngx.timer.at local O_CREAT = system_constants.O_CREAT() local O_WRONLY = system_constants.O_WRONLY() local O_APPEND = system_constants.O_APPEND() local S_IRUSR = system_constants.S_IRUSR() local S_IWUSR = system_constants.S_IWUSR() local S_IRGRP = system_constants.S_IRGRP() local S_IROTH = system_constants.S_IROTH() local oflags = bit.bor(O_WRONLY, O_CREAT, O_APPEND) local mode = bit.bor(S_IRUSR, S_IWUSR, S_IRGRP, S_IROTH) ffi.cdef[[ int write(int fd, const void * ptr, int numbytes); ]] -- fd tracking utility functions local file_descriptors = {} -- Log to a file. Function used as callback from an nginx timer. -- @param `premature` see OpenResty `ngx.timer.at()` -- @param `conf` Configuration table, holds http endpoint details -- @param `message` Message to be logged local function log(premature, conf, message) if premature then return end local msg = cjson.encode(message) .. "\n" local fd = file_descriptors[conf.path] if fd and conf.reopen then -- close fd, we do this here, to make sure a previously cached fd also -- gets closed upon dynamic changes of the configuration ffi.C.close(fd) file_descriptors[conf.path] = nil fd = nil end if not fd then fd = ffi.C.open(conf.path, oflags, mode) if fd < 0 then local errno = ffi.errno() ngx.log(ngx.ERR, "[file-log] failed to open the file: ", ffi.string(ffi.C.strerror(errno))) else file_descriptors[conf.path] = fd end end ffi.C.write(fd, msg, #msg) end local FileLogHandler = BasePlugin:extend() FileLogHandler.PRIORITY = 9 function FileLogHandler:new() FileLogHandler.super.new(self, "file-log") end function FileLogHandler:log(conf) FileLogHandler.super.log(self) local message = basic_serializer.serialize(ngx) local ok, err = ngx_timer(0, log, conf, message) if not ok then ngx.log(ngx.ERR, "[file-log] failed to create timer: ", err) end end return FileLogHandler
apache-2.0
liruqi/bigfoot
Interface/AddOns/DBM-BlackrockFoundry/BlackrockFoundryTrash.lua
1
5887
local mod = DBM:NewMod("BlackrockFoundryTrash", "DBM-BlackrockFoundry") local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 14080 $"):sub(12, -3)) --mod:SetModelID(47785) mod:SetZone() mod.isTrashMod = true mod:RegisterEvents( "SPELL_CAST_START 156446 163194 171537", "SPELL_AURA_APPLIED 175583 175594 175765 175993 177855 159750", "SPELL_AURA_APPLIED_DOSE 175594", "SPELL_AURA_REMOVED 159750", "RAID_BOSS_WHISPER", "UNIT_SPELLCAST_SUCCEEDED" ) local warnLivingBlaze = mod:NewTargetAnnounce(175583, 3, nil, false) local warnEmberInWind = mod:NewTargetAnnounce(177855, 3, nil, false) local warnBlastWaves = mod:NewCountAnnounce(159750, 4)--On mythic the miniboss casts 3 of them in a row at different locations, 3 seconds apart. Basically sindragosa local specWarnOverheadSmash = mod:NewSpecialWarningTaunt(175765) local specWarnBlastWave = mod:NewSpecialWarningMoveTo(156446, nil, DBM_CORE_AUTO_SPEC_WARN_OPTIONS.spell:format(156446)) local specWarnInsatiableHunger = mod:NewSpecialWarningRun(159632, nil, nil, nil, 4) local specWarnLumberingStrength = mod:NewSpecialWarningRun(175993, "Tank", nil, 2, 4) local specWarnLivingBlaze = mod:NewSpecialWarningMoveAway(175583) local yellLivingBlaze = mod:NewYell(175583) local specWarnEmberInWind = mod:NewSpecialWarningMoveAway(177855) local specWarnFinalFlame = mod:NewSpecialWarningDodge(163194, "MeleeDps") local specWarnReapingWhirl = mod:NewSpecialWarningDodge(171537, "MeleeDps") local specWarnBurning = mod:NewSpecialWarningStack(175594, nil, 8) local specWarnBurningOther = mod:NewSpecialWarningTaunt(175594, nil, nil, nil, nil, 2) local voiceBurning = mod:NewVoice(155242) --changemt mod:RemoveOption("HealthFrame") local volcanicBomb = GetSpellInfo(156413) local blastCount = 0--Non synced variable, because mods that don't use start/endcombat don't have timer recovery function mod:SPELL_CAST_START(args) if not self.Options.Enabled then return end local spellId = args.spellId if spellId == 156446 then specWarnBlastWave:Show(volcanicBomb) elseif spellId == 163194 then specWarnFinalFlame:Show() elseif spellId == 171537 then specWarnReapingWhirl:Show() end end function mod:SPELL_AURA_APPLIED(args) if not self.Options.Enabled then return end local spellId = args.spellId if spellId == 175583 then warnLivingBlaze:CombinedShow(0.5, args.destName) if args:IsPlayer() then specWarnLivingBlaze:Show() if not self:IsLFR() then yellLivingBlaze:Yell() end end elseif spellId == 177855 then warnEmberInWind:CombinedShow(0.5, args.destName) if args:IsPlayer() then specWarnEmberInWind:Show() end elseif spellId == 175594 then local amount = args.amount or 1 if (amount >= 8) and (amount % 3 == 0) then voiceBurning:Play("changemt") if args:IsPlayer() then specWarnBurning:Show(amount) else--Taunt as soon as stacks are clear, regardless of stack count. if not UnitDebuff("player", args.spellName) and not UnitIsDeadOrGhost("player") then specWarnBurningOther:Show(args.destName) end end end elseif spellId == 175765 and not args:IsPlayer() then local uId = DBM:GetRaidUnitId(args.destName) if self:IsTanking(uId) then specWarnOverheadSmash:Show(args.destName) end elseif spellId == 175993 then specWarnLumberingStrength:Show() elseif spellId == 159750 then--Mythic version (Blast Waves) DBM:HideBlizzardEvents(1)--Blizzards frame completely covers dbms warnings here and stays on screen forever, so disable the stupid thing. blastCount = 0 specWarnBlastWave:Show(volcanicBomb) end end mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED function mod:SPELL_AURA_REMOVED(args) local spellId = args.spellId if spellId == 159750 then--Mythic version (Blast Waves) DBM:HideBlizzardEvents(0) end end --[[ --Boss Gains Blast Waves "<95.97 22:11:12> [CLEU] SPELL_AURA_APPLIED#Creature-0-3137-1205-5634-77504-000014A9AF#Slag Behemoth#Creature-0-3137-1205-5634-77504-000014A9AF#Slag Behemoth#159750#Blast Waves#BUFF#nil", -- [1429] --Boss Casts First Wave "<99.06 22:11:15> [UNIT_SPELLCAST_SUCCEEDED] Slag Behemoth(Shiramura) target:Blast Waves::0:159751", -- [1506] --Boss Casts Second Wave "<102.03 22:11:18> [UNIT_SPELLCAST_SUCCEEDED] Slag Behemoth(Shiramura) target:Blast Waves::0:159751", -- [1570] --First wave hits "<104.05 22:11:20> [CLEU] SPELL_DAMAGE#Creature-0-3137-1205-5634-77504-000014A9AF#Slag Behemoth#Player-55-05730E16#Torima#159752#Blast Waves#227543#-1", -- [1595] --Boss Casts 3rd and final wave "<104.99 22:11:21> [UNIT_SPELLCAST_SUCCEEDED] Slag Behemoth(Shiramura) target:Blast Waves::0:159755", -- [1625] --Boss Loses Blast Waves "<104.99 22:11:21> [CLEU] SPELL_AURA_REMOVED#Creature-0-3137-1205-5634-77504-000014A9AF#Slag Behemoth#Creature-0-3137-1205-5634-77504-000014A9AF#Slag Behemoth#159750#Blast Waves#BUFF#nil", -- [1627] --Second wave hits "<106.99 22:11:23> [CLEU] SPELL_MISSED#Creature-0-3137-1205-5634-77504-000014A9AF#Slag Behemoth#Player-55-078511B6#Metsuki#159752#Blast Waves#IMMUNE#false", -- [1665] --Third wave hits "<109.00 22:11:25> [CLEU] SPELL_MISSED#Creature-0-3137-1205-5634-77504-000014A9AF#Slag Behemoth#Player-55-036B2A5B#Ikatus#159757#Blast Waves#IMMUNE#false", -- [1720] --]] function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId) if (spellId == 159751 or spellId == 159755) and self:AntiSpam(1.5, 1) then--Sub casts don't show in combat log. Block players who do not pass latency check from sending sync since have to set threshold so low blastCount = blastCount + 1 warnBlastWaves:Show(blastCount) end end function mod:RAID_BOSS_WHISPER(msg, count) if not self.Options.Enabled then return end if msg:find("spell:159632") then specWarnInsatiableHunger:Show() end end
mit
shiprabehera/kong
spec/01-unit/006-schema_validation_spec.lua
3
32117
local schemas = require "kong.dao.schemas_validation" local validate_entity = schemas.validate_entity --require "kong.tools.ngx_stub" describe("Schemas", function() -- Ok kids, today we're gonna test a custom validation schema, -- grab a pair of glasses, this stuff can literally explode. describe("#validate_entity()", function() local schema = { fields = { string = { type = "string", required = true, immutable = true}, table = {type = "table"}, number = {type = "number"}, timestamp = {type = "timestamp"}, url = {regex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$"}, date = {default = 123456, immutable = true}, allowed = {enum = {"hello", "world"}}, boolean_val = {type = "boolean"}, endpoint = { type = "url" }, enum_array = { type = "array", enum = { "hello", "world" }}, default = {default = function(t) assert.truthy(t) return "default" end}, custom = {func = function(v, t) if v then if t.default == "test_custom_func" then return true else return false, "Nah" end else return true end end} } } it("should confirm a valid entity is valid", function() local values = {string = "example entity", url = "example.com"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.True(valid) end) describe("[required]", function() it("should invalidate entity if required property is missing", function() local values = {url = "example.com"} local valid, err = validate_entity(values, schema) assert.False(valid) assert.truthy(err) assert.are.same("string is required", err.string) end) it("errors if required property is set to ngx.null", function() local values = { string = ngx.null } local ok, err = validate_entity(values, schema) assert.falsy(ok) assert.equal("string is required", err.string) end) end) describe("[type]", function() --[] it("should validate the type of a property if it has a type field", function() -- Failure local values = {string = "foo", table = "bar"} local valid, err = validate_entity(values, schema) assert.False(valid) assert.truthy(err) assert.are.same("table is not a table", err.table) -- Success local values = {string = "foo", table = {foo = "bar"}} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.True(valid) -- Failure local values = {string = 1, table = {foo = "bar"}} local valid, err = validate_entity(values, schema) assert.False(valid) assert.truthy(err) assert.are.same("string is not a string", err.string) -- Success local values = {string = "foo", number = 10} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.True(valid) -- Success local values = {string = "foo", number = "10"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.are.same("number", type(values.number)) -- Success local values = {string = "foo", boolean_val = true} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.are.same("boolean", type(values.boolean_val)) -- Success local values = {string = "foo", boolean_val = "true"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) -- Failure local values = {string = "foo", endpoint = ""} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.truthy(err) assert.are.equal("endpoint is not a url", err.endpoint) -- Failure local values = {string = "foo", endpoint = "asdasd"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.truthy(err) -- Success local values = {string = "foo", endpoint = "http://google.com"} local valid, err = validate_entity(values, schema) assert.truthy(valid) assert.falsy(err) -- Success local values = {string = "foo", endpoint = "http://google.com/"} local valid, err = validate_entity(values, schema) assert.truthy(valid) assert.falsy(err) -- Success local values = {string = "foo", endpoint = "http://google.com/hello/?world=asd"} local valid, err = validate_entity(values, schema) assert.truthy(valid) assert.falsy(err) end) it("should return error when an invalid boolean value is passed", function() local values = {string = "test", boolean_val = "ciao"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.truthy(err) assert.are.same("boolean_val is not a boolean", err.boolean_val) end) it("should not return an error when a true boolean value is passed", function() local values = {string = "test", boolean_val = true} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) end) it("should not return an error when a false boolean value is passed", function() local values = {string = "test", boolean_val = false} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) end) it("should consider `id` as a type", function() local s = { fields = { id = {type = "id"} } } local values = {id = "123"} local valid, err = validate_entity(values, s) assert.falsy(err) assert.truthy(valid) end) it("should consider `timestamp` as a type", function() local s = { fields = { created_at = {type = "timestamp"} } } local values = {created_at = "123"} local valid, err = validate_entity(values, s) assert.falsy(err) assert.truthy(valid) end) it("should consider `array` as a type", function() local s = { fields = { array = {type = "array"} } } -- Success local values = {array = {"hello", "world"}} local valid, err = validate_entity(values, s) assert.True(valid) assert.falsy(err) -- Failure local values = {array = {hello="world"}} local valid, err = validate_entity(values, s) assert.False(valid) assert.truthy(err) assert.equal("array is not an array", err.array) end) describe("[aliases]", function() it("should not return an error when a `number` is passed as a string", function() local values = {string = "test", number = "10"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.same("number", type(values.number)) end) it("should not return an error when a `boolean` is passed as a string", function() local values = {string = "test", boolean_val = "false"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.same("boolean", type(values.boolean_val)) end) it("should not return an error when a `timestamp` is passed as a string", function() local values = {string = "test", timestamp = "123"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.same("number", type(values.timestamp)) end) it("should return an error when a `timestamp` is not a number", function() local values = {string = "test", timestamp = "just a string"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.are.same("timestamp is not a timestamp", err.timestamp) end) it("should return an error when a `timestamp` is a negative number", function() local values = {string = "test", timestamp = "-123"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.are.same("timestamp is not a timestamp", err.timestamp) end) it("should alias a string to `array`", function() local s = { fields = { array = {type = "array"} } } -- It should also strip the resulting strings local values = { array = "hello, world" } local valid, err = validate_entity(values, s) assert.True(valid) assert.falsy(err) assert.same({"hello", "world"}, values.array) end) it("preserves escaped commas in comma-separated arrays", function() -- Note: regression test for arrays of PCRE URIs: -- https://github.com/Mashape/kong/issues/2780 local s = { fields = { array = { type = "array" } } } local values = { array = [[hello\, world,goodbye world\,,/hello/\d{1\,3}]] } local valid, err = validate_entity(values, s) assert.True(valid) assert.falsy(err) assert.same({ "hello, world", "goodbye world,", [[/hello/\d{1,3}]] }, values.array) end) end) end) describe("[default]", function() it("should set default values if those are variables or functions specified in the validator", function() -- Variables local values = {string = "example entity", url = "example.com"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.are.same(123456, values.date) -- Functions local values = {string = "example entity", url = "example.com"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.are.same("default", values.default) end) it("should override default values if specified", function() -- Variables local values = {string = "example entity", url = "example.com", date = 654321} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.are.same(654321, values.date) -- Functions local values = {string = "example entity", url = "example.com", default = "abcdef"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) assert.are.same("abcdef", values.default) end) it("sets to default when a field is given ngx.null", function() local values = { string = "foo", default = ngx.null } local ok, err = validate_entity(values, schema) assert.falsy(err) assert.is_true(ok) assert.equal("default", values.default) end) end) describe("[regex]", function() it("should validate a field against a regex", function() local values = {string = "example entity", url = "example_!"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.truthy(err) assert.are.same("url has an invalid value", err.url) end) end) describe("[enum]", function() it("should validate a field against an enum", function() -- Success local values = {string = "somestring", allowed = "hello"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) -- Failure local values = {string = "somestring", allowed = "hello123"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.truthy(err) assert.are.same("\"hello123\" is not allowed. Allowed values are: \"hello\", \"world\"", err.allowed) end) it("should validate an enum into an array", function() -- Failure local values = {string = "somestring", enum_array = "hello1"} local valid, err = validate_entity(values, schema) assert.truthy(err) assert.falsy(valid) assert.are.same("\"hello1\" is not allowed. Allowed values are: \"hello\", \"world\"", err.enum_array) -- Failure local values = {string = "somestring", enum_array = {"hello1"}} local valid, err = validate_entity(values, schema) assert.truthy(err) assert.falsy(valid) assert.are.same("\"hello1\" is not allowed. Allowed values are: \"hello\", \"world\"", err.enum_array) -- Success local values = {string = "somestring", enum_array = {"hello"}} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) -- Success local values = {string = "somestring", enum_array = {"hello", "world"}} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) -- Failure local values = {string = "somestring", enum_array = {"hello", "world", "another"}} local valid, err = validate_entity(values, schema) assert.truthy(err) assert.falsy(valid) assert.are.same("\"another\" is not allowed. Allowed values are: \"hello\", \"world\"", err.enum_array) -- Success local values = {string = "somestring", enum_array = {}} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) end) end) describe("[func]", function() it("should validate a field against a custom function", function() -- Success local values = {string = "somestring", custom = true, default = "test_custom_func"} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) -- Failure local values = {string = "somestring", custom = true, default = "not the default :O"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.truthy(err) assert.are.same("Nah", err.custom) end) it("is called with arg1 'nil' when given ngx.null", function() spy.on(schema.fields.custom, "func") local values = { string = "foo", custom = ngx.null } local ok, err = validate_entity(values, schema) assert.falsy(err) assert.is_true(ok) assert.is_nil(values.custom) assert.spy(schema.fields.custom.func).was_called_with(nil, values, "custom") end) end) it("should return error when unexpected values are included in the schema", function() local values = {string = "example entity", url = "example.com", unexpected = "abcdef"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.truthy(err) end) it("should be able to return multiple errors at once", function() local values = {url = "example.com", unexpected = "abcdef"} local valid, err = validate_entity(values, schema) assert.falsy(valid) assert.truthy(err) assert.are.same("string is required", err.string) assert.are.same("unexpected is an unknown field", err.unexpected) end) it("should not check a custom function if a `required` condition is false already", function() local f = function() error("should not be called") end -- cannot use a spy which changes the type to table local schema = { fields = { property = {required = true, func = f} } } assert.has_no_errors(function() local valid, err = validate_entity({}, schema) assert.False(valid) assert.are.same("property is required", err.property) end) end) describe("Sub-schemas", function() -- To check wether schema_from_function was called, we will simply use booleans because -- busted's spy methods create tables and metatable magic, but the validate_entity() function -- only callse v.schema if the type is a function. Which is not the case with a busted spy. local called, called_with local schema_from_function = function(t) called = true called_with = t if t.error_loading_sub_sub_schema then return nil, "Error loading the sub-sub-schema" end return {fields = {sub_sub_field_required = {required = true}}} end local nested_schema = { fields = { some_required = { required = true }, sub_schema = { type = "table", schema = { fields = { sub_field_required = {required = true}, sub_field_default = {default = "abcd"}, sub_field_number = {type = "number"}, error_loading_sub_sub_schema = {} } } } } } it("should validate a property with a sub-schema", function() -- Success local values = { some_required = "somestring", sub_schema = {sub_field_required = "sub value"}} local valid, err = validate_entity(values, nested_schema) assert.falsy(err) assert.truthy(valid) assert.are.same("abcd", values.sub_schema.sub_field_default) -- Failure local values = {some_required = "somestring", sub_schema = {sub_field_default = ""}} local valid, err = validate_entity(values, nested_schema) assert.truthy(err) assert.falsy(valid) assert.are.same("sub_field_required is required", err["sub_schema.sub_field_required"]) end) it("should validate a property with a sub-schema from a function", function() nested_schema.fields.sub_schema.schema.fields.sub_sub_schema = {schema = schema_from_function} -- Success local values = {some_required = "somestring", sub_schema = { sub_field_required = "sub value", sub_sub_schema = {sub_sub_field_required = "test"} }} local valid, err = validate_entity(values, nested_schema) assert.falsy(err) assert.truthy(valid) -- Failure local values = {some_required = "somestring", sub_schema = { sub_field_required = "sub value", sub_sub_schema = {} }} local valid, err = validate_entity(values, nested_schema) assert.truthy(err) assert.falsy(valid) assert.are.same("sub_sub_field_required is required", err["sub_schema.sub_sub_schema.sub_sub_field_required"]) end) it("should call the schema function with the actual parent t table of the subschema", function() local values = {some_required = "somestring", sub_schema = { sub_field_default = "abcd", sub_field_required = "sub value", sub_sub_schema = {sub_sub_field_required = "test"} }} local valid, err = validate_entity(values, nested_schema) assert.falsy(err) assert.truthy(valid) assert.True(called) assert.are.same(values.sub_schema, called_with) end) it("should retrieve errors when cannot load schema from function", function() local values = {some_required = "somestring", sub_schema = { sub_field_default = "abcd", sub_field_required = "sub value", error_loading_sub_sub_schema = true, sub_sub_schema = {sub_sub_field_required = "test"} }} local valid, err = validate_entity(values, nested_schema) assert.truthy(err) assert.falsy(valid) assert.are.same("Error loading the sub-sub-schema", err["sub_schema.sub_sub_schema"]) end) it("should instanciate a sub-value if sub-schema has a `default` value and do that before `required`", function() local function validate_value(value) if not value.some_property then return false, "value.some_property must not be empty" end return true end local schema = { fields = { value = {type = "table", schema = {fields = {some_property={default="hello"}}}, func = validate_value, required = true} } } local obj = {} local valid, err = validate_entity(obj, schema) assert.falsy(err) assert.True(valid) assert.are.same("hello", obj.value.some_property) end) it("should mark a value required if sub-schema has a `required`", function() local schema = { fields = { value = {type = "table", schema = {fields = {some_property={required=true}}}} } } local obj = {} local valid, err = validate_entity(obj, schema) assert.truthy(err) assert.False(valid) assert.are.same("value.some_property is required", err.value) end) it("should work with flexible schemas", function() local schema = { fields = { flexi = { type = "table", schema = { flexible = true, fields = { name = {type = "string"}, age = {type = "number"} } } } } } local obj = { flexi = { somekey = { name = "Mark", age = 12 } } } local valid, err = validate_entity(obj, schema) assert.falsy(err) assert.True(valid) assert.are.same({flexi = { somekey = { name = "Mark", age = 12 } }}, obj) obj = { flexi = { somekey = { name = "Mark", age = 12 }, hello = { name = "Mark2", age = 13 } } } valid, err = validate_entity(obj, schema) assert.falsy(err) assert.True(valid) assert.are.same({flexi = { somekey = { name = "Mark", age = 12 }, hello = { name = "Mark2", age = 13 } }}, obj) end) it("should return proper errors with a flexible schema", function() local schema = { fields = { flexi = { type = "table", schema = { flexible = true, fields = { name = {type = "string"}, age = {type = "number"} } } } } } local obj = { flexi = { somekey = { name = "Mark", age = "hello" } } } local valid, err = validate_entity(obj, schema) assert.truthy(err) assert.falsy(valid) assert.are.same("age is not a number", err["flexi.somekey.age"]) end) it("should return proper errors with a flexible schema an an unknown field", function() local schema = { fields = { flexi = { type = "table", schema = { flexible = true, fields = { name = {type = "string"}, age = {type = "number"} } } } } } local obj = { flexi = { somekey = { name = "Mark", age = 12, asd = "hello" } } } local valid, err = validate_entity(obj, schema) assert.truthy(err) assert.falsy(valid) assert.are.same("asd is an unknown field", err["flexi.somekey.asd"]) end) it("should return proper errors with a flexible schema with two keys and an unknown field", function() local schema = { fields = { flexi = { type = "table", schema = { flexible = true, fields = { name = {type = "string"}, age = {type = "number"} } } } } } local obj = { flexi = { somekey = { name = "Mark" }, somekey2 = { name = "Mark", age = 12, asd = "hello" } } } local valid, err = validate_entity(obj, schema) assert.truthy(err) assert.falsy(valid) assert.are.same("asd is an unknown field", err["flexi.somekey2.asd"]) end) it("errors if required sub-schema is given ngx.null", function() local values = { some_required = "foo", sub_schema = ngx.null } local ok, err = validate_entity(values, nested_schema) assert.falsy(ok) assert.same({ ["sub_schema"] = "sub_schema.sub_field_required is required", ["sub_schema.sub_field_required"] = "sub_field_required is required", ["sub_schema.sub_sub_schema"] = "sub_sub_schema.sub_sub_field_required is required", }, err) end) it("gives NULL to sub-schema if given ngx.null in update", function() local values = { some_required = "foo", sub_schema = ngx.null } local ok, err = validate_entity(values, nested_schema, { update = true }) assert.falsy(err) assert.is_true(ok) assert.equal(ngx.null, values.sub_schema) end) it("errors if required sub-schema is given ngx.null in a full update", function() local values = { some_required = "foo", sub_schema = ngx.null } local ok, err = validate_entity(values, nested_schema, { update = true, full_update = true }) assert.falsy(ok) assert.same({ ["sub_schema"] = "sub_schema.sub_field_required is required", ["sub_schema.sub_field_required"] = "sub_field_required is required", ["sub_schema.sub_sub_schema"] = "sub_sub_schema.sub_sub_field_required is required", }, err) end) end) describe("[update] (partial)", function() it("should ignore required properties and defaults if we are updating because the entity might be partial", function() local values = {} local valid, err = validate_entity(values, schema, {update = true}) assert.falsy(err) assert.True(valid) assert.falsy(values.default) assert.falsy(values.date) end) it("should still validate set properties", function() local values = {string = 123} local valid, err = validate_entity(values, schema, {update = true}) assert.False(valid) assert.equal("string is not a string", err.string) end) it("should ignore immutable fields if they are required", function() local values = {string = "somestring"} local valid, err = validate_entity(values, schema, {update = true}) assert.falsy(err) assert.True(valid) end) it("should prevent immutable fields to be changed", function() -- Success local values = {string = "somestring", date = 5678} local valid, err = validate_entity(values, schema) assert.falsy(err) assert.truthy(valid) -- Failure local valid, err = validate_entity(values, schema, {update = true, old_t = {date = 1234}}) assert.False(valid) assert.truthy(err) assert.equal("date cannot be updated", err.date) end) it("passes NULL if a field with default is given ngx.null", function() local values = { string = "foo", date = ngx.null } local ok, err = validate_entity(values, schema, { update = true }) assert.falsy(err) assert.is_true(ok) assert.equal(ngx.null, values.date) -- DAO will handle ngx.null to 'NULL' end) it("calls 'func' with arg1 'nil' when given ngx.null", function() spy.on(schema.fields.custom, "func") local values = { string = "foo", custom = ngx.null } local ok, err = validate_entity(values, schema, { update = true }) assert.falsy(err) assert.is_true(ok) assert.equal(ngx.null, values.custom) assert.spy(schema.fields.custom.func).was_called_with(nil, values, "custom") end) it("errors when a required field is given ngx.null", function() spy.on(schema.fields.custom, "func") local values = { string = ngx.null } local ok, err = validate_entity(values, schema, { update = true }) assert.falsy(ok) assert.equal("string is required", err.string) end) end) describe("[update] (full)", function() it("should not ignore required properties", function() local values = {} local valid, err = validate_entity(values, schema, {update = true, full_update = true}) assert.False(valid) assert.truthy(err) assert.equal("string is required", err.string) end) it("should complete default fields", function() local values = {string = "foo", date = 123456} local valid, err = validate_entity(values, schema, {update = true, full_update = true}) assert.True(valid) assert.falsy(err) assert.equal("default", values.default) end) it("sets a field to its default if given ngx.null", function() local values = { string = "foo", date = ngx.null } local ok, err = validate_entity(values, schema, {update = true, full_update = true}) assert.falsy(err) assert.is_true(ok) assert.is_number(values.date) end) it("calls 'func' with arg1 'nil' when given ngx.null", function() spy.on(schema.fields.custom, "func") local values = { string = "foo", custom = ngx.null } local ok, err = validate_entity(values, schema, { update = true, full_update = true }) assert.falsy(err) assert.is_true(ok) assert.is_nil(values.custom) assert.spy(schema.fields.custom.func).was_called_with(nil, values, "custom") end) it("errors when a required field is given ngx.null", function() spy.on(schema.fields.custom, "func") local values = { string = ngx.null } local ok, err = validate_entity(values, schema, { update = true, full_update = true }) assert.falsy(ok) assert.equal("string is required", err.string) end) end) end) end)
apache-2.0
alicemirror/EA3250
package/uci/trigger/lib/trigger.lua
40
8391
module("uci.trigger", package.seeall) require("posix") require("uci") local path = "/lib/config/trigger" local triggers = nil local tmp_cursor = nil function load_modules() if triggers ~= nil then return end triggers = { list = {}, uci = {}, active = {} } local modules = posix.glob(path .. "/*.lua") if modules == nil then return end local oldpath = package.path package.path = path .. "/?.lua" for i, v in ipairs(modules) do pcall(require(string.gsub(v, path .. "/(%w+)%.lua$", "%1"))) end package.path = oldpath end function check_table(table, name) if table[name] == nil then table[name] = {} end return table[name] end function get_table_val(val, vtype) if type(val) == (vtype or "string") then return { val } elseif type(val) == "table" then return val end return nil end function get_name_list(name) return get_table_val(name or ".all") end function add_trigger_option(list, t) local name = get_name_list(t.option) for i, n in ipairs(name) do option = check_table(list, n) table.insert(option, t) end end function add_trigger_section(list, t) local name = get_name_list(t.section) for i, n in ipairs(name) do section = check_table(list, n) add_trigger_option(section, t) end end function check_insert_triggers(dest, list, tuple) if list == nil then return end for i, t in ipairs(list) do local add = true if type(t.check) == "function" then add = t.check(tuple) end if add then dest[t.id] = t end end end function find_section_triggers(tlist, pos, tuple) if pos == nil then return end check_insert_triggers(tlist, pos[".all"], tuple) if tuple.option then check_insert_triggers(tlist, pos[tuple.option], tuple) end end function check_recursion(name, seen) if seen == nil then seen = {} end if seen[name] then return nil end seen[name] = true return seen end function find_recursive_depends(list, name, seen) seen = check_recursion(name, seen) if not seen then return end local bt = get_table_val(triggers.list[name].belongs_to) or {} for i, n in ipairs(bt) do table.insert(list, n) find_recursive_depends(list, n, seen) end end function check_trigger_depth(list, name) if name == nil then return end local n = list[name] if n == nil then return end list[name] = nil return check_trigger_depth(list, n) end function find_triggers(tuple) local pos = triggers.uci[tuple.package] if pos == nil then return {} end local tlist = {} find_section_triggers(tlist, pos[".all"], tuple) find_section_triggers(tlist, pos[tuple.section[".type"]], tuple) for n, t in pairs(tlist) do local dep = {} find_recursive_depends(dep, t.id) for i, depname in ipairs(dep) do check_trigger_depth(tlist, depname) end end local nlist = {} for n, t in pairs(tlist) do if t then table.insert(nlist, t) end end return nlist end function reset_state() assert(io.open("/var/run/uci_trigger", "w")):close() if tctx then tctx:unload("uci_trigger") end end function load_state() -- make sure the config file exists before we attempt to load it -- uci doesn't like loading nonexistent config files local f = assert(io.open("/var/run/uci_trigger", "a")):close() load_modules() triggers.active = {} if tctx then tctx:unload("uci_trigger") else tctx = uci.cursor() end assert(tctx:load("/var/run/uci_trigger")) tctx:foreach("uci_trigger", "trigger", function(section) trigger = triggers.list[section[".name"]] if trigger == nil then return end active = {} triggers.active[trigger.id] = active local s = get_table_val(section["sections"]) or {} for i, v in ipairs(s) do active[v] = true end end ) end function get_names(list) local slist = {} for name, val in pairs(list) do if val then table.insert(slist, name) end end return slist end function check_cancel(name, seen) local t = triggers.list[name] local dep = get_table_val(t.belongs_to) seen = check_recursion(name, seen) if not t or not dep or not seen then return false end for i, v in ipairs(dep) do -- only cancel triggers for all sections -- if both the current and the parent trigger -- are per-section local section_only = false if t.section_only then local tdep = triggers.list[v] if tdep then section_only = tdep.section_only end end if check_cancel(v, seen) then return true end if triggers.active[v] then if section_only then for n, active in pairs(triggers.active[v]) do triggers.active[name][n] = false end else return true end end end return false end -- trigger api functions function add(ts) for i,t in ipairs(ts) do triggers.list[t.id] = t match = {} if t.package then local package = check_table(triggers.uci, t.package) add_trigger_section(package, t) triggers.list[t.id] = t end end end function save_trigger(name) if triggers.active[name] then local slist = get_names(triggers.active[name]) if #slist > 0 then tctx:set("uci_trigger", name, "sections", slist) end else tctx:delete("uci_trigger", name) end end function set(data, cursor) assert(data ~= nil) if cursor == nil then cursor = tmp_cursor or uci.cursor() tmp_cursor = uci.cursor end local tuple = { package = data[1], section = data[2], option = data[3], value = data[4] } assert(cursor:load(tuple.package)) load_state() local section = cursor:get_all(tuple.package, tuple.section) if (section == nil) then if option ~= nil then return end section = { [".type"] = value } if tuple.section == nil then tuple.section = "" section[".anonymous"] = true end section[".name"] = tuple.section end tuple.section = section local ts = find_triggers(tuple) for i, t in ipairs(ts) do local active = triggers.active[t.id] if not active then active = {} triggers.active[t.id] = active tctx:set("uci_trigger", t.id, "trigger") end if section[".name"] then active[section[".name"]] = true end save_trigger(t.id) end tctx:save("uci_trigger") end function get_description(trigger, sections) if not trigger.title then return trigger.id end local desc = trigger.title if trigger.section_only and sections and #sections > 0 then desc = desc .. " (" .. table.concat(sections, ", ") .. ")" end return desc end function get_active() local slist = {} if triggers == nil then load_state() end for name, val in pairs(triggers.active) do if val and not check_cancel(name) then local sections = {} for name, active in pairs(triggers.active[name]) do if active then table.insert(sections, name) end end table.insert(slist, { triggers.list[name], sections }) end end return slist end function set_active(trigger, sections) if triggers == nil then load_state() end if not triggers.list[trigger] then return end if triggers.active[trigger] == nil then tctx:set("uci_trigger", trigger, "trigger") triggers.active[trigger] = {} end local active = triggers.active[trigger] if triggers.list[trigger].section_only or sections ~= nil then for i, t in ipairs(sections) do triggers.active[trigger][t] = true end end save_trigger(trigger) tctx:save("uci_trigger") end function clear_active(trigger, sections) if triggers == nil then load_state() end if triggers.list[trigger] == nil or triggers.active[trigger] == nil then return end local active = triggers.active[trigger] if not triggers.list[trigger].section_only or sections == nil then triggers.active[trigger] = nil else for i, t in ipairs(sections) do triggers.active[trigger][t] = false end end save_trigger(trigger) tctx:save("uci_trigger") end function run(ts) if ts == nil then ts = get_active() end for i, t in ipairs(ts) do local trigger = t[1] local sections = t[2] local actions = get_table_val(trigger.action, "function") or {} for ai, a in ipairs(actions) do if not trigger.section_only then sections = { "" } end for si, s in ipairs(sections) do if a(s) then tctx:delete("uci_trigger", trigger.id) tctx:save("uci_trigger") end end end end end -- helper functions function system_command(arg) local cmd = arg return function(arg) return os.execute(cmd:format(arg)) == 0 end end function service_restart(arg) return system_command("/etc/init.d/" .. arg .. " restart") end
gpl-2.0
TeleDALAD/sg
plugins/spanish_lang.lua
1
17433
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos & @iicc1 -- -- -- -------------------------------------------------- local LANG = 'es' local function run(msg, matches) if permissions(msg.from.id, msg.to.id, "lang_install") then ------------------------- -- Translation version -- ------------------------- set_text(LANG, 'version', '0.1') set_text(LANG, 'versionExtended', 'Traducción versión 0.1') ------------- -- Plugins -- ------------- -- global plugins -- set_text(LANG, 'require_sudo', 'Este plugin requiere privilegios sudo o superior') set_text(LANG, 'require_admin', 'Este plugin requiere privilegios admin o superior') set_text(LANG, 'require_mod', 'Este plugin requiere privilegios mod o superior') -- Spam.lua -- set_text(LANG, 'reportUser', 'USUARIO') set_text(LANG, 'reportReason', 'Motivo del reporte') set_text(LANG, 'reportGroup', 'Grupo') set_text(LANG, 'reportMessage', 'Mensaje') set_text(LANG, 'allowedSpamT', 'Spam permitido en este grupo') set_text(LANG, 'allowedSpamL', 'Spam permitido en este supergrupo') set_text(LANG, 'notAllowedSpamT', 'Spam no permitido en este grupo') set_text(LANG, 'notAllowedSpamL', 'Spam no permitido en este supergrupo') -- bot.lua -- set_text(LANG, 'botOn', 'Estoy listo, allá vamos!') set_text(LANG, 'botOff', 'No pinto nada aquí') -- settings.lua -- set_text(LANG, 'user', 'El usuario') set_text(LANG, 'isFlooding', 'está haciendo flood.') set_text(LANG, 'noStickersT', 'Stickers no permitidos en este grupo.') set_text(LANG, 'noStickersL', 'Stickers no permitidos en este supergrupo.') set_text(LANG, 'stickersT', 'Stickers permitidos en este grupo.') set_text(LANG, 'stickersL', 'Stickers permitidos en este supergrupo.') set_text(LANG, 'gifsT', 'Gifs permitidos en este grupo.') set_text(LANG, 'gifsL', 'Gifs permitidos en este supergrupo.') set_text(LANG, 'noGifsT', 'Gifs no permitidos en este grupo.') set_text(LANG, 'noGifsL', 'Gifs no permitidos en este supergrupo.') set_text(LANG, 'photosT', 'Fotos permitidas en este grupo.') set_text(LANG, 'photosL', 'Fotos permitidas en este supergrupo.') set_text(LANG, 'noPhotosT', 'Fotos no permitidas en este grupo.') set_text(LANG, 'noPhotosL', 'Fotos no permitidas en este supergrupo.') set_text(LANG, 'arabicT', 'El árabe está ahora permitido en este grupo.') set_text(LANG, 'arabicL', 'El árabe está ahora permitido en este supergrupo.') set_text(LANG, 'noArabicT', 'El árabe no está permitido en este grupo.') set_text(LANG, 'noArabicL', 'El árabe no está permitido en este supergrupo.') set_text(LANG, 'audiosT', 'Audios permitidos en este grupo.') set_text(LANG, 'audiosL', 'Audios permitidos en este supergrupo.') set_text(LANG, 'noAudiosT', 'Audios no permitidos en este grupo.') set_text(LANG, 'noAudiosL', 'Audios no permitidos en este supergrupo.') set_text(LANG, 'kickmeT', 'Autoexpulsión permitida en este grupo.') set_text(LANG, 'kickmeL', 'Autoexpulsión permitida en este supergrupo.') set_text(LANG, 'noKickmeT', 'Autoexpulsión no permitida en este grupo.') set_text(LANG, 'noKickmeL', 'Autoexpulsión no permitida en este supergrupo.') set_text(LANG, 'floodT', 'Flood permitido en este grupo.') set_text(LANG, 'floodL', 'Flood permitido en este supergrupo.') set_text(LANG, 'noFloodT', 'Flood no permitido en este grupo.') set_text(LANG, 'noFloodL', 'Flood no permitido en este supergrupo.') set_text(LANG, 'floodTime', 'Tiempo máximo de flood establecido a ') set_text(LANG, 'floodMax', 'Número máximo de mensajes flood establecido a ') set_text(LANG, 'gSettings', 'Ajustes del grupo') set_text(LANG, 'sSettings', 'Ajustes del supergrupo') set_text(LANG, 'allowed', 'permitido') set_text(LANG, 'noAllowed', 'no permitido') set_text(LANG, 'noSet', 'no establecido') set_text(LANG, 'stickers', 'Stickers') set_text(LANG, 'links', 'Enlaces') set_text(LANG, 'arabic', 'Árabe') set_text(LANG, 'bots', 'Bots') set_text(LANG, 'gifs', 'Gifs') set_text(LANG, 'photos', 'Fotos') set_text(LANG, 'audios', 'Audios') set_text(LANG, 'kickme', 'Autoexpulsión') set_text(LANG, 'spam', 'Spam') set_text(LANG, 'gName', 'Nombre del grupo') set_text(LANG, 'flood', 'Flood') set_text(LANG, 'language', 'Idioma') set_text(LANG, 'mFlood', 'Límite de flood') set_text(LANG, 'tFlood', 'Tiempo de flood') set_text(LANG, 'setphoto', 'Establecer foto') set_text(LANG, 'photoSaved', 'Foto guardada!') set_text(LANG, 'photoFailed', 'Error, intenta de nuevo!') set_text(LANG, 'setPhotoAborted', 'Parando el proceso de establecer foto...') set_text(LANG, 'sendPhoto', 'Envia una foto por favor') set_text(LANG, 'linkSaved', 'Nuevo link guardado') set_text(LANG, 'groupLink', 'Link del grupo') set_text(LANG, 'sGroupLink', 'Link del supergrupo') set_text(LANG, 'noLinkSet', 'No hay ningún link establecido. Por favor añade uno con #setlink [Link].') set_text(LANG, 'chatRename', 'Ahora puedes renombrar el chat.') set_text(LANG, 'channelRename', 'Ahora puedes renombrar el supergrupo.') set_text(LANG, 'notChatRename', 'Ahora no puedes renombrar el chat.') set_text(LANG, 'notChannelRename', 'Ahora no puedes renombrar el supergrupo.') set_text(LANG, 'lockMembersT', 'El número de miembros del chat ha sido bloqueado.') set_text(LANG, 'lockMembersL', 'El número de miembros del supergrupo ha sido bloqueado.') set_text(LANG, 'notLockMembersT', 'El número de miembros del chat ha sido desbloqueado.') set_text(LANG, 'notLockMembersL', 'El número de miembros del supergrupo ha sido desbloqueado.') set_text(LANG, 'langUpdated', 'El idioma ha sido cambiado a: ') -- export_gban.lua -- set_text(LANG, 'accountsGban', 'cuentas globalmente baneadas.') -- giverank.lua -- set_text(LANG, 'alreadyAdmin', 'Este usuario ya es admin.') set_text(LANG, 'alreadyMod', 'Este usuario ya es mod.') set_text(LANG, 'newAdmin', 'Nuevo admin') set_text(LANG, 'newMod', 'Nuevo mod') set_text(LANG, 'nowUser', 'ahora es un usuario.') set_text(LANG, 'modList', 'Lista de Mods') set_text(LANG, 'adminList', 'Lista de Admins') set_text(LANG, 'modEmpty', 'La lista de mods está vacia en este chat.') set_text(LANG, 'adminEmpty', 'La lista de admins está vacia.') -- id.lua -- set_text(LANG, 'user', 'Usuario') set_text(LANG, 'supergroupName', 'Nombre del SuperGrupo') set_text(LANG, 'chatName', 'Nombre del Chat') set_text(LANG, 'supergroup', 'SuperGrupo') set_text(LANG, 'chat', 'Chat') -- moderation.lua -- set_text(LANG, 'userUnmuted:1', 'Usuario') set_text(LANG, 'userUnmuted:2', 'No silenciado.') set_text(LANG, 'userMuted:1', 'Usuario.') set_text(LANG, 'userMuted:2', 'silenciado.') set_text(LANG, 'kickUser:1', 'Usuario') set_text(LANG, 'kickUser:2', 'expulsado.') set_text(LANG, 'banUser:1', 'Usuario') set_text(LANG, 'banUser:2', 'baneado.') set_text(LANG, 'unbanUser:1', 'Usuario') set_text(LANG, 'unbanUser:2', 'está desbaneado.') set_text(LANG, 'gbanUser:1', 'Usuario') set_text(LANG, 'gbanUser:2', 'globalmente baneado.') set_text(LANG, 'ungbanUser:1', 'Usuario') set_text(LANG, 'ungbanUser:2', 'desbaneado globalmente.') set_text(LANG, 'addUser:1', 'Usuario') set_text(LANG, 'addUser:2', 'añadido al chat.') set_text(LANG, 'addUser:3', 'añadido al supergrupo.') set_text(LANG, 'kickmeBye', 'adiós.') -- plugins.lua -- set_text(LANG, 'plugins', 'Plugins') set_text(LANG, 'installedPlugins', 'plugins instalados.') set_text(LANG, 'pEnabled', 'activado.') set_text(LANG, 'pDisabled', 'desactivado.') set_text(LANG, 'isEnabled:1', 'Plugin') set_text(LANG, 'isEnabled:2', 'está activado.') set_text(LANG, 'notExist:1', 'Plugin') set_text(LANG, 'notExist:2', 'no existe.') set_text(LANG, 'notEnabled:1', 'Plugin') set_text(LANG, 'notEnabled:2', 'no activado.') set_text(LANG, 'pNotExists', 'No existe el plugin.') set_text(LANG, 'pDisChat:1', 'Plugin') set_text(LANG, 'pDisChat:2', 'desactivado en este chat.') set_text(LANG, 'anyDisPlugin', 'No hay plugins desactivados.') set_text(LANG, 'anyDisPluginChat', 'No hay plugins desactivados en este chat.') set_text(LANG, 'notDisabled', 'Este plugin no está desactivado') set_text(LANG, 'enabledAgain:1', 'Plugin') set_text(LANG, 'enabledAgain:2', 'está activado de nuevo') -- commands.lua -- set_text(LANG, 'commandsT', 'Comandos') set_text(LANG, 'errorNoPlug', 'Este plugin no existe o no tiene comandos.') ------------ -- Usages -- ------------ -- bot.lua -- set_text(LANG, 'bot:0', 2) set_text(LANG, 'bot:1', '#bot on: activa el bot en el chat actual.') set_text(LANG, 'bot:2', '#bot off: desactiva el bot en el chat actual.') -- commands.lua -- set_text(LANG, 'commands:0', 2) set_text(LANG, 'commands:1', '#commands: Muestra los comandos para todos los plugins.') set_text(LANG, 'commands:2', '#commands [plugin]: Comandos para ese plugin.') -- export_gban.lua -- set_text(LANG, 'export_gban:0', 2) set_text(LANG, 'export_gban:1', '#gbans installer: Devuelve un archivo lua instalador para compartir gbans y añadirlos en otro bot con un único comando.') set_text(LANG, 'export_gban:2', '#gbans list: Devuelve un archivo con la lista de gbans.') -- gban_installer.lua -- set_text(LANG, 'gban_installer:0', 1) set_text(LANG, 'gban_installer:1', '#install gbans: añade una lista de gbans en tu base de datos redis.') -- giverank.lua -- set_text(LANG, 'giverank:0', 9) set_text(LANG, 'giverank:1', '#rank admin (reply): convierte la persona a la que respondes en admin.') set_text(LANG, 'giverank:2', '#rank admin <user_id>/<user_name>: añade un admin mediante su ID/Username.') set_text(LANG, 'giverank:3', '#rank mod (reply): convierte la persona a la que respondes en mod.') set_text(LANG, 'giverank:4', '#rank mod <user_id>/<user_name>: añade un mod mediante su ID/Username.') set_text(LANG, 'giverank:5', '#rank guest (reply): borra de admin a la persona que respondes.') set_text(LANG, 'giverank:6', '#rank guest <user_id>/<user_name>: borra un admin mediante su ID/Username.') set_text(LANG, 'giverank:7', '#admins: lista de todos los admins.') set_text(LANG, 'giverank:8', '#mods: lista de todos los mods.') set_text(LANG, 'giverank:9', '#members: lista de todos los miembros del chat.') -- id.lua -- set_text(LANG, 'id:0', 6) set_text(LANG, 'id:1', '#id: devuelve tu id y la del chat si estás en alguno.') set_text(LANG, 'id:2', '#ids chat: devuelve las IDs de los miembros actuales en el grupo.') set_text(LANG, 'id:3', '#ids channel: devuelve las IDs de los miembros actuales en el supergrupo.') set_text(LANG, 'id:4', '#id <user_name>: devuelve la ID del usuario presente en el chat.') set_text(LANG, 'id:5', '#whois <user_id>/<user_name>: Devuelve el alias/id del usuario.') set_text(LANG, 'id:6', '#whois (reply): Devuelve la ID del usuario.') -- moderation.lua -- set_text(LANG, 'moderation:0', 18) set_text(LANG, 'moderation:1', '#add: respondiendo a un mensaje, añadirá a ese usuario al grupo o supergrupo actual.') set_text(LANG, 'moderation:2', '#add <id>/<username>: añade a un usuario, por su ID/alias, al grupo o supergrupo actual.') set_text(LANG, 'moderation:3', '#kick: respondiendo a un mensaje, expulsará a ese usuario del grupo o supergrupo actual.') set_text(LANG, 'moderation:4', '#kick <id>/<username>: expulsa a un usuario, por su ID/alias, del grupo o supergrupo actual.') set_text(LANG, 'moderation:5', '#kickme: autokick.') set_text(LANG, 'moderation:6', '#ban: respondiendo a un mensaje, expulsará y baneará a ese usuario del grupo o supergrupo actual.') set_text(LANG, 'moderation:7', '#ban <id>/<username>: expulsa a un usuario, por su ID/alias, e impide que éste vuelva a entrar al grupo o supergrupo.') set_text(LANG, 'moderation:8', '#unban: respondiendo a un mensaje, desbanea a ese usuario del grupo o supergrupo.') set_text(LANG, 'moderation:9', '#unban <id>/<username>: desbanea al usuario por su ID/alias del grupo o supergrupo.') set_text(LANG, 'moderation:10', '#gban: respondiendo a un mensaje, el usuario será baneado de todos los grupos y supergrupos.') set_text(LANG, 'moderation:11', '#gban <id>/<username>: expulsa y banea al usuario, por su ID/alias, de todos los grupos o supergrupos e impide que éste vuelva a entrar en todos los grupos y/o supergrupos.') set_text(LANG, 'moderation:12', '#ungban: respondiendo a un mensaje, quita el baneo de todos los grupos y/o supergrupos.') set_text(LANG, 'moderation:13', '#ungban <id>/<username>: quita el baneo al usuario, por su ID/alias, de todos los grupos y/o supergrupos.') set_text(LANG, 'moderation:14', '#mute: respondiendo a un mensaje, silencia al usuario eliminando sus mensajes en el supergrupo actual.') set_text(LANG, 'moderation:15', '#mute <id>/<username>: silencia a un usuario, por su ID/alias, eliminando sus mensajes en el supergrupo actual.') set_text(LANG, 'moderation:16', '#unmute: respondiendo a un mensaje, quita el silencio al usuario.') set_text(LANG, 'moderation:17', '#unmute <id>/<username>: quita el silencio al usuario, por su ID/alias, en el supergrupo actual.') set_text(LANG, 'moderation:18', '#rem: respondiendo a un mensaje, ese mensaje será borrado.') -- settings.lua -- set_text(LANG, 'settings:0', 19) set_text(LANG, 'settings:1', '#settings stickers enable/disable: cuando esté activo, todos los stickers serán borrados.') set_text(LANG, 'settings:2', '#settings links enable/disable: cuando esté activo, todos los links serán borrados.') set_text(LANG, 'settings:3', '#settings arabic enable/disable: cuando esté activo, todos mensajes con árabe/persa serán borrados.') set_text(LANG, 'settings:4', '#settings bots enable/disable: cuando esté activo, si alguien añade algún bot será expulsado.') set_text(LANG, 'settings:5', '#settings gifs enable/disable: cuando esté activo, todos los gifs serán borrados.') set_text(LANG, 'settings:6', '#settings photos enable/disable: cuando esté activo, todas las fotos serán borradas.') set_text(LANG, 'settings:7', '#settings audios enable/disable: cuando esté activo, todos los audios serán borrados.') set_text(LANG, 'settings:8', '#settings kickme enable/disable: cuando esté activo, los usuarios podrán autoexpulsarse.') set_text(LANG, 'settings:9', '#settings spam enable/disable: cuando esté activo, todos los enlaces de spam serán borrados') set_text(LANG, 'settings:10', '#settings setphoto enable/disable: cuando esté activo, si un usuario cambia la foto del grupo, el bot la cambiará por la foto guardada.') set_text(LANG, 'settings:11', '#settings setname enable/disable: cuando esté activo, si un usuario cambia el nombre del grupo, el bot lo cambiará por el nombre guardado.') set_text(LANG, 'settings:12', '#settings lockmember enable/disable: cuando esté activo, el bot expulsará a toda la gente que entre al grupo.') set_text(LANG, 'settings:13', '#settings floodtime <secs>: establece el tiempo de medición del flood.') set_text(LANG, 'settings:14', '#settings maxflood <secs>: establece el máximo de mensajes en un floodtime para ser considerado flood.') set_text(LANG, 'settings:15', '#setname <título del grupo>: el bot cambiará el nombre del grupo.') set_text(LANG, 'settings:16', '#setphoto <después envía la foto>: el bot cambiará la foto del grupo.') set_text(LANG, 'settings:17', '#lang <language (en, es...)>: cambia el idioma del bot.') set_text(LANG, 'settings:18', '#setlink <link>: guarda el link del grupo.') set_text(LANG, 'settings:19', '#link: muestra el link del grupo.') -- plugins.lua -- set_text(LANG, 'plugins:0', 4) set_text(LANG, 'plugins:1', '#plugins: muestra una lista de todos los plugins.') set_text(LANG, 'plugins:2', '#plugins <enable>/<disable> [plugin]: activa/desactiva el plugin especificado.') set_text(LANG, 'plugins:3', '#plugins <enable>/<disable> [plugin] chat: activa/desactiva el plugin especificado, solo en el actual grupo/supergrupo.') set_text(LANG, 'plugins:4', '#plugins reload: recarga todos los plugins.') -- version.lua -- set_text(LANG, 'version:0', 1) set_text(LANG, 'version:1', '#version: muestra la versión del bot.') -- version.lua -- set_text(LANG, 'rules:0', 1) set_text(LANG, 'rules:1', '#rules: muestra las reglas del chat.') if matches[1] == 'install' then return 'ℹ️ El lenguaje español ha sido instalado en su base de datos.' elseif matches[1] == 'update' then return 'ℹ️ El lenguaje español ha sido actualizado en su base de datos.' end else return "Este plugin requiere permisos de sudo." end end return { patterns = { '(install) (spanish_lang)$', '(update) (spanish_lang)$' }, run = run, }
gpl-2.0
mario0582/devenserver
data/movements/scripts/arenagoblet.lua
2
1282
function onStepIn(creature, item, position, fromPosition) local gobletPos = item:getPosition() if item.actionid == 42360 then if creature:getStorageValue(42360) ~= 1 then creature:setStorageValue(42360, 1) local goblet = Game.createItem(5807, 1, {x=gobletPos.x,y=gobletPos.y-1,z=gobletPos.z}) goblet:setAttribute(ITEM_ATTRIBUTE_DESCRIPTION, "It is given to the courageous victor of the barbarian arena greenhorn difficulty.\nAwarded to " .. creature:getName() .. ".") end elseif item.actionid == 42370 then if creature:getStorageValue(42370) ~= 1 then creature:setStorageValue(42370, 1) local goblet = Game.createItem(5806, 1, {x=gobletPos.x,y=gobletPos.y-1,z=gobletPos.z}) goblet:setAttribute(ITEM_ATTRIBUTE_DESCRIPTION, "It is given to the courageous victor of the barbarian arena scrapper difficulty.\nAwarded to " .. creature:getName() .. ".") end elseif item.actionid == 42380 then if creature:getStorageValue(42380) ~= 1 then creature:setStorageValue(42380, 1) local goblet = Game.createItem(5805, 1, {x=gobletPos.x,y=gobletPos.y-1,z=gobletPos.z}) goblet:setAttribute(ITEM_ATTRIBUTE_DESCRIPTION, "It is given to the courageous victor of the barbarian arena warlord difficulty.\nAwarded to " .. creature:getName() .. ".") end end end
gpl-2.0
Unknown8765/SpeedBot
bot/utils.lua
239
13499
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
valy012/safroid5
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_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*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
ozhanf/ozhanf----bot
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_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*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
telegrambot81/supergrup
plugins/sticker_maker.lua
7
2158
local function run(msg, matches) local text = URL.escape(matches[1]) local color = 'blue' if matches[2] == 'red' then color = 'red' elseif matches[2] == 'black' then color = 'black' elseif matches[2] == 'blue' then color = 'blue' elseif matches[2] == 'green' then color = 'green' elseif matches[2] == 'yellow' then color = 'yellow' elseif matches[2] == 'pink' then color = 'magenta' elseif matches[2] == 'orange' then color = 'Orange' elseif matches[2] == 'brown' then color = 'DarkOrange' end local font = 'mathrm' if matches[3] == 'bold' then font = 'mathbf' elseif matches[3] == 'italic' then font = 'mathit' elseif matches[3] == 'fun' then font = 'mathfrak' elseif matches[1] == 'arial' then font = 'mathrm' end local size = '700' if matches[4] == 'small' then size = '300' elseif matches[4] == 'larg' then size = '700' end local url = 'http://latex.codecogs.com/png.latex?'..'\\dpi{'..size..'}%20\\huge%20\\'..font..'{{\\color{'..color..'}'..text..'}}' local file = download_to_file(url,'file.webp') if msg.to.type == 'channel' then send_document('channel#id'..msg.to.id,file,ok_cb,false) else send_document('chat#id'..msg.to.id,file,ok_cb,false) end end return { patterns = { "^[/!#]sticker (.*) ([^%s]+) (.*) (small)$", "^[/!#]sticker (.*) ([^%s]+) (.*) (larg)$", "^[/!#]sticker (.*) ([^%s]+) (bold)$", "^[/!#]sticker (.*) (bold)$", "^[/!#]sticker (.*) ([^%s]+) (italic)$", "^[/!#]sticker (.*) ([^%s]+) (fun)$", "^[/!#]sticker (.*) ([^%s]+) (arial)$", "^[/!#]sticker (.*) (red)$", "[/!#]sticker (.*) (black)$", "^[/!#]sticker (.*) (blue)$", "^[/!#]sticker (.*) (green)$", "^[/!#]sticker (.*) (yellow)$", "^[/!#]sticker (.*) (pink)$", "^[/!#]sticker (.*) (orange)$", "^[/!#]sticker (.*) (brown)$", "^[/!#]sticker +(.*)$", }, run = run }
gpl-2.0
Beagle/wesnoth
data/ai/micro_ais/cas/ca_patrol.lua
26
6200
local AH = wesnoth.require "ai/lua/ai_helper.lua" local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua" local function get_patrol(cfg) local filter = cfg.filter or { id = cfg.id } local patrol = AH.get_units_with_moves { side = wesnoth.current.side, { "and", filter } }[1] return patrol end local ca_patrol = {} function ca_patrol:evaluation(ai, cfg) if get_patrol(cfg) then return cfg.ca_score end return 0 end function ca_patrol:execution(ai, cfg) local patrol = get_patrol(cfg) local patrol_vars = MAIUV.get_mai_unit_variables(patrol, cfg.ai_id) -- Set up waypoints, taking into account whether 'reverse' is set -- This works even the first time, when patrol_vars.patrol_reverse is not set yet cfg.waypoint_x = AH.split(cfg.waypoint_x, ",") cfg.waypoint_y = AH.split(cfg.waypoint_y, ",") local n_wp = #cfg.waypoint_x local waypoints = {} for i = 1,n_wp do if patrol_vars.patrol_reverse then waypoints[i] = { tonumber(cfg.waypoint_x[n_wp-i+1]), tonumber(cfg.waypoint_y[n_wp-i+1]) } else waypoints[i] = { tonumber(cfg.waypoint_x[i]), tonumber(cfg.waypoint_y[i]) } end end -- If not set, set next location (first move) -- This needs to be in WML format, so that it persists over save/load cycles if (not patrol_vars.patrol_x) then patrol_vars.patrol_x = waypoints[1][1] patrol_vars.patrol_y = waypoints[1][2] patrol_vars.patrol_reverse = false MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) end while patrol.moves > 0 do -- Check whether one of the enemies to be attacked is next to the patroller -- If so, don't move, but attack that enemy local adjacent_enemy = wesnoth.get_units { id = cfg.attack, { "filter_adjacent", { id = patrol.id } }, { "filter_side", {{ "enemy_of", { side = wesnoth.current.side } }} } }[1] if adjacent_enemy then break end -- Also check whether we're next to any unit (enemy or ally) which is on the next waypoint local unit_on_wp = wesnoth.get_units { x = patrol_vars.patrol_x, y = patrol_vars.patrol_y, { "filter_adjacent", { id = patrol.id } } }[1] for i,wp in ipairs(waypoints) do -- If the patrol is on a waypoint or adjacent to one that is occupied by any unit if ((patrol.x == wp[1]) and (patrol.y == wp[2])) or (unit_on_wp and ((unit_on_wp.x == wp[1]) and (unit_on_wp.y == wp[2]))) then if (i == n_wp) then -- Move him to the first one (or reverse route), if he's on the last waypoint -- Unless cfg.one_time_only is set if cfg.one_time_only then patrol_vars.patrol_x = waypoints[n_wp][1] patrol_vars.patrol_y = waypoints[n_wp][2] MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) else -- Go back to first WP or reverse direction if cfg.out_and_back then patrol_vars.patrol_x = waypoints[n_wp-1][1] patrol_vars.patrol_y = waypoints[n_wp-1][2] -- We also need to reverse the waypoints right here, as this might not be the end of the move patrol_vars.patrol_reverse = not patrol_vars.patrol_reverse MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) local tmp_wp = {} for j,wp2 in ipairs(waypoints) do tmp_wp[n_wp-j+1] = wp2 end waypoints = tmp_wp else patrol_vars.patrol_x = waypoints[1][1] patrol_vars.patrol_y = waypoints[1][2] MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) end end else -- ... else move him on toward the next waypoint patrol_vars.patrol_x = waypoints[i+1][1] patrol_vars.patrol_y = waypoints[i+1][2] MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) end end end -- If we're on the last waypoint on one_time_only is set, stop here if cfg.one_time_only and (patrol.x == waypoints[n_wp][1]) and (patrol.y == waypoints[n_wp][2]) then AH.checked_stopunit_moves(ai, patrol) else -- Otherwise move toward next WP local x, y = wesnoth.find_vacant_tile(patrol_vars.patrol_x, patrol_vars.patrol_y, patrol) local nh = AH.next_hop(patrol, x, y) if nh and ((nh[1] ~= patrol.x) or (nh[2] ~= patrol.y)) then AH.checked_move(ai, patrol, nh[1], nh[2]) else AH.checked_stopunit_moves(ai, patrol) end end if (not patrol) or (not patrol.valid) then return end end -- Attack unit on the last waypoint under all circumstances if cfg.one_time_only is set local adjacent_enemy if cfg.one_time_only then adjacent_enemy = wesnoth.get_units{ x = waypoints[n_wp][1], y = waypoints[n_wp][2], { "filter_adjacent", { id = patrol.id } }, { "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } } }[1] end -- Otherwise attack adjacent enemy (if specified) if (not adjacent_enemy) then adjacent_enemy = wesnoth.get_units{ id = cfg.attack, { "filter_adjacent", { id = patrol.id } }, { "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } } }[1] end if adjacent_enemy then AH.checked_attack(ai, patrol, adjacent_enemy) end if (not patrol) or (not patrol.valid) then return end AH.checked_stopunit_all(ai, patrol) end return ca_patrol
gpl-2.0
liruqi/bigfoot
Interface/AddOns/DBM-Nighthold/localization.en.lua
1
3065
local L --------------- -- Skorpyron -- --------------- L= DBM:GetModLocalization(1706) --------------------------- -- Chronomatic Anomaly -- --------------------------- L= DBM:GetModLocalization(1725) L:SetOptionLocalization({ InfoFrameBehavior = "Set information InfoFrame shows during encounter", TimeRelease = "Show players affected by Time Release", TimeBomb = "Show players affected by Time Bomb" }) --------------------------- -- Trilliax -- --------------------------- L= DBM:GetModLocalization(1731) ------------------ -- Spellblade Aluriel -- ------------------ L= DBM:GetModLocalization(1751) ------------------ -- Tichondrius -- ------------------ L= DBM:GetModLocalization(1762) L:SetMiscLocalization({ First = "First", Second = "Second", Third = "Third", Adds1 = "Underlings! Get in here!", Adds2 = "Show these pretenders how to fight!" }) ------------------ -- Krosus -- ------------------ L= DBM:GetModLocalization(1713) L:SetWarningLocalization({ warnSlamSoon = "Bridge break in %ds" }) L:SetOptionLocalization({ warnSlamSoon = DBM_CORE_AUTO_ANNOUNCE_OPTIONS.soon:format(205862) }) L:SetMiscLocalization({ MoveLeft = "Move Left", MoveRight = "Move Right" }) ------------------ -- High Botanist Tel'arn -- ------------------ L= DBM:GetModLocalization(1761) L:SetWarningLocalization({ warnStarLow = "Plasma Sphere is low" }) L:SetOptionLocalization({ warnStarLow = "Show special warning when Plasma Sphere is low (at ~25%)" }) ------------------ -- Star Augur Etraeus -- ------------------ L= DBM:GetModLocalization(1732) L:SetOptionLocalization({ ConjunctionYellFilter = "During $spell:205408, disable all other SAY messages and just spam the star sign message says instead until conjunction has ended" }) ------------------ -- Grand Magistrix Elisande -- ------------------ L= DBM:GetModLocalization(1743) L:SetTimerLocalization({ timerFastTimeBubble = "Fast Bubble (%d)", timerSlowTimeBubble = "Slow Bubble (%d)" }) L:SetOptionLocalization({ timerFastTimeBubble = "Show timer for $spell:209166 bubbles", timerSlowTimeBubble = "Show timer for $spell:209165 bubbles" }) L:SetMiscLocalization({ noCLEU4EchoRings = "Let the waves of time crash over you!", noCLEU4EchoOrbs = "You'll find time can be quite volatile.", prePullRP = "I foresaw your coming, of course. The threads of fate that led you to this place. Your desperate attempt to stop the Legion." }) ------------------ -- Gul'dan -- ------------------ L= DBM:GetModLocalization(1737) L:SetMiscLocalization({ mythicPhase3 = "Time to return the demon hunter's soul to his body... and deny the Legion's master a host!", prePullRP = "Ah yes, the heroes have arrived. So persistent. So confident. But your arrogance will be your undoing!" }) ------------- -- Trash -- ------------- L = DBM:GetModLocalization("NightholdTrash") L:SetGeneralLocalization({ name = "Nighthold Trash" })
mit
liruqi/bigfoot
Interface/AddOns/DBM-Party-Legion/EyeOfAzshara/Hatecoil.lua
1
2558
local mod = DBM:NewMod(1490, "DBM-Party-Legion", 3, 716) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 17471 $"):sub(12, -3)) mod:SetCreatureID(91789) mod:SetEncounterID(1811) mod:SetZone() mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_AURA_APPLIED 193698", "SPELL_CAST_START 193682 193597 193611" ) --TODO, maybe add a "get back in boss area warning" if you take Crackling THunder damage --TODO, more curse notes perhaps? Add special warning for player maybe? --[[ 1. Healer--193712+18 2. 3 dps--193716+24.5 3. healer--193712+16.5 4. Everyone--193717+30 5. 1 healer, 1 tank, 1 dps--193716+17 6. Everyone--193717+19 --]] local warnCurseofWitch = mod:NewTargetAnnounce(193698, 3) local specWarnStaticNova = mod:NewSpecialWarning("specWarnStaticNova", nil, DBM_CORE_AUTO_SPEC_WARN_OPTIONS.dodge:format(193597), nil, 3, 2) local specWarnFocusedLightning = mod:NewSpecialWarning("specWarnFocusedLightning", nil, DBM_CORE_AUTO_SPEC_WARN_OPTIONS.soon:format(193611), nil, 1) local specWarnAdds = mod:NewSpecialWarningSwitch(193682, "Tank", nil, nil, 1, 2) local yellCurseofWitch = mod:NewShortFadesYell(193698) local timerAddsCD = mod:NewCDTimer(47, 193682, nil, nil, nil, 1)--47-51 local timerStaticNovaCD = mod:NewCDTimer(34, 193597, nil, nil, nil, 2, nil, DBM_CORE_DEADLY_ICON) local timerFocusedLightningCD = mod:NewNextTimer(15.5, 193611, nil, nil, nil, 3) local countdownStaticNova = mod:NewCountdown(34, 193597) function mod:OnCombatStart(delay) timerStaticNovaCD:Start(10.5-delay) countdownStaticNova:Start(10.5-delay) timerAddsCD:Start(19-delay) end function mod:SPELL_AURA_APPLIED(args) local spellId = args.spellId if spellId == 193698 then warnCurseofWitch:CombinedShow(0.3, args.destName) if args:IsPlayer() then local _, _, _, _, _, _, expires = DBM:UnitDebuff("player", args.spellName) local debuffTime = expires - GetTime() yellCurseofWitch:Schedule(debuffTime-1, 1) yellCurseofWitch:Schedule(debuffTime-2, 2) yellCurseofWitch:Schedule(debuffTime-3, 3) end end end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 193682 then specWarnAdds:Show() specWarnAdds:Play("mobsoon") timerAddsCD:Start() elseif spellId == 193597 then specWarnStaticNova:Show() specWarnStaticNova:Play("findshelter") timerFocusedLightningCD:Start() countdownStaticNova:Start() specWarnFocusedLightning:Schedule(10)--5 seconds before focused lightning cast -- elseif spellId == 193611 then--Maybe not needed at all end end
mit
kaen/sutratman
unittest/test_mapdata.lua
1
1040
TestMapData = {} function TestMapData:testMapGenerationWatchdog() -- reset the state to thwart the global mapdata and on_generated mocking stm = nil minetest = nil dofile("mods/stm/init.lua") local generated_blocks = fixture('generated_blocks') local done = false -- register a callback and assert that it has fired table.insert(MapData.generation_callbacks, function() done = true end) for _, args in ipairs(generated_blocks) do MapData.on_generated(args.minp, args.maxp, args.blockseed) end assert(done) end function TestMapData:testMapGenerationWatchdogIncomplete() local generated_blocks = fixture('generated_blocks') local done = false -- register a callback and assert that it has fired table.insert(MapData.generation_callbacks, function() done = true end) for i, args in ipairs(generated_blocks) do -- bail early so the callback is never fired if i > (#generated_blocks / 2) then break end MapData.on_generated(args.minp, args.maxp, args.blockseed) end assert(not done) end
mit
mrbangi/kingproject
plugins/invite.lua
1
1196
do local function callbackres(extra, success, result) -- Callback for res_user in line 27 local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then -- Ignore bans send_large_msg(chat, 'User is banned.') elseif is_gbanned(result.id) then -- Ignore globall bans send_large_msg(chat, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) -- Add user on chat end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end --if not is_admin(msg) then -- For admins only ! --return 'Only admins can invite.' --end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^[!/]invtogp (.*)$" }, run = run } end
gpl-2.0