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
AdamGagorik/darkstar
scripts/zones/Port_Jeuno/npcs/Rinzei.lua
13
1355
----------------------------------- -- Area: Port Jeuno -- NPC: Rinzei -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Jeuno/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,18) == false) then player:startEvent(315); else player:startEvent(0x38); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 315) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",18,true); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Windurst_Walls/npcs/Naih_Arihmepp.lua
13
1472
----------------------------------- -- Area: Windurst Walls -- NPC: Naih Arihmepp -- Type: Standard NPC -- @pos -64.578 -13.465 202.147 239 ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,9) == false) then player:startEvent(0x01f4); else player:startEvent(0x0146); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x01f4) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",9,true); end end;
gpl-3.0
Firew0lf/FAT16-Lua
fat16.lua
1
14511
-- Warning: in order to work, the library need a "disk" object, which must provide this functions: -- disk:read(address, [size]): read [size] bytes from <address> -- disk:write(address, data): write <data> on the disk from the address <address> -- disk:flush(): save the changes on the disk, if some cache is used -- -- <address> is a value from 0 to sizeOfTheDisk-1 --- -- FAT16 support -- FAT16 support for Lunux -- -- @module FAT16 local mod = {} -- types documentation --- -- Partition -- FAT16 partition -- -- @type fatPartition --- -- BPB -- FAT16 Boot Paramter Block -- -- @type fatBPB --- -- Cluster Index -- FAT16 cluster index in fat -- -- @type fatClusterIndex --- -- File -- FAT16 file -- -- @type fatFile --- -- Directory -- FAT16 directory -- -- @type fatDirectory -- local functions local function bytesToNumber(str) local number = 0 for i=1, #str do number = number + (str:sub(i,i):byte() * 2^(8*(i-1))) end return number end local function numberToBytes(num, size) local hex = string.format("%x", num) if size and #hex < size*2 then while #hex < size*2 do hex = ("0"..hex) end end local str = "" for i=1, #hex, 2 do str = (str..string.char(tonumber(hex:sub(i,i+1), 16))) end return str:reverse() end --- -- BPB Parser, -- Extract the Boot Paramter Block from the disk -- -- @function parseBPB -- @param #disk disk Disk to extract from -- @return #fatBPB the disk's BPB local function parseBPB(disk) local raw = disk:read(0, 512) if #raw ~= 512 then return nil, "Disk smaller than 512 bytes." end local BPB = { jump = bytesToNumber(raw:sub(1, 3)), formater = raw:sub(4, 11), sectorSize = bytesToNumber(raw:sub(12, 13)), clusterSize = bytesToNumber(raw:sub(14, 14)), reservedSectors = bytesToNumber(raw:sub(15, 16)), fatNumber = raw:sub(17, 17):byte(), rootEntriesNumber = bytesToNumber(raw:sub(18, 19)), twoBytesSectorsNumber = bytesToNumber(raw:sub(20, 21)), diskType = raw:sub(22, 22):byte(), fatSize = bytesToNumber(raw:sub(23, 24)), sectorsPerTrack = bytesToNumber(raw:sub(25, 26)), headsNumber = bytesToNumber(raw:sub(27, 28)), hiddenSectors = bytesToNumber(raw:sub(29, 32)), FourBytesSectorsNumber = bytesToNumber(raw:sub(33, 36)), diskId = raw:sub(37, 37):byte(), reserved = raw:sub(38, 38):byte(), signature = raw:sub(39, 39):byte(), serial = bytesToNumber(raw:sub(40, 43)), diskName = raw:sub(44, 54), fatType = raw:sub(55, 62), bootCode = raw:sub(63, 510), isBootable = (raw:sub(511, 512) == "\x55\xAA"), } return BPB end --- -- FAT read interface -- Return the value of a FAT entry from it's index -- -- @function searchClusterInFAT -- @param #disk disk Disk to search from -- @param #fatBPB BPB FAT Infos -- @param #number index Index of the entry -- @return #number Value in the entry local function searchClusterInFAT(disk, BPB, index) if (index < 0) or (index > (BPB.fatSize*BPB.sectorSize/2)) then return nil, "Index out of range" end local offset = ((BPB.reservedSectors * BPB.sectorSize)) return bytesToNumber(disk:read(offset+(index*2), 2)) end --- -- FAT write interface -- Set the value of a FAT entry from it's index and a value -- -- @function setClusterInFAT -- @param #disk disk Disk to set to -- @param #fatBPB BPB FAT Infos -- @param #number index Index of the entry local function setClusterInFAT(disk, BPB, index, value) if (index < 0) or (index > (BPB.fatSize*BPB.sectorSize/2)) then return nil, "Index out of range" end local offset = ((BPB.reservedSectors * BPB.sectorSize)) local svalue = numberToBytes(value, 2) return disk:write(offset+(index*2), svalue) end --- -- Clusters lister -- List all the clusters in a file -- -- @function listFileClusters -- @param #fatPartition partition Partition where the file is stored -- @param #fatClusterIndex start First cluster of the file -- @return cluster list local function listFileClusters(partition, start) local clusters = {[1] = start} while clusters[#clusters] <= 0xFFEF do local cluster, err = searchClusterInFAT(partition.disk, partition.BPB, clusters[#clusters]) if cluster < 0x0002 then return nil, "Corrupted FAT" end clusters[#clusters+1] = cluster end clusters[#clusters] = nil if clusters[#clusters] == 0xFFF7 then --bad/hidden cluster clusters[#clusters] = nil end return clusters end local function setFileClusters(partition, clusters) for i=1, #clusters do setClusterInFAT(partition.disk, partition.BPB, clusters[i], (clusters[i+1] or 0xFFEF)) end end --- -- Get a cluster -- Get data from a cluster on the FAT -- -- @function getCluster -- @param #disk disk Disk -- @param #fatBPB BPB Disk's BPB -- @param #fatClusterIndex index Cluster to get -- @return #string Cluster data local function getCluster(disk, BPB, index) index = (index - 1) local offset = ((BPB.fatSize * BPB.sectorSize * BPB.fatNumber) + (BPB.rootEntriesNumber * 32)) --should be good local clusterSize = (BPB.sectorSize * BPB.clusterSize) return disk:read(offset + (index * clusterSize), clusterSize) end local function setCluster(disk, BPB, index, data) index = (index-1) local offset = ((BPB.fatSize * BPB.sectorSize * BPB.fatNumber) + (BPB.rootEntriesNumber * 32)) local clusterSize = (BPB.sectorSize * BPB.clusterSize) while #data < clusterSize do data = (data.."\0") end return disk:write(offset + (index * clusterSize), data) end local function searchEmptyCluster(partition) for i=2, (partition.BPB.fatSize*partition.BPB.sectorSize/2) do if searchClusterInFAT(partition.disk, partition.BPB, i) == 0x0000 then return i end end return nil, "FAT Full" end local function parseDirectoryEntry(entry) local data = { name = entry:sub(1, 8), extension = entry:sub(9, 11), attributes = entry:sub(12, 12):byte(), reserved = entry:sub(13, 13):byte(), createTime = entry:sub(14, 16), createDate = entry:sub(17, 18), accessDate = entry:sub(19, 20), accessTime = entry:sub(21, 22), modificationTime = entry:sub(23, 24), modificationDate = entry:sub(25, 26), firstCluster = bytesToNumber(entry:sub(27, 28)), size = bytesToNumber(entry:sub(29, 32)) } if data.name:sub(1, 1) == "\0" then return nil, "End" elseif data.name:sub(1, 1) == "\xE5" then return nil, "Deleted" end if data.attributes == 15 then return nil, "Meta-file" end data.name = data.name:gsub("\x05", "\xE5") --Seriously, "Y did U do dis" return data end local function makeDirectoryEntry(data) local entry = (data.name:gsub("\xE5", "\x05")..data.extension..string.char(data.attributes, data.reserved)..data.createTime..data.createDate..data.accessDate..data.accessTime..data.modificationTime..data.modificationDate) entry = (entry..numberToBytes(data.firstCluster, 2)..numberToBytes(data.size, 4)) return entry end local function getRootDir(partition) local offset = (partition.BPB.sectorSize * ((partition.BPB.fatSize * partition.BPB.fatNumber) + 1)) local list = {} local err = false for i=1, partition.BPB.rootEntriesNumber do list[#list+1], err = parseDirectoryEntry(partition.disk:read(offset + (i*32), 32)) if not list[i] and err == "End" then break end end return list end local function setRootDir(partition, entries) if #entries > partition.BPB.rootEntriesNumber then return nil, "Root entries number excessed" end local offset = (partition.BPB.sectorSize * ((partition.BPB.fatSize * partition.BPB.fatNumber) + 1)) for i=1, partition.BPB.rootEntriesNumber do if i > #entries then partition.disk:write(offset + (i*32), "\xE5") else partition.disk:write(offset + (i*32), makeDirectoryEntry(entries[i])) end end end local function getDir(partition, start, size) local clusters = listFileClusters(partition, start) local data = "" for i=1, #clusters do data = (data..getCluster(partition.disk, partition.BPB, clusters[i])) end --data = data:sub(1, (size or #data)) local entries = {} local err for i=1, math.floor(#data/32) do entries[#entries+1], err = parseDirectoryEntry(data:sub(i*32+1, i*32+32)) if err == "End" then break end end return entries end local function setDir(partition, start, size, entries) local clusters = listFileClusters(partition, start) while #entries > (#clusters*partition.BPB.sectorSize*partition.BPB.clusterSize/32) do local nextCluster, err = searchEmptyCluster(partition) if not nextCluster then return nil, err end clusters[#clusters+1] = nextCluster end while #entries < (#clusters*partition.BPB.sectorSize*partition.BPB.clusterSize/32) do setClusterInFAT(clusters[#clusters], 0) clusters[#clusters] = nil end local clusterSize = (partition.BPB.sectorSize*partition.BPB.clusterSize) for i=1, #entries do local cluster = clusters[math.floor(i*clusterSize/32)] partition.disk:write((cluster*clusterSize)+(i*32), makeDirectoryEntry(entries[i])) end end local function resolvePath(partition, path) --Directory searching part local dirs = {} local file = false for e in string.gmatch(path, "[^/]+") do dirs[#dirs+1] = e end if path:sub(-1,-1) ~= "/" then file = dirs[#dirs] dirs[#dirs] = nil end local dir = getRootDir(partition) for level = 1, #dirs do for i=1, (#dir) do if ((dir[i].name.."."..dir[i].extension) == dirs[level]) and (bit32.band(dir[i].attributes, 0x10) == 0x10) then dir = getDir(partition, dir[i].firstCluster, dir[i].size) i=1 --reset the counter break --go to the next level elseif i == #dir then return nil, ("No such directory: "..dirs[level]) end end end if not file then return (dirs[#dirs] or "/"), dir end --File searching part for i=1, #dir do if (dir[i].name.."."..dir[i].extension == file) then return file, dir[i] elseif i==#dir then return nil, "No such file" end end end local function getFileBytes(file, size, stop) --start from file.seek local tsize = (file.size + #file.buff) if file.aseek > (tsize) then return nil, "End of file" end if (file.aseek + size) > tsize then size = (size-(tsize-file.aseek)) end local offset = (file.partition.BPB.sectorSize*((file.partition.BPB.fatSize*file.partition.BPB.fatNumber)+file.partition.BPB.reservedSectors))+(file.partition.BPB.rootEntriesNumber*32) local buff = "" local clusterSize = (file.partition.BPB.clusterSize * file.partition.BPB.sectorSize) for i=1, size do if file.aseek <= (file.size) then --read from the disk local clusterIndex = math.ceil(file.aseek/clusterSize) local cluster = file.clusters[clusterIndex]-2 local addr = offset+((clusterSize*cluster)+(file.aseek%clusterSize)) buff = (buff..file.partition.disk:read(addr, 1)) else --read from the file buffer local buffindex = (file.aseek-file.size) buff = (buff..file.buff:sub(buffindex,buffindex)) end if stop and (buff:sub(-1, -1)):match(stop) then buff=buff:sub(1,-2) break end file.aseek = (file.aseek+1) end return buff end local function setFileBytes(file, data) end -- module functions function mod.open(partition, path, mode) local name, details = resolvePath(partition, path) if not name then return nil, details end local clusters = listFileClusters(partition, details.firstCluster) local file = {partition=partition, path=path, mode=mode, aseek=1, vbuff="full", buff="", clusters=clusters, size=details.size} if mode:sub(1,1) == "w" then file.size = 0 elseif mode:sub(1,1) == "a" then file.aseek = file.size + 1 end function file.read(self, pattern) if not (self.mode:sub(1,1) == "r" or self.mode:find("+")) then return nil, "Write only mode" end if type(pattern) == "number" then return getFileBytes(self, pattern) elseif pattern == "*a" then return getFileBytes(self, (self.size-self.aseek+#file.buff)) elseif pattern == "*l" then return getFileBytes(self, (self.size-self.aseek), "\n") elseif pattern == "*L" then return (getFileBytes(self, (self.size-self.aseek), "\n").."\n") elseif pattern == "*n" then local n = nil while not n do getFileBytes(self, (self.size-self.aseek), "[%d%-]") local f=getFileBytes(self, (self.size-self.aseek), "[^%d^%.^%-^%e]") if not f then return nil end n = tonumber(f) end return n else return nil, "Bad pattern" end end function file.write(self, data) if file.aseek < file.size then return nil, "Read-only part" end local start = (file.aseek - file.size) self.buff = (self.buff:sub(1,start)..data..self.buff:sub(start+#data,-1)) return self end function file.seek(self, mode, arg) if (type(arg) == "number") and arg > (self.size + #self.buff) then return nil, "Number too high" end if mode == "set" and type(arg) == "number" then self.aseek = arg+1 elseif mode == "cur" and type(arg) == "number" then self.aseek = (self.aseek + arg) else return nil, "Bad mode" end return self.aseek-1 end function file.flush(self) end function file.close(self) for n,v in pairs(self) do self[n] = nil end end function file.setvbuff(self, mode) self:flush() if (mode == nil or mode == "full" or mode == "line" or mode == "none") then self.vbuff = (mode or self.vbuff) return self.vbuff end return nil, "Bad buff mode" end return file end function mod.list(self, path, details) local data path, data = resolvePath(self, path) if not path then return nil, data end local list = {} for n,v in pairs(data) do list[n] = {name=string.format("%-8s.%-3s", v.name, v.extension), attributes=v.attributes, size=v.size, isDirectory=(bit32.band(v.attributes, 0x10) == 0x10)} end return path, ((details and data) or list) end function mod.remove(self, path) end function mod.rename(self, from, to) end function mod.tmpname(self) return (tostring(os.clock()):sub(-8, -1)..".tmp") end function mod.mount(self, disk) if self.disk then return nil, "Already mounted" end local BPB, err = parseBPB(disk) if err then return err end local partition = {disk=disk, BPB=BPB, err=err} for n,v in pairs(self) do partition[n] = v end return partition end function mod.umount(partition) partition.disk:flush() partition = {disk=partition.disk} end return mod
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Northern_San_dOria/npcs/Synergy_Engineer.lua
13
1071
----------------------------------- -- Area: Northern San d'Oria -- NPC: Synergy Engineer -- Type: Standard NPC -- @zone: 231 -- @pos -123.000 10.5 244.000 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2afa); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Port_Bastok/npcs/Galvin.lua
17
1407
----------------------------------- -- Area: Port Bastok -- NPC: Galvin -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,GALVIN_SHOP_DIALOG); stock = { 0x1020, 4445,1, --Ether 0x1037, 736,2, --Echo Drops 0x1010, 837,2, --Potion 0x43A6, 3,2, --Wooden Arrow 0x1036, 2387,3, --Eye Drops 0x1034, 290,3, --Antidote 0x43A8, 7,3, --Iron Arrow 0x43B8, 5,3 --Crossbow Bolt } showNationShop(player, BASTOK, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Rubahah.lua
32
1388
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Rubahah -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local stock = { 629, 48, -- Millioncorn 2237, 60, -- Imperial Flour (available only if AC is in the Al Zahbi) 2214, 68, -- Imperial Rice (available only if AC is in the Al Zahbi) 2271, 316 -- Coffee Beans (available only if AC is in the Al Zahbi) } showShop(player, STATIC, stock); player:showText(npc,RUBAHAH_SHOP_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
SwadicalRag/banana
lua/banana/init.lua
1
1357
local function include(name) if bFS then bFS:RunFile(name) else _G.include(name:sub(2,-1)) AddCSLuaFile(name:sub(2,-1)) end end -- STAGE 1 include("/banana/banana.lua") banana.isGMod = gmod and true if banana.isGMod then AddCSLuaFile() end include("/banana/timer/cpu.lua") include("/banana/io/outputwriter.lua") include("/banana/io/logger.lua") include("/banana/lua/loader.lua") banana.Logger = banana.New("Logger") banana.Logger:SetTag("banana") banana.Logger:Log("Initialising...") banana.Loader = banana.New("Loader") banana.Loader:SetTag("bananaLoader") banana.Loader:SetLoaded("/banana/banana.lua",true) banana.Loader:SetLoaded("/banana/init.lua",true) banana.Loader:SetLoaded("/banana/timer/cpu.lua",true) banana.Loader:SetLoaded("/banana/io/outputwriter.lua",true) banana.Loader:SetLoaded("/banana/io/logger.lua",true) banana.Loader:SetLoaded("/banana/lua/loader.lua",true) banana.Loader:LoadFolderRecursive("/banana/") banana.Logger:Log("banana has successfully been planted!") banana.Loader:LoadFolder("/autobanana/") banana.Loader:LoadFolder("/autobanana/shared/") if SERVER then banana.Loader:LoadFolder("/autobanana/server/",true) banana.Loader:ShareFolder("/autobanana/client/") else banana.Loader:LoadFolder("/autobanana/client/") end banana.Logger:Log("autobanana load complete!")
mit
sjznxd/lc-20130204
modules/niu/luasrc/model/cbi/niu/network/wlanwan.lua
50
9208
--[[ LuCI - Lua Configuration Interface Copyright 2009 Steven Barth <steven@midlink.org> Copyright 2009 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$ ]]-- local fs = require "nixio.fs" local uci = require "luci.model.uci" local nixio = require "nixio" local iwinfo = require "iwinfo" local bridge local iface = "client" local net = "wan" if arg[1] == "bridge" then bridge = true iface = "bridge" net = "lan" end local cursor = uci.inst local state = uci.inst_state cursor:unload("wireless") state:unload("wireless") local has_ipv6 = fs.access("/proc/net/ipv6_route") local device = cursor:get("wireless", iface, "device") local hwtype = cursor:get("wireless", device, "type") -- Bring up interface and scan -- if not state:get("wireless", iface, "network") then local olduci = uci.cursor(nil, "") local oldcl = olduci:get_all("wireless", iface) olduci:unload("wireless") local newuci = uci.cursor() local newcl = newuci:get_all("wireless", iface) newcl.network = net local proc = nixio.fork() if proc == 0 then newuci:delete("wireless", iface, "ssid") newuci:commit("wireless") nixio.exec("/sbin/wifi", "up", device) os.exit(1) end nixio.wait(proc) newuci:delete("wireless", iface) newuci:section("wireless", "wifi-iface", iface, oldcl) newuci:commit("wireless") newuci:tset("wireless", iface, newcl) newuci:save("wireless") newuci:unload("wireless") state:unload("wireless") end local ifname = state:get("wireless", iface, "ifname") or "wlan0dummy" local iwlib = iwinfo.type(ifname) and iwinfo[iwinfo.type(ifname)] local suggest = {} local encrdep = { none = {{["!default"] = 1}}, wep = {{["!default"] = 1}}, psk = {{["!default"] = 1}}, psk2 = {{["!default"] = 1}}, wpa = {{["!default"] = 1}}, wpa2 = {{["!default"] = 1}} } if iwlib then suggest = iwlib.scanlist(ifname) end -- Form definition -- m2 = Map("wireless", translate("Configure WLAN-Adapter for Client Connection"), bridge and ("<strong>" .. translate([[It is absolutely necessary that the network you are joining supports and allows bridging (WDS) otherwise your connection will fail.]]) .. "</strong> " .. translate([[Note: You can use the access point wizard to configure your private access point to increase the range of the network you are connected to.]])) or "") s = m2:section(NamedSection, iface, "wifi-iface", translate("Wireless Settings")) s.addremove = false s:tab("general", translate("General Settings")) s:tab("expert", translate("Expert Settings")) local ssid = s:taboption("general", Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) ssid.rmempty = false for _, v in ipairs(suggest) do if v.mode == "Master" then ssid:value(v.ssid) if not v.wep then encrdep.wep[#encrdep.wep+1] = {ssid = v.ssid, ["!reverse"] = 1} end if v.wpa ~= 1 or (v.wpa == 1 and v.auth_suites[1] ~= "802.1x") then encrdep.wpa[#encrdep.wpa+1] = {ssid = v.ssid, ["!reverse"] = 1} end if v.wpa ~= 1 or (v.wpa == 1 and v.auth_suites[1] ~= "PSK") then encrdep.psk[#encrdep.psk+1] = {ssid = v.ssid, ["!reverse"] = 1} end if not v.wpa or v.wpa < 2 or (v.wpa >= 2 and v.auth_suites[1] ~= "802.1x") then encrdep.wpa2[#encrdep.wpa2+1] = {ssid = v.ssid, ["!reverse"] = 1} end if not v.wpa or v.wpa < 2 or (v.wpa >= 2 and v.auth_suites[1] ~= "PSK") then encrdep.psk2[#encrdep.psk2+1] = {ssid = v.ssid, ["!reverse"] = 1} end if v.wpa or v.wep then encrdep.none[#encrdep.none+1] = {ssid = v.ssid, ["!reverse"] = 1} end end end mode = s:taboption("expert", ListValue, "mode", translate("Operating Mode")) mode.override_values = true mode:value("sta", translate("Client")) encr = s:taboption("general", ListValue, "encryption", translate("Encryption")) if hwtype == "mac80211" then if not bridge then mode:value("mesh", translate("Mesh (802.11s)")) local meshid = s:taboption("expert", Value, "mesh_id", translate("Mesh ID")) meshid:depends("mode", "mesh") end local ps = s:taboption("expert", Flag, "powersave", translate("Enable Powersaving")) ps:depends("mode", "sta") elseif hwtype == "atheros" then s:taboption("expert", Flag, "bursting", translate("Allow Burst Transmissions")) end -- Encryption -- encr.override_values = true encr.override_depends = true encr:value("none", "No Encryption", unpack(encrdep.none)) encr:value("wep", "WEP", unpack(encrdep.wep)) if hwtype == "atheros" or hwtype == "mac80211" or hwtype == "prism2" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") or os.getenv("LUCI_SYSROOT") if supplicant then encr:value("psk", "WPA", unpack(encrdep.psk)) encr:value("wpa", "WPA-EAP", unpack(encrdep.wpa)) encr:value("psk2", "WPA2", unpack(encrdep.psk2)) encr:value("wpa2", "WPA2-EAP (802.11i)", unpack(encrdep.wpa2)) end elseif hwtype == "broadcom" then encr:value("psk", "WPA", unpack(encrdep.psk)) encr:value("psk2", "WPA2", unpack(encrdep.psk2)) end key = s:taboption("general", Value, "key", translate("Password")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key.rmempty = true key.password = true if hwtype == "atheros" or hwtype == "mac80211" or hwtype == "prism2" then eaptype = s:taboption("general", ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({encryption="wpa"}) eaptype:depends({encryption="wpa2"}) cacert = s:taboption("general", FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({encryption="wpa"}) cacert:depends({encryption="wpa2"}) privkey = s:taboption("general", FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({eap_type="TLS", encryption="wpa2"}) privkey:depends({eap_type="TLS", encryption="wpa"}) privkeypwd = s:taboption("general", Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({eap_type="TLS", encryption="wpa"}) auth = s:taboption("general", Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({eap_type="PEAP", encryption="wpa2"}) auth:depends({eap_type="PEAP", encryption="wpa"}) auth:depends({eap_type="TTLS", encryption="wpa2"}) auth:depends({eap_type="TTLS", encryption="wpa"}) identity = s:taboption("general", Value, "identity", translate("Identity")) identity:depends({eap_type="PEAP", encryption="wpa2"}) identity:depends({eap_type="PEAP", encryption="wpa"}) identity:depends({eap_type="TTLS", encryption="wpa2"}) identity:depends({eap_type="TTLS", encryption="wpa"}) password = s:taboption("general", Value, "password", translate("Password")) password:depends({eap_type="PEAP", encryption="wpa2"}) password:depends({eap_type="PEAP", encryption="wpa"}) password:depends({eap_type="TTLS", encryption="wpa2"}) password:depends({eap_type="TTLS", encryption="wpa"}) end if not bridge then m = Map("network") s = m:section(NamedSection, net, "interface", translate("Address Settings")) s.addremove = false s:tab("general", translate("General Settings")) s:tab("expert", translate("Expert Settings")) p = s:taboption("general", ListValue, "proto", "Connection Type") p.override_scheme = true p.default = "dhcp" p:value("dhcp", "Automatic Configuration (DHCP)") p:value("static", "Static Configuration") ipaddr = s:taboption("general", Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) ipaddr.rmempty = true ipaddr:depends("proto", "static") nm = s:taboption("general", Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")) nm.rmempty = true nm:depends("proto", "static") nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") gw = s:taboption("general", Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) gw:depends("proto", "static") gw.rmempty = true bcast = s:taboption("expert", Value, "bcast", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Broadcast")) bcast:depends("proto", "static") if has_ipv6 then ip6addr = s:taboption("expert", Value, "ip6addr", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix")) ip6addr:depends("proto", "static") ip6gw = s:taboption("expert", Value, "ip6gw", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")) ip6gw:depends("proto", "static") end dns = s:taboption("expert", Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server")) dns:depends("peerdns", "") mtu = s:taboption("expert", Value, "mtu", "MTU") mtu.isinteger = true mac = s:taboption("expert", Value, "macaddr", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) return m2, m else return m2 end
apache-2.0
teamactivebot/team-active
libs/url.lua
567
9183
--[[ Copyright 2004-2007 Diego Nehab. 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. ]] ----------------------------------------------------------------------------- -- URI parsing, composition and relative URL resolution -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $ ----------------------------------------------------------------------------- -- updated for a module()-free world of 5.3 by slact local string = require("string") local base = _G local table = require("table") local Url={} Url._VERSION = "URL 1.0.2" function Url.escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end function Url.unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function Url.parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query stringing url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then parsed.host = authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function Url.build(parsed) local ppath = Url.parse_path(parsed.path or "") local url = Url.build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end -- Builds a absolute URL from a base and a relative URL according to RFC 2396 function Url.absolute(base_url, relative_url) if base.type(base_url) == "table" then base_parsed = base_url base_url = Url.build(base_parsed) else base_parsed = Url.parse(base_url) end local relative_parsed = Url.parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return Url.build(relative_parsed) end end -- Breaks a path into its segments, unescaping the segments function Url.parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = Url.unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end -- Builds a path component from its segments, escaping protected characters. function Url.build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return Url
gpl-2.0
mahmedhany128/Mr_BOT
libs/url.lua
567
9183
--[[ Copyright 2004-2007 Diego Nehab. 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. ]] ----------------------------------------------------------------------------- -- URI parsing, composition and relative URL resolution -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $ ----------------------------------------------------------------------------- -- updated for a module()-free world of 5.3 by slact local string = require("string") local base = _G local table = require("table") local Url={} Url._VERSION = "URL 1.0.2" function Url.escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end function Url.unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function Url.parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query stringing url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then parsed.host = authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function Url.build(parsed) local ppath = Url.parse_path(parsed.path or "") local url = Url.build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end -- Builds a absolute URL from a base and a relative URL according to RFC 2396 function Url.absolute(base_url, relative_url) if base.type(base_url) == "table" then base_parsed = base_url base_url = Url.build(base_parsed) else base_parsed = Url.parse(base_url) end local relative_parsed = Url.parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return Url.build(relative_parsed) end end -- Breaks a path into its segments, unescaping the segments function Url.parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = Url.unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end -- Builds a path component from its segments, escaping protected characters. function Url.build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return Url
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/_5eb.lua
13
1869
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Gate: Magical Gizmo -- Involved In Mission: Full Moon Fountain -- @pos -291 0 -659 194 ----------------------------------- package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Outer_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CurrentMission = player:getCurrentMission(WINDURST); local MissionStatus = player:getVar("MissionStatus"); if (CurrentMission == FULL_MOON_FOUNTAIN and MissionStatus == 1 and player:hasKeyItem(SOUTHWESTERN_STAR_CHARM)) then SpawnMob(17572197) -- Jack of Cups SpawnMob(17572198) -- Jack of Batons SpawnMob(17572199) -- Jack of Swords SpawnMob(17572200) -- Jack of Coins elseif (CurrentMission == FULL_MOON_FOUNTAIN and MissionStatus == 2) then player:startEvent(0x0044) else player:messageSpecial(DOOR_FIRMLY_SHUT); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0044) then player:setVar("MissionStatus",3); player:delKeyItem(SOUTHWESTERN_STAR_CHARM); end end;
gpl-3.0
flybird119/Atlas
lib/proxy/commands.lua
43
3477
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] module("proxy.commands", package.seeall) --- -- map the constants to strings -- lua starts at 1 local command_names = { "COM_SLEEP", "COM_QUIT", "COM_INIT_DB", "COM_QUERY", "COM_FIELD_LIST", "COM_CREATE_DB", "COM_DROP_DB", "COM_REFRESH", "COM_SHUTDOWN", "COM_STATISTICS", "COM_PROCESS_INFO", "COM_CONNECT", "COM_PROCESS_KILL", "COM_DEBUG", "COM_PING", "COM_TIME", "COM_DELAYED_INSERT", "COM_CHANGE_USER", "COM_BINLOG_DUMP", "COM_TABLE_DUMP", "COM_CONNECT_OUT", "COM_REGISTER_SLAVE", "COM_STMT_PREPARE", "COM_STMT_EXECUTE", "COM_STMT_SEND_LONG_DATA", "COM_STMT_CLOSE", "COM_STMT_RESET", "COM_SET_OPTION", "COM_STMT_FETCH", "COM_DAEMON" } --- -- split a MySQL command packet into its parts -- -- @param packet a network packet -- @return a table with .type, .type_name and command specific fields function parse(packet) local cmd = {} cmd.type = packet:byte() cmd.type_name = command_names[cmd.type + 1] if cmd.type == proxy.COM_QUERY then cmd.query = packet:sub(2) elseif cmd.type == proxy.COM_QUIT or cmd.type == proxy.COM_PING or cmd.type == proxy.COM_SHUTDOWN then -- nothing to decode elseif cmd.type == proxy.COM_STMT_PREPARE then cmd.query = packet:sub(2) -- the stmt_handler_id is at the same position for both STMT_EXECUTE and STMT_CLOSE elseif cmd.type == proxy.COM_STMT_EXECUTE or cmd.type == proxy.COM_STMT_CLOSE then cmd.stmt_handler_id = string.byte(packet, 2) + (string.byte(packet, 3) * 256) + (string.byte(packet, 4) * 256 * 256) + (string.byte(packet, 5) * 256 * 256 * 256) elseif cmd.type == proxy.COM_FIELD_LIST then cmd.table = packet:sub(2) elseif cmd.type == proxy.COM_INIT_DB or cmd.type == proxy.COM_CREATE_DB or cmd.type == proxy.COM_DROP_DB then cmd.schema = packet:sub(2) elseif cmd.type == proxy.COM_SET_OPTION then cmd.option = packet:sub(2) else print("[debug] (command) unhandled type name:" .. tostring(cmd.type_name) .. " byte:" .. tostring(cmd.type)) end return cmd end function pretty_print(cmd) if cmd.type == proxy.COM_QUERY or cmd.type == proxy.COM_STMT_PREPARE then return ("[%s] %s"):format(cmd.type_name, cmd.query) elseif cmd.type == proxy.COM_INIT_DB then return ("[%s] %s"):format(cmd.type_name, cmd.schema) elseif cmd.type == proxy.COM_QUIT or cmd.type == proxy.COM_PING or cmd.type == proxy.COM_SHUTDOWN then return ("[%s]"):format(cmd.type_name) elseif cmd.type == proxy.COM_FIELD_LIST then -- should have a table-name return ("[%s]"):format(cmd.type_name) elseif cmd.type == proxy.COM_STMT_EXECUTE then return ("[%s] %s"):format(cmd.type_name, cmd.stmt_handler_id) end return ("[%s] ... no idea"):format(cmd.type_name) end
gpl-2.0
AdamGagorik/darkstar
scripts/globals/items/orange_kuchen_+1.lua
18
1311
----------------------------------------- -- ID: 4332 -- Item: orange_kuchen_+1 -- Food Effect: 4Hrs, All Races ----------------------------------------- -- MP % 13 (cap 80) -- MP Recovered While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4332); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 13); target:addMod(MOD_FOOD_MP_CAP, 80); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 13); target:delMod(MOD_FOOD_MP_CAP, 80); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Quicksand_Caves/npcs/Treasure_Coffer.lua
13
4643
----------------------------------- -- Area: Quicksand Caves -- NPC: Treasure Coffer -- @zone 208 -- @pos 615 -6 -681 ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Quicksand_Caves/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1054,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1054,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local mJob = player:getMainJob(); local zone = player:getZoneID(); if (player:hasKeyItem(MAP_OF_THE_QUICKSAND_CAVES) == false) then questItemNeeded = 3; end local listAF = getAFbyZone(zone); for nb = 1,table.getn(listAF),3 do if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then questItemNeeded = 2; break end end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 3) then player:addKeyItem(MAP_OF_THE_QUICKSAND_CAVES); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_QUICKSAND_CAVES); -- Map of the Quicksand Caves (KI) elseif (questItemNeeded == 2) then for nb = 1,table.getn(listAF),3 do if (mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1054); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Ponono.lua
13
1062
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ponono -- Type: Standard NPC -- @zone: 94 -- @pos 156.069 -0.001 -15.667 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00c1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Windurst_Woods/npcs/Taraihi-Perunhi.lua
12
1682
----------------------------------- -- Area: Windurst Woods -- NPC: Taraihi-Perunhi -- Only sells when Windurst controlls Derfland Region -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/events/harvest_festivals") require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(DERFLAND); if (RegionOwner ~= WINDURST) then player:showText(npc,TARAIHIPERUNHI_CLOSED_DIALOG); else player:showText(npc,TARAIHIPERUNHI_OPEN_DIALOG); stock = { 0x1100, 128, --Derfland Pear 0x0269, 142, --Ginger 0x11C1, 62, --Gysahl Greens 0x0584, 1656, --Olive Flower 0x0279, 14, --Olive Oil 0x03B7, 110 --Wijnruit } showShop(player,WINDURST,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Northern_San_dOria/npcs/Fantarviont.lua
13
1414
----------------------------------- -- Area: Northern San d'Oria -- NPC: Fantarviont -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x029f); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Alzadaal_Undersea_Ruins/Zone.lua
16
6641
----------------------------------- -- -- Zone: Alzadaal_Undersea_Ruins (72) -- ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/besieged"); require("scripts/globals/settings"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -329, -2, 483,-323, 0, 489); -- map 1 SE porter zone:registerRegion(2, -477, -2, 631,-471, 0, 636); -- map 1 NW porter zone:registerRegion(3, 110, -2,-556, 116, 0,-551); -- map 2 west porter (white) zone:registerRegion(4, 30, -2, 750, 36, 0, 757); -- map 3 west porter (blue) zone:registerRegion(5, 83, -2, 750, 90, 0, 757); -- map 3 east porter (white) zone:registerRegion(6, -329, -2, 150,-323, 0, 156); -- map 4 porter (white) zone:registerRegion(7, -208, -2,-556,-202, 0,-551); -- map 5 porter (white) zone:registerRegion(8, 323, -2, 591, 329, 0, 598); -- map 6 east porter (white) zone:registerRegion(9, 270, -2, 591, 276, 0, 598); -- map 6 west porter (blue) zone:registerRegion(10, 442, -2,-557, 450, 0,-550); -- map 7 porter (white) zone:registerRegion(11, -63,-10, 56, -57,-8, 62); -- map 8 NW/Arrapago porter zone:registerRegion(12, 17, -6, 56, 23,-4, 62); -- map 8 NE/Silver Sea/Khim porter zone:registerRegion(13, -63,-10, -23, -57,-8, -16); -- map 8 SW/Zhayolm/bird camp porter zone:registerRegion(14, 17, -6, -23, 23,-4, -16); -- map 8 SE/Bhaflau Porter zone:registerRegion(15,-556, -2, -77,-550, 0, -71); -- map 9 east porter (white) zone:registerRegion(16,-609, -2, -77,-603, 0, -71); -- map 9 west porter (blue) zone:registerRegion(17, 643, -2,-289, 649, 0,-283); -- map 10 east porter (blue) zone:registerRegion(18, 590, -2,-289, 597, 0,-283); -- map 10 west porter (white) zone:registerRegion(19, 603, -2, 522, 610, 0, 529); -- map 11 east porter (blue) zone:registerRegion(20, 550, -2, 522, 557, 0, 529); -- map 11 west porter (white) zone:registerRegion(21,-556, -2,-489,-550, 0,-483); -- map 12 east porter (white) zone:registerRegion(22,-610, -2,-489,-603, 0,-483); -- map 12 west porter (blue) zone:registerRegion(23,382, -1,-582,399, 1,-572); -- mission 9 TOAU end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(222.798, -0.5, 19.872, 0); end return cs; end; ----------------------------------- -- afterZoneIn ----------------------------------- function afterZoneIn(player) player:entityVisualPacket("1pa1"); player:entityVisualPacket("1pb1"); player:entityVisualPacket("2pb1"); end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) player:startEvent(204); end, [2] = function (x) player:startEvent(205); end, [3] = function (x) player:startEvent(201); end, [4] = function (x) player:startEvent(203); end, [5] = function (x) player:startEvent(202); end, [6] = function (x) player:startEvent(206); end, [7] = function (x) player:startEvent(211); end, [8] = function (x) player:startEvent(200); end, [9] = function (x) player:startEvent(201); end, [10] = function (x) player:startEvent(213); end, [11] = function (x) player:startEvent(218); end, [12] = function (x) player:startEvent(221); end, [13] = function (x) player:startEvent(219); end, [14] = function (x) player:startEvent(220); end, [15] = function (x) player:startEvent(207); end, [16] = function (x) player:startEvent(208); end, [17] = function (x) player:startEvent(214); end, [18] = function (x) player:startEvent(207); end, [19] = function (x) player:startEvent(202); end, [20] = function (x) player:startEvent(207); end, [21] = function (x) player:startEvent(207); end, [22] = function (x) player:startEvent(210); end, [23] = function (x) if (player:getCurrentMission(TOAU) == UNDERSEA_SCOUTING) then player:startEvent(1, getMercenaryRank(player)); end end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1 and option == 10) then -- start player:updateEvent(0,0,0,0,0,0,0,0); elseif (csid == 1 and option == 1) then -- windows player:setLocalVar("UnderseaScouting", player:getLocalVar("UnderseaScouting")+1); player:updateEvent(player:getLocalVar("UnderseaScouting"),0,0,0,0,0,0,0); elseif (csid == 1 and option == 2) then -- pillars player:setLocalVar("UnderseaScouting", player:getLocalVar("UnderseaScouting")+2); player:updateEvent(player:getLocalVar("UnderseaScouting"),0,0,0,0,0,0,0); elseif (csid == 1 and option == 3) then -- floor player:setLocalVar("UnderseaScouting", player:getLocalVar("UnderseaScouting")+4); player:updateEvent(player:getLocalVar("UnderseaScouting"),0,0,0,0,0,0,0); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1) then player:addKeyItem(ASTRAL_COMPASS); player:completeMission(TOAU,UNDERSEA_SCOUTING); player:addMission(TOAU,ASTRAL_WAVES); player:messageSpecial(KEYITEM_OBTAINED,ASTRAL_COMPASS); end end;
gpl-3.0
Nathan22Miles/sile
lua-libraries/imagesize/format/swf.lua
9
1697
local MIME_TYPE = "application/x-shockwave-flash" local function _bytes_to_bits (s) local bits = "" for i = 1, s:len() do local c = s:byte(i) bits = bits .. (c >= 0x80 and "1" or "0") .. ((c % 0x80) >= 0x40 and "1" or "0") .. ((c % 0x40) >= 0x20 and "1" or "0") .. ((c % 0x20) >= 0x10 and "1" or "0") .. ((c % 0x10) >= 0x08 and "1" or "0") .. ((c % 0x08) >= 0x04 and "1" or "0") .. ((c % 0x04) >= 0x02 and "1" or "0") .. ((c % 0x02) >= 0x01 and "1" or "0") end return bits end local function _bin2int (s) local n = 0 for i = 1, s:len() do n = n * 2 if s:sub(i, i) == "1" then n = n + 1 end end return n end -- Determine size of ShockWave/Flash files. Adapted from code sent by -- Dmitry Dorofeev <dima@yasp.com> local function size (stream, options) local buf = stream:read(33) if not buf or buf:len() ~= 33 then return nil, nil, "SWF file header incomplete" end local bs if buf:sub(1, 1) == "C" then -- Decompress enough of the file to get the FrameSize RECT. -- TODO - decompress into bs, update docs about module required return nil, nil, "compressed SWF files are currently not supported" else bs = _bytes_to_bits(buf:sub(9, 25)) end local bits = _bin2int(bs:sub(1, 5)) local x = _bin2int(bs:sub(6 + bits, 5 + bits * 2)) local y = _bin2int(bs:sub(6 + bits * 3, 5 + bits * 4)) return math.floor((x + 19) / 20), math.floor((y + 19) / 20), MIME_TYPE end return size -- vi:ts=4 sw=4 expandtab
mit
GiantCyber/Giants_TM
plugins/invite.lua
393
1225
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)] and 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 = { "^[!/]invite (.*)$" }, run = run } end
agpl-3.0
shakib01/anonymous01
plugins/invite.lua
393
1225
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)] and 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 = { "^[!/]invite (.*)$" }, run = run } end
gpl-2.0
wwww1233/wwww
plugins/invite.lua
393
1225
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)] and 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 = { "^[!/]invite (.*)$" }, run = run } end
gpl-2.0
TrurlMcByte/docker-prosody
etc/prosody-modules/mod_statistics/prosodytop.lua
21
3159
local curses = require "curses"; local server = require "net.server_select"; local timer = require "util.timer"; assert(curses.timeout, "Incorrect version of curses library. Try 'sudo luarocks install luaposix'"); local top = require "top"; function main() local stdscr = curses.stdscr() -- it's a userdatum --stdscr:clear(); local view = top.new({ stdscr = stdscr; prosody = { up_since = os.time() }; conn_list = {}; }); timer.add_task(0.01, function () local ch = stdscr:getch(); if ch then if stdscr:getch() == 410 then view:resized(); else curses.ungetch(ch); end end return 0.2; end); timer.add_task(0, function () view:draw(); return 1; end); --[[ posix.signal(28, function () table.insert(view.conn_list, { jid = "WINCH" }); --view:draw(); end); ]] -- Fake socket object around stdin local stdin = { getfd = function () return 0; end; dirty = function (self) return false; end; settimeout = function () end; send = function (_, d) return #d, 0; end; close = function () end; receive = function (_, patt) local ch = stdscr:getch(); if ch >= 0 and ch <=255 then return string.char(ch); elseif ch == 410 then view:resized(); else table.insert(view.conn_list, { jid = tostring(ch) }); --FIXME end return ""; end }; local function on_incoming(stdin, text) -- TODO: Handle keypresses if text:lower() == "q" then os.exit(); end end stdin = server.wrapclient(stdin, "stdin", 0, { onincoming = on_incoming, ondisconnect = function () end }, "*a"); local function handle_line(line) local e = { STAT = function (name) return function (value) view:update_stat(name, value); end end; SESS = function (id) return function (jid) return function (stats) view:update_session(id, jid, stats); end end end; }; local chunk = assert(loadstring(line)); setfenv(chunk, e); chunk(); end local stats_listener = {}; function stats_listener.onconnect(conn) --stdscr:mvaddstr(6, 0, "CONNECTED"); end local partial = ""; function stats_listener.onincoming(conn, data) --print("DATA", data) data = partial..data; local lastpos = 1; for line, pos in data:gmatch("([^\n]+)\n()") do lastpos = pos; handle_line(line); end partial = data:sub(lastpos); end function stats_listener.ondisconnect(conn, err) stdscr:mvaddstr(6, 0, "DISCONNECTED: "..(err or "unknown")); end local conn = require "socket".tcp(); assert(conn:connect("localhost", 5782)); handler = server.wrapclient(conn, "localhost", 5782, stats_listener, "*a"); end return { run = function () --os.setlocale("UTF-8", "all") curses.initscr() curses.cbreak() curses.echo(false) -- not noecho ! curses.nl(false) -- not nonl ! curses.timeout(0); local ok, err = pcall(main); --while true do stdscr:getch() end --stdscr:endwin() if ok then ok, err = xpcall(server.loop, debug.traceback); end curses.endwin(); --stdscr:refresh(); if not ok then print(err); end print"DONE" end; };
mit
AdamGagorik/darkstar
scripts/globals/spells/bind.lua
27
1125
----------------------------------------- -- Spell: Bind ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --Pull base stats. local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration, including resistance. May need more research. local duration = 60; if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); --Resist local resist = applyResistanceEffect(caster,spell,target,dINT,35,0,EFFECT_BIND); if (resist >= 0.5) then --Do it! --Try to erase a weaker bind. if (target:addStatusEffect(EFFECT_BIND,target:speed(),0,duration*resist)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end return EFFECT_BIND; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Upper_Jeuno/npcs/Rouliette.lua
26
2190
----------------------------------- -- Area: Upper Jeuno -- NPC: Rouliette -- Starts and Finishes Quest: Candle-making -- @zone 244 -- @pos -24 -2 11 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,CANDLE_MAKING) == QUEST_ACCEPTED and trade:hasItemQty(531,1) == true and trade:getItemCount() == 1) then player:startEvent(0x0025); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --Prerequisites for this quest : A_CANDLELIGHT_VIGIL ACCEPTED if (player:getQuestStatus(JEUNO,CANDLE_MAKING) ~= QUEST_COMPLETED and player:getQuestStatus(JEUNO,A_CANDLELIGHT_VIGIL) == QUEST_ACCEPTED) then player:startEvent(0x0024); -- Start Quest Candle-making else player:startEvent(0x001e); --Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0024 and player:getQuestStatus(JEUNO,CANDLE_MAKING) == QUEST_AVAILABLE) then player:addQuest(JEUNO,CANDLE_MAKING); elseif (csid == 0x0025) then player:addTitle(BELIEVER_OF_ALTANA); player:addKeyItem(HOLY_CANDLE); player:messageSpecial(KEYITEM_OBTAINED,HOLY_CANDLE); player:addFame(JEUNO,30); player:tradeComplete(trade); player:completeQuest(JEUNO,CANDLE_MAKING); end end;
gpl-3.0
TrurlMcByte/docker-prosody
etc/prosody-modules/mod_tls_policy/mod_tls_policy.lua
1
1281
assert(require"ssl.core".info, "Incompatible LuaSec version"); local function hook(event_name, typ, policy) if not policy then return end if policy == "FS" then policy = { cipher = "^E?C?DHE%-" }; elseif type(policy) == "string" then policy = { cipher = policy }; end module:hook(event_name, function (event) local origin = event.origin; if origin.encrypted then local info = origin.conn:socket():info(); for key, what in pairs(policy) do module:log("debug", "Does info[%q] = %s match %s ?", key, tostring(info[key]), tostring(what)); if (type(what) == "number" and what < info[key] ) or (type(what) == "string" and not info[key]:match(what)) then origin:close({ condition = "policy-violation", text = ("TLS %s '%s' not acceptable"):format(key, tostring(info[key])) }); return false; end module:log("debug", "Seems so"); end module:log("debug", "Policy matches"); end end, 1000); end local policy = module:get_option(module.name, {}); if type(policy) == "string" then policy = { c2s = policy, s2s = policy }; end hook("stream-features", "c2s", policy.c2s); hook("s2s-stream-features", "s2sin", policy.s2sin or policy.s2s); hook("stanza/http://etherx.jabber.org/streams:features", "s2sout", policy.s2sout or policy.s2s);
mit
AdamGagorik/darkstar
scripts/zones/Al_Zahbi/npcs/Najelith.lua
13
1043
----------------------------------- -- Area: Al Zahbi -- NPC: Najelith -- Type: Galeserpent General -- @zone: 48 -- @pos -64.526 -8 39.372 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x010d); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/PsoXja/npcs/_i94.lua
13
1276
----------------------------------- -- Area: Pso'Xja -- NPC: _i94 (Stone Gate) -- Notes: Blue Bracelet Door -- @pos -330.000 14.074 -261.600 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Z=player:getZPos(); if (Z >= -261) then if (player:hasKeyItem(595)==true) then -- Blue Bracelet player:startEvent(0x003d); else player:messageSpecial(ARCH_GLOW_BLUE); end elseif (Z <= -262) then player:messageSpecial(CANNOT_OPEN_SIDE); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) end;
gpl-3.0
Hostle/luci
applications/luci-app-asterisk/luasrc/model/cbi/asterisk/trunks.lua
68
2343
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local ast = require("luci.asterisk") cbimap = Map("asterisk", "Trunks") cbimap.pageaction = false local sip_peers = { } cbimap.uci:foreach("asterisk", "sip", function(s) if s.type == "peer" then s.name = s['.name'] s.info = ast.sip.peer(s.name) sip_peers[s.name] = s end end) sip_table = cbimap:section(TypedSection, "sip", "SIP Trunks") sip_table.template = "cbi/tblsection" sip_table.extedit = luci.dispatcher.build_url("admin", "asterisk", "trunks", "sip", "%s") sip_table.addremove = true sip_table.sectionhead = "Extension" function sip_table.filter(self, s) return s and ( cbimap.uci:get("asterisk", s, "type") == nil or cbimap.uci:get_bool("asterisk", s, "provider") ) end function sip_table.create(self, section) if TypedSection.create(self, section) then created = section else self.invalid_cts = true end end function sip_table.parse(self, ...) TypedSection.parse(self, ...) if created then cbimap.uci:tset("asterisk", created, { type = "friend", qualify = "yes", provider = "yes" }) cbimap.uci:save("asterisk") luci.http.redirect(luci.dispatcher.build_url( "admin", "asterisk", "trunks", "sip", created )) end end user = sip_table:option(DummyValue, "username", "Username") context = sip_table:option(DummyValue, "context", "Dialplan") context.href = luci.dispatcher.build_url("admin", "asterisk", "dialplan") function context.cfgvalue(...) return AbstractValue.cfgvalue(...) or "(default)" end online = sip_table:option(DummyValue, "online", "Registered") function online.cfgvalue(self, s) if sip_peers[s] and sip_peers[s].info.online == nil then return "n/a" else return sip_peers[s] and sip_peers[s].info.online and "yes" or "no (%s)" %{ sip_peers[s] and sip_peers[s].info.Status:lower() or "unknown" } end end delay = sip_table:option(DummyValue, "delay", "Delay") function delay.cfgvalue(self, s) if sip_peers[s] and sip_peers[s].info.online then return "%i ms" % sip_peers[s].info.delay else return "n/a" end end info = sip_table:option(Button, "_info", "Info") function info.write(self, s) luci.http.redirect(luci.dispatcher.build_url( "admin", "asterisk", "trunks", "sip", s, "info" )) end return cbimap
apache-2.0
AdamGagorik/darkstar
scripts/globals/weaponskills/blade_ku.lua
11
1679
----------------------------------- -- Blade Ku -- Katana weapon skill -- Skill level: N/A -- Description: Delivers a five-hit attack. params.accuracy varies with TP. -- In order to obtain Blade: Ku, the quest Bugi Soden must be completed. -- Will stack with Sneak Attack. -- Aligned with the Shadow Gorget, Soil Gorget & Light Gorget. -- Aligned with the Shadow Belt, Soil Belt & Light Belt. -- Skillchain Properties: Gravitation/Transfixion -- Modifiers: STR:10% ; DEX:10% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 -- -- params.acc -- 100%TP 200%TP 300%TP -- ?? ?? ?? ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.numHits = 5; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.1; params.dex_wsc = 0.1; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1.25; params.ftp200 = 1.25; params.ftp300 = 1.25; params.str_wsc = 0.3; params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
AdamGagorik/darkstar
scripts/globals/abilities/earth_shot.lua
16
3132
----------------------------------- -- Ability: Earth Shot -- Consumes a Earth Card to enhance earth-based debuffs. Deals earth-based magic damage -- Rasp Effect: Enhanced DoT and DEX-, Slow Effect +10% ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/weaponskills"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) --ranged weapon/ammo: You do not have an appropriate ranged weapon equipped. --no card: <name> cannot perform that action. if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then return 216,0; end if (player:hasItem(2179, 0) or player:hasItem(2974, 0)) then return 0,0; else return 71, 0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local params = {}; params.includemab = true; local dmg = (2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG)) * 1 + player:getMod(MOD_QUICK_DRAW_DMG_PERCENT)/100; dmg = addBonusesAbility(player, ELE_EARTH, target, dmg, params); dmg = dmg * applyResistanceAbility(player,target,ELE_EARTH,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY)); dmg = adjustForTarget(target,dmg,ELE_EARTH); target:takeWeaponskillDamage(player, dmg, SLOT_RANGED, 1, 0, 0); -- targetTPMult is 0 because Quick Draw gives no TP to the mob target:updateEnmityFromDamage(player,dmg); local effects = {}; local counter = 1; local rasp = target:getStatusEffect(EFFECT_RASP); if (rasp ~= nil) then effects[counter] = rasp; counter = counter + 1; end local threnody = target:getStatusEffect(EFFECT_THRENODY); if (threnody ~= nil and threnody:getSubPower() == MOD_THUNDERRES) then effects[counter] = threnody; counter = counter + 1; end local slow = target:getStatusEffect(EFFECT_SLOW); if (slow ~= nil) then effects[counter] = slow; counter = counter + 1; end if counter > 1 then local effect = effects[math.random(1, counter-1)]; local duration = effect:getDuration(); local startTime = effect:getStartTime(); local tick = effect:getTick(); local power = effect:getPower(); local subpower = effect:getSubPower(); local tier = effect:getTier(); local effectId = effect:getType(); local subId = effect:getSubType(); power = power * 1.2; target:delStatusEffectSilent(effectId); target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier); local newEffect = target:getStatusEffect(effectId); newEffect:setStartTime(startTime); end local del = player:delItem(2179, 1) or player:delItem(2974, 1) target:updateClaim(player); return dmg; end;
gpl-3.0
paritoshmmmec/kong
spec/integration/admin_api/consumers_routes_spec.lua
20
6146
local json = require "cjson" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" local send_content_types = require "spec.integration.admin_api.helpers" describe("Admin API", function() setup(function() spec_helper.prepare_db() spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("/consumers/", function() local BASE_URL = spec_helper.API_URL.."/consumers/" describe("POST", function() it("[SUCCESS] should create a Consumer", function() send_content_types(BASE_URL, "POST", { username = "consumer POST tests" }, 201, nil, {drop_db = true}) end) it("[FAILURE] should return proper errors", function() send_content_types(BASE_URL, "POST", {}, 400, '{"custom_id":"At least a \'custom_id\' or a \'username\' must be specified","username":"At least a \'custom_id\' or a \'username\' must be specified"}') send_content_types(BASE_URL, "POST", { username = "consumer POST tests" }, 409, '{"username":"username already exists with value \'consumer POST tests\'"}') end) end) describe("PUT", function() it("[SUCCESS] should create and update", function() local consumer = send_content_types(BASE_URL, "PUT", { username = "consumer PUT tests" }, 201, nil, {drop_db=true}) consumer = send_content_types(BASE_URL, "PUT", { id = consumer.id, username = "consumer PUT tests updated", }, 200) assert.equal("consumer PUT tests updated", consumer.username) end) it("[FAILURE] should return proper errors", function() send_content_types(BASE_URL, "PUT", {}, 400, '{"custom_id":"At least a \'custom_id\' or a \'username\' must be specified","username":"At least a \'custom_id\' or a \'username\' must be specified"}') send_content_types(BASE_URL, "PUT", { username = "consumer PUT tests updated", }, 409, '{"username":"username already exists with value \'consumer PUT tests updated\'"}') end) end) describe("GET", function() setup(function() spec_helper.drop_db() spec_helper.seed_db(10) end) it("should retrieve all", function() local response, status = http_client.get(BASE_URL) assert.equal(200, status) local body = json.decode(response) assert.truthy(body.data) assert.equal(10, table.getn(body.data)) end) it("should retrieve a paginated set", function() local response, status = http_client.get(BASE_URL, {size=3}) assert.equal(200, status) local body_page_1 = json.decode(response) assert.truthy(body_page_1.data) assert.equal(3, table.getn(body_page_1.data)) assert.truthy(body_page_1.next) response, status = http_client.get(BASE_URL, {size=3,offset=body_page_1.next}) assert.equal(200, status) local body_page_2 = json.decode(response) assert.truthy(body_page_2.data) assert.equal(3, table.getn(body_page_2.data)) assert.truthy(body_page_2.next) assert.not_same(body_page_1, body_page_2) response, status = http_client.get(BASE_URL, {size=4,offset=body_page_2.next}) assert.equal(200, status) local body_page_3 = json.decode(response) assert.truthy(body_page_3.data) assert.equal(4, table.getn(body_page_3.data)) -- TODO: fixme --assert.falsy(body_page_3.next) assert.not_same(body_page_2, body_page_3) end) end) describe("/consumers/:consumer", function() local consumer setup(function() spec_helper.drop_db() local fixtures = spec_helper.insert_fixtures { consumer = {{username = "get_consumer_tests"}} } consumer = fixtures.consumer[1] end) describe("GET", function() it("should retrieve by id", function() local response, status = http_client.get(BASE_URL..consumer.id) assert.equal(200, status) local body = json.decode(response) assert.same(consumer, body) end) it("should retrieve by username", function() local response, status = http_client.get(BASE_URL..consumer.username) assert.equal(200, status) local body = json.decode(response) assert.same(consumer, body) end) end) describe("PATCH", function() it("[SUCCESS] should update a Consumer", function() local response, status = http_client.patch(BASE_URL..consumer.id, {username="patch-updated"}) assert.equal(200, status) local body = json.decode(response) assert.same("patch-updated", body.username) consumer = body response, status = http_client.patch(BASE_URL..consumer.username, {username="patch-updated-json"}, {["content-type"]="application/json"}) assert.equal(200, status) body = json.decode(response) assert.same("patch-updated-json", body.username) consumer = body end) it("[FAILURE] should return proper errors", function() local _, status = http_client.patch(BASE_URL.."hello", {username="patch-updated"}) assert.equal(404, status) local response, status = http_client.patch(BASE_URL..consumer.id, {username=" "}) assert.equal(400, status) assert.equal('{"username":"At least a \'custom_id\' or a \'username\' must be specified"}\n', response) end) end) describe("DELETE", function() it("[FAILURE] should return proper errors", function() local _, status = http_client.delete(BASE_URL.."hello") assert.equal(404, status) end) it("[SUCCESS] should delete a Consumer", function() local response, status = http_client.delete(BASE_URL..consumer.id) assert.equal(204, status) assert.falsy(response) end) end) end) end) end)
mit
Nathan22Miles/sile
core/inputs-common.lua
1
1183
SILE.inputs.common = { init = function(fn, t) local dclass = t.attr.class or "plain" SILE.documentState.documentClass = SILE.require("classes/"..dclass) SU.required(t.attr, "papersize", fn) for k,v in pairs(t.attr) do if SILE.documentState.documentClass.options[k] then SILE.documentState.documentClass.options[k](v) end end if not SILE.outputFilename and SILE.masterFileName then SILE.outputFilename = string.gsub(SILE.masterFileName,"%..-$", "").. ".pdf" end local ff = SILE.documentState.documentClass:init() SILE.typesetter:init(ff) end } SILE.process = function(t) if type(t) == "function" then return t() end for k,v in ipairs(t) do SILE.currentCommand = v if type(v) == "string" then SILE.typesetter:typeset(v) elseif SILE.Commands[v.tag] then SILE.Commands[v.tag](v.attr,v) else SU.error("Unknown command "..(v.tag or v.id)) end end end -- Just a simple one-level find. We're not reimplementing XPath here. SILE.findInTree = function (t, tag) for k,v in ipairs(t) do if type(v) == "string" then elseif v.tag == tag then return v end end end
mit
qwattash/config
roles/conf_x11_base/files/awesome/qwattash_conf/q_rules.lua
1
1492
-- -- Client rules configuration. These are applied to new clients through the manage signal. -- local awful = require("awful") local beautiful = require("beautiful") local M = {} local function initRules() awful.rules.rules = { -- All clients will match this rule. { rule = { }, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = awful.client.focus.filter, raise = true, keys = clientkeys, buttons = clientbuttons, screen = awful.screen.preferred, placement = awful.placement.no_overlap+awful.placement.no_offscreen } }, -- Floating clients, most of this is useless for us. { rule_any = { instance = { "DTA", -- Firefox addon DownThemAll. "copyq", -- Includes session name in class. }, class = { "Arandr", "Gpick", "Kruler", "MessageWin", -- kalarm. "Sxiv", "Wpa_gui", "pinentry", "veromix", "xtightvncviewer"}, name = { "Event Tester", -- xev. }, role = { "AlarmWindow", -- Thunderbird's calendar. "pop-up", -- e.g. Google Chrome's (detached) Developer Tools. } }, properties = { floating = true }}, } end M.initRules = initRules return M
mit
Snazz2001/fbcunn
test/test_Threshold.lua
9
8318
-- Copyright 2004-present Facebook. All Rights Reserved. require('fb.luaunit') require('fbtorch') require('nn') require('cutorch') require('cunn') local function assertTensorEq(a, b, msg, precision) precision = precision or 1e-5 msg = msg or 'error' local diff = torch.dist(a, b) if diff > precision then error('diff = ' .. diff .. ': ' .. msg) end end TestUpdateOutput = {} function TestUpdateOutput:setUp() self.hostLayer = nn.Threshold(0.0, 0.0):float() self.hostInput = torch.Tensor(16, 10, 10):float():uniform(-1.0, 1.0) self.hostOutput = self.hostLayer:forward(self.hostInput) self.cudaLayer = self.hostLayer:clone():cuda() self.cudaInput = self.hostInput:cuda() end function TestUpdateOutput:tearDown() collectgarbage() end function TestUpdateOutput:compareResults() local hostCudaOutput = self.cudaOutput:float() assertTensorEq(self.hostOutput, hostCudaOutput, "Results don't match", 0.0) end function TestUpdateOutput:testBasic() self.cudaOutput = self.cudaLayer:forward(self.cudaInput) self:compareResults() end function TestUpdateOutput:testTransposed() -- transpose the cuda input, make contiguous and transpose back -- this results in a tensor with original sizes that is not contiguous, -- i.e. it is in a transposed state and if iterated in lexicographical -- order would not result in a linear motions through address space. self.cudaInput = self.cudaInput:transpose(1, 3):contiguous():transpose(3, 1) self.cudaOutput = self.cudaLayer:forward(self.cudaInput) self:compareResults() end TestUpdateOutputInPlace = {} function TestUpdateOutputInPlace:setUp() TestUpdateOutput.setUp(self) self.cudaLayer.inplace = true end function TestUpdateOutputInPlace:tearDown() collectgarbage() end function TestUpdateOutputInPlace:compareResults() TestUpdateOutput.compareResults(self) end function TestUpdateOutputInPlace:testBasic() self.cudaOutput = self.cudaLayer:forward(self.cudaInput) self:compareResults() end function TestUpdateOutputInPlace:testPreserveTransposition() -- to avoid unnecessary copies when chaining layers that operate on -- transposed tensors (i.e. transparently use a different memory layout from -- Torch's default, point-wise layers should preserve the memory layout of -- their input self.cudaInput = self.cudaInput:transpose(1, 3):contiguous():transpose(3, 1) self.cudaOutput = self.cudaLayer:forward(self.cudaInput) assert(self.cudaInput:dim() == self.cudaOutput:dim()) for i = 1, self.cudaInput:dim() do assert(self.cudaInput:size(i) == self.cudaOutput:size(i)) assert(self.cudaInput:stride(i) == self.cudaOutput:stride(i)) end end TestUpdateGradInput = {} function TestUpdateGradInput:setUp() -- use setup from updateOutput() tests TestUpdateOutput.setUp(self) -- run forward pass cuda self.cudaOutput = self.cudaLayer:forward(self.cudaInput) -- create gradOutput tensor and run backward pass self.hostGradOutput = torch.Tensor(16, 10, 10):float():uniform(-1.0, 1.0) self.hostGradInput = self.hostLayer:backward(self.hostInput, self.hostGradOutput) self.cudaGradOutput = self.hostGradOutput:cuda() end function TestUpdateGradInput:tearDown() collectgarbage() end function TestUpdateGradInput:compareResults() local hostCudaGradInput = self.cudaGradInput:float() assertTensorEq(self.hostGradInput, hostCudaGradInput, "Results don't match", 0.0) end function TestUpdateGradInput:testBasic() self.cudaGradInput = self.cudaLayer:backward(self.cudaInput, self.cudaGradOutput) self:compareResults() end function TestUpdateGradInput:testTransposed() -- this test puts the gradOutput into a transposed state self.cudaGradOutput = self.cudaGradOutput:transpose(1, 3):contiguous() self.cudaGradOutput = self.cudaGradOutput:transpose(3, 1) self.cudaGradInput = self.cudaLayer:backward(self.cudaInput, self.cudaGradOutput) self:compareResults() end TestUpdateGradInputInPlace = {} function TestUpdateGradInputInPlace:setUp() -- use setup from updateOutput() in-place tests TestUpdateOutputInPlace.setUp(self) -- run forward pass cuda self.cudaOutput = self.cudaLayer:forward(self.cudaInput) -- create gradOutput tensor and run backward pass self.hostGradOutput = torch.Tensor(16, 10, 10):float():uniform(-1.0, 1.0) self.hostGradInput = self.hostLayer:backward(self.hostInput, self.hostGradOutput) self.cudaGradOutput = self.hostGradOutput:cuda() end function TestUpdateGradInputInPlace:tearDown() collectgarbage() end function TestUpdateGradInputInPlace:compareResults() TestUpdateGradInput.compareResults(self) end function TestUpdateGradInputInPlace:testBase() self.cudaGradInput = self.cudaLayer:backward(self.cudaInput, self.cudaGradOutput) self:compareResults() end function TestUpdateGradInputInPlace:testPreserveTransposition() self.cudaGradOutput = self.cudaGradOutput:transpose(1, 3):contiguous() self.cudaGradOutput = self.cudaGradOutput:transpose(3, 1) self.cudaGradInput = self.cudaLayer:backward(self.cudaInput, self.cudaGradOutput) assert(self.cudaGradOutput:dim() == self.cudaGradInput:dim()) for i = 1, self.cudaGradOutput:dim() do assert(self.cudaGradOutput:size(i) == self.cudaGradInput:size(i)) assert(self.cudaGradOutput:stride(i) == self.cudaGradInput:stride(i)) end end TestInPlaceCPU = {} function TestInPlaceCPU:setUp() self.threshold = nn.Threshold(2.0, 1.0) self.input = torch.Tensor(16, 10, 10):uniform(-1.0, 3.0) self.inputIP = self.input:clone() assertTensorEq(self.input, self.inputIP, 'inputs must match') self.thresholdIP = nn.Threshold(2.0, 1.0, true) end function TestUpdateOutput:tearDown() collectgarbage() end function TestInPlaceCPU:testForward() local output = self.threshold:forward(self.input) local outputIP = self.thresholdIP:forward(self.inputIP) assertTensorEq(outputIP, output, 'in-place output wrong') assertTensorEq(outputIP, self.inputIP, 'in-place input must be same as output') end function TestInPlaceCPU:testBackward() local output = self.threshold:forward(self.input) local outputIP = self.thresholdIP:forward(self.inputIP) output:uniform(-1.0, 1.0) outputIP = output:clone() local gradInput = self.threshold:backward(self.input, output) local gradInputIP = self.thresholdIP:backward(self.inputIP, outputIP) assertTensorEq(gradInputIP, gradInput, 'in-place result wrong') assertTensorEq(gradInputIP, outputIP, 'in-place input and output must be identical') end -- ----------------------------------------------------------------------------- -- Performance -- ----------------------------------------------------------------------------- local function format_time(time, size) return string.format('%1.5E / %u = %1.5E', time, size, time/size) end PerformanceThresholdGPU = {} function PerformanceThresholdGPU:tearDown() collectgarbage() end local function thresholdPerf(size, offset) offset = offset or 0.0 local input = torch.Tensor(size):uniform(-1.0 + offset, 1.0 + offset):cuda() local threshold = nn.Threshold(offset, offset):cuda() threshold:updateOutput(input) cutorch.synchronize() local timer = torch.Timer() threshold:updateOutput(input) cutorch.synchronize() print(format_time(timer:time().real, size)) end function PerformanceThresholdGPU:testSize1000() thresholdPerf(1000) end function PerformanceThresholdGPU:testSize10000() thresholdPerf(10000) end function PerformanceThresholdGPU:testSize100000() thresholdPerf(100000) end function PerformanceThresholdGPU:testSize1000000() thresholdPerf(1000000) end function PerformanceThresholdGPU:testSize10000000() thresholdPerf(10000000) end function PerformanceThresholdGPU:testSize100000000() thresholdPerf(100000000) end function PerformanceThresholdGPU:testSize1000000000() thresholdPerf(1000000000) end LuaUnit:main()
bsd-3-clause
yaoqi/Atlas
examples/tutorial-warnings.lua
40
2248
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] --- -- read_query() can rewrite packets -- -- You can use read_query() to replace the packet sent by the client and rewrite -- query as you like -- -- @param packet the mysql-packet sent by the client -- -- @return -- * nothing to pass on the packet as is, -- * proxy.PROXY_SEND_QUERY to send the queries from the proxy.queries queue -- * proxy.PROXY_SEND_RESULT to send your own result-set -- function read_query( packet ) if string.byte(packet) == proxy.COM_QUERY then proxy.queries:append(1, packet, { resultset_is_needed = true } ) return proxy.PROXY_SEND_QUERY end end --- -- dumps the warnings of queries -- -- read_query_result() is called when we receive a query result -- from the server -- -- for all queries which pass by we check if the warning-count is > 0 and -- inject a SHOW WARNINGS and dump it to the stdout -- -- @return -- * nothing or proxy.PROXY_SEND_RESULT to pass the result-set to the client -- * proxy.PROXY_IGNORE_RESULT to drop the result-set -- function read_query_result(inj) if (inj.id == 1) then local res = assert(inj.resultset) if res.warning_count > 0 then print("Query had warnings: " .. inj.query:sub(2)) proxy.queries:append(2, string.char(proxy.COM_QUERY) .. "SHOW WARNINGS", { resultset_is_needed = true } ) end elseif (inj.id == 2) then for row in inj.resultset.rows do print(string.format("warning: [%d] %s", row[2], row[1])) end return proxy.PROXY_IGNORE_RESULT end end
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Garlaige_Citadel/npcs/qm1.lua
13
1606
----------------------------------- -- Area: Garlaige Citadel -- NPC: qm1 (???) -- Involved In Quest: Altana's Sorrow -- @pos -282.339 0.001 261.707 200 ----------------------------------- package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Garlaige_Citadel/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local AltanaSorrow = player:getQuestStatus(BASTOK,ALTANA_S_SORROW); local VirnageLetter = player:hasKeyItem(LETTER_FROM_VIRNAGE); local DivinePaint = player:hasKeyItem(BUCKET_OF_DIVINE_PAINT); if (AltanaSorrow == QUEST_ACCEPTED and VirnageLetter == false and DivinePaint == false) then player:addKeyItem(BUCKET_OF_DIVINE_PAINT); player:messageSpecial(KEYITEM_OBTAINED,BUCKET_OF_DIVINE_PAINT); else player:messageSpecial(YOU_FIND_NOTHING); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Gamygyn.lua
5
1300
----------------------------------- -- Area: Dynamis Xarcabard -- MOB: Marquis Gamygyn ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if (mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 8192; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if (Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330183); -- 177 SpawnMob(17330184); -- 178 activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if (Animate_Trigger == 32767) then ally:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Yorcia_Weald/Zone.lua
16
1181
----------------------------------- -- -- Zone: Yorcia Weald -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Yorcia_Weald/TextIDs"] = nil; require("scripts/zones/Yorcia_Weald/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(254,6,64,219); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ohmbase/OpenRA
mods/cnc/maps/nod03b/nod03b.lua
12
3033
NodUnits = { "e1", "e1", "bggy", "bike", "e1", "e1", "bike", "bggy", "e1", "e1" } Engineers = { "e6", "e6", "e6" } FirstAttackWaveUnits = { "e1", "e1", "e2" } SecondAttackWaveUnits = { "e1", "e1", "e1" } ThirdAttackWaveUnits = { "e1", "e1", "e1", "e2" } SendAttackWave = function(units, action) Reinforcements.Reinforce(enemy, units, { GDIBarracksSpawn.Location, WP0.Location, WP1.Location }, 15, action) end FirstAttackWave = function(soldier) soldier.Move(WP2.Location) soldier.Move(WP3.Location) soldier.Move(WP4.Location) soldier.AttackMove(PlayerBase.Location) end SecondAttackWave = function(soldier) soldier.Move(WP5.Location) soldier.Move(WP6.Location) soldier.Move(WP7.Location) soldier.Move(WP9.Location) soldier.AttackMove(PlayerBase.Location) end InsertNodUnits = function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.Reinforce(player, { "mcv" }, { McvEntry.Location, McvDeploy.Location }) Reinforcements.Reinforce(player, NodUnits, { NodEntry.Location, NodRallypoint.Location }) Trigger.AfterDelay(DateTime.Seconds(15), function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.Reinforce(player, Engineers, { McvEntry.Location, PlayerBase.Location }) end) end WorldLoaded = function() player = Player.GetPlayer("Nod") enemy = Player.GetPlayer("GDI") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) gdiObjective = enemy.AddPrimaryObjective("Eliminate all Nod forces in the area.") nodObjective1 = player.AddPrimaryObjective("Capture the prison.") nodObjective2 = player.AddSecondaryObjective("Destroy all GDI forces.") Trigger.OnKilled(TechCenter, function() player.MarkFailedObjective(nodObjective1) end) Trigger.OnCapture(TechCenter, function() Trigger.AfterDelay(DateTime.Seconds(2), function() player.MarkCompletedObjective(nodObjective1) end) end) InsertNodUnits() Trigger.AfterDelay(DateTime.Seconds(40), function() SendAttackWave(FirstAttackWaveUnits, FirstAttackWave) end) Trigger.AfterDelay(DateTime.Seconds(80), function() SendAttackWave(SecondAttackWaveUnits, SecondAttackWave) end) Trigger.AfterDelay(DateTime.Seconds(140), function() SendAttackWave(ThirdAttackWaveUnits, FirstAttackWave) end) end Tick = function() if DateTime.GameTime > 2 then if player.HasNoRequiredUnits() then enemy.MarkCompletedObjective(gdiObjective) end if enemy.HasNoRequiredUnits() then player.MarkCompletedObjective(nodObjective2) end end end
gpl-3.0
AdamGagorik/darkstar
scripts/zones/VeLugannon_Palace/npcs/Grounds_Tome.lua
30
1099
----------------------------------- -- Area: Ve'Lugannon Palace -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_VELUGANNON_PALACE,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,743,744,745,746,747,748,0,0,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,743,744,745,746,747,748,0,0,0,0,GOV_MSG_VELUGANNON_PALACE); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/QuBia_Arena/Zone.lua
32
1564
----------------------------------- -- -- Zone: Qu'Bia Arena (206) -- ----------------------------------- package.loaded["scripts/zones/QuBia_Arena/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/QuBia_Arena/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-241.046,-25.86,19.991,0); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/spells/bluemagic/mysterious_light.lua
25
1855
----------------------------------------- -- Spell: Mysterious Light -- Deals wind damage to enemies within range. Additional effect: Weight -- Spell cost: 73 MP -- Monster Type: Arcana -- Spell Type: Magical (Wind) -- Blue Magic Points: 4 -- Stat Bonus: AGI+3 -- Level: 40 -- Casting Time: 3.75 seconds -- Recast Time: 24.5 seconds -- Magic Bursts on: Detonation, Fragmentation, Light -- Combos: Max MP Boost ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = 2.0; params.tMultiplier = 1.0; params.duppercap = 56; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.2; damage = BlueMagicalSpell(caster, target, spell, params, CHR_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (damage > 0 and resist > 0.0625) then local typeEffect = EFFECT_WEIGHT; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Promyvion-Vahzl/mobs/Memory_Receptacle.lua
6
6870
----------------------------------- -- Area: Promyvion-Vahzl -- MOB: Memory Receptacle -- Todo: clean up disgustingly bad formatting ----------------------------------- package.loaded["scripts/zones/Promyvion-Vahzl/TextIDs"] = nil; ----------------------------------- require( "scripts/zones/Promyvion-Vahzl/TextIDs" ); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 100); -- 10% Regain for now mob:SetAutoAttackEnabled(false); -- Recepticles only use TP moves. end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local Mem_Recep = mob:getID(); -- This will serve as a ghetto Regain (not damage dependent) based on kjlotus's testing. Caps at 100 if (mob:getTP() < 900) then mob:addTP(100); end if (Mem_Recep == 16867382 or Mem_Recep == 16867387) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do -- Keep pets linked if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif (Mem_Recep == 16867429 or Mem_Recep == 16867436 or Mem_Recep == 16867494 or Mem_Recep == 16867501 or Mem_Recep == 16867508 or -- Floor 2/3 Mem_Recep == 16867515) then for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif (Mem_Recep == 16867586 or Mem_Recep == 16867595 or Mem_Recep == 16867604) then -- Floor 4 for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end end -- Summons a single stray every 30 seconds. if (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16867382 or Mem_Recep == 16867387) and mob:AnimationSub() == 2) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do if (GetMobAction(i) == 0) then -- My Stray is deeaaaaaad! mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16867429 or Mem_Recep == 16867436 or Mem_Recep == 16867494 or -- Floor 2/3 Mem_Recep == 16867501 or Mem_Recep == 16867508 or Mem_Recep == 16867515) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16867586 or Mem_Recep == 16867595 or Mem_Recep == 16867604) and -- Floor 4 mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); return; end end else mob:AnimationSub(2); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local mobID = mob:getID(); local difX = ally:getXPos()-mob:getXPos(); local difY = ally:getYPos()-mob:getYPos(); local difZ = ally:getZPos()-mob:getZPos(); local killeranimation = ally:getAnimation(); local Distance = math.sqrt( math.pow(difX,2) + math.pow(difY,2) + math.pow(difZ,2) ); --calcul de la distance entre les "killer" et le memory receptacle mob:AnimationSub(0); -- Set ani. sub to default or the recepticles wont work properly switch (mob:getID()) : caseof { [16867387] = function (x) GetNPCByID(16867700):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(32); end end, [16867382] = function (x) GetNPCByID(16867699):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(33); end end, [16867429] = function (x) GetNPCByID(16867697):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(30); end end, [16867436] = function (x) GetNPCByID(16867698):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(31); end end, [16867501] = function (x) GetNPCByID(16867703):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(35); end end, [16867515] = function (x) GetNPCByID(16867705):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(36); end end, [16867494] = function (x) GetNPCByID(16867702):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(37); end end, [16867508] = function (x) GetNPCByID(16867704):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(38); end end, [16867604] = function (x) GetNPCByID(16867707):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(34); end end, [16867586] = function (x) GetNPCByID(16867701):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(39); end end, [16867595] = function (x) GetNPCByID(16867706):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(40); end end, } end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ---------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Xarcabard/npcs/Trail_Markings.lua
12
2589
----------------------------------- -- Area: Xarcabard -- NPC: Trail Markings -- Dynamis-Xarcabard Enter -- @pos 570 0 -272 112 ----------------------------------- package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/dynamis"); require("scripts/zones/Xarcabard/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("DynaXarcabard_Win") == 1) then player:startEvent(0x0020,HYDRA_CORPS_BATTLE_STANDARD); -- Win CS elseif (player:hasKeyItem(HYDRA_CORPS_INSIGNIA)) then local firstDyna = 0; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if (checkFirstDyna(player,6)) then -- First Dyna-Xarcabard => CS firstDyna = 1; end if (player:getMainLvl() < DYNA_LEVEL_MIN) then player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN); elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaXarcabard]UniqueID")) then player:startEvent(0x0010,6,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,32,VIAL_OF_SHROUDED_SAND,4236,4237); else dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456); player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,6); end else player:messageSpecial(UNUSUAL_ARRANGEMENT_OF_PEBBLES); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("updateRESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("finishRESULT: %u",option); if (csid == 0x0020) then player:setVar("DynaXarcabard_Win",0); elseif (csid == 0x0010 and option == 0) then if (checkFirstDyna(player,6)) then player:setVar("Dynamis_Status",player:getVar("Dynamis_Status") + 64); end player:setPos(569.312,-0.098,-270.158,90,0x87); end end;
gpl-3.0
archiloque/nginx_services_logging
lua_scripts/nginx_request_logger_http_endpoint.lua
2
7425
-- Http endpoint local HttpEndpoint = {} HttpEndpoint.__index = HttpEndpoint function HttpEndpoint.new(endpoint_configuration) local self = setmetatable({}, HttpEndpoint) self.http_method = endpoint_configuration.http_method self.uri_type = endpoint_configuration.uri_type self.uri = endpoint_configuration.uri self.name = endpoint_configuration.name self.need_request_body_json = false self.request = nil if endpoint_configuration.request and (next(endpoint_configuration.request) ~= nil) then self.request = {} for _, request_configuration_element in ipairs(endpoint_configuration.request) do local process_result = self:process_request_configuration(request_configuration_element) self.need_request_body_json = self.need_request_body_json or process_result.need_request_body_json table.insert(self.request, { name = request_configuration_element.name, processor = process_result.processor }) end end self.need_response_body_json = false self.response = nil if endpoint_configuration.response and (next(endpoint_configuration.response) ~= nil) then self.response = {} for _, response_configuration_element in ipairs(endpoint_configuration.response) do local process_result = self:process_response_configuration(response_configuration_element) self.need_response_body_json = self.need_response_body_json or process_result.need_response_body_json table.insert(self.response, { name = response_configuration_element.name, processor = process_result.processor }) end end return self end function HttpEndpoint.process_request_configuration(self, request_configuration_element) local request_type = request_configuration_element.type if request_type == "uri_regex" then return { need_request_body_json = false, processor = self:create_uri_regex_request_function(request_configuration_element.configuration) } elseif request_type == "post_arg" then return { need_request_body_json = false, processor = self:create_post_arg_request_function(request_configuration_element.configuration) } elseif request_type == "json_body" then return { need_request_body_json = true, processor = self:create_json_body_param_function(request_configuration_element.configuration) } elseif request_type == "query" then return { need_request_body_json = false, processor = self:create_query_request_function(request_configuration_element.configuration) } elseif request_type == "header" then return { need_request_body_json = false, processor = self:create_header_param_function(request_configuration_element.configuration) } else error("Unknown request type [" .. request_type .. "]") end end function HttpEndpoint.process_response_configuration(self, reponse_configuration_element) local response_type = reponse_configuration_element.type if response_type == "json_body" then return { need_response_body_json = true, processor = self:create_json_body_param_function(reponse_configuration_element.configuration) } elseif response_type == "header" then return { need_response_body_json = false, processor = self:create_header_param_function(reponse_configuration_element.configuration) } else error("Unknown response type [" .. response_type .. "]") end end function HttpEndpoint.create_uri_regex_request_function(self, request_configuration_element) local match_index = request_configuration_element.match_index + 2 return function(arguments) return arguments.match_result[match_index] end end function HttpEndpoint.create_post_arg_request_function(self, request_configuration_element) local parameter_name = request_configuration_element.parameter_name return function(arguments) local args = arguments.post_args if args then return args[parameter_name] else return nil end end end function HttpEndpoint.create_json_body_param_function(self, param_configuration_element) local path = param_configuration_element.path return function(arguments) if arguments.json_body then local current_body_part = arguments.json_body for _, current_key in ipairs(path) do if current_body_part then current_body_part = current_body_part[current_key] end end return current_body_part else return nil end end end function HttpEndpoint.create_query_request_function(self, request_configuration_element) local parameter_name = request_configuration_element.parameter_name return function(arguments) return arguments.uri_args[parameter_name] end end function HttpEndpoint.create_header_param_function(self, param_configuration_element) local header_name = param_configuration_element.header_name return function(arguments) return arguments.headers[header_name] end end -- Check it the current call match the service function HttpEndpoint.match_current_call(self, http_method, uri, matcher) if http_method == self.http_method then if self.uri_type == "plain" then return uri == self.uri else -- regex type return matcher.match(uri, self.uri, "ao") end else return false end end function HttpEndpoint.process_before_call(self, ngx, match_result) if self.request then local headers = ngx.req.get_headers() local values = { match_result = match_result, headers = headers, uri_args = ngx.req.get_uri_args(), post_args = ngx.req.get_post_args() } if self.need_request_body_json then self:add_json_body(headers, ngx.var.request_body, values) end return self:process_call(self.request, values) else return {} end end function HttpEndpoint.process_after_call(self, ngx, response_body) if self.response then local headers = ngx.resp.get_headers() local values = { headers = headers } if self.need_response_body then self:add_json_body(headers, response_body, values) end return self:process_call(self.response, values) else return {} end end function HttpEndpoint.add_json_body(self, headers, body, values) if body then local content_type = headers["Content-Type"] if (content_type == "application/json") then pcall(function() values.json_body = cjson.decode(body) end) end end end function HttpEndpoint.process_call(self, parameters, arguments) local result_params = {} for _, parameter in ipairs(parameters) do local result = parameter.processor(arguments) if result then result_params[parameter.name] = result end end return result_params end function HttpEndpoint.need_response_body(self) return self.need_response_body_json end return HttpEndpoint
mit
AdamGagorik/darkstar
scripts/globals/items/seafood_stewpot.lua
18
1436
----------------------------------------- -- ID: 5238 -- Item: Seafood Stewpot -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 50 -- MP +10 -- Accuracy 5 -- Evasion 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5238); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 50); target:addMod(MOD_MP, 10); target:addMod(MOD_ACC, 5); target:addMod(MOD_EVA, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 50); target:delMod(MOD_MP, 10); target:delMod(MOD_ACC, 5); target:delMod(MOD_EVA, 5); end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/spells/bluemagic/jet_stream.lua
33
1738
----------------------------------------- -- Spell: Jet Stream -- Delivers a threefold attack. Accuracy varies with TP -- Spell cost: 47 MP -- Monster Type: Birds -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: DEX+2 -- Level: 38 -- Casting Time: 0.5 seconds -- Recast Time: 23 seconds -- Skillchain Element(s): Lightning (can open Liquefaction or Detonation; can close Impaction or Fusion) -- Combos: Rapid Shot ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ACC; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_IMPACTION; params.numhits = 3; params.multiplier = 1.125; params.tp150 = 1.2; params.tp300 = 1.4; params.azuretp = 1.5; params.duppercap = 39; --guesstimated acc % bonuses params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
aquileia/wesnoth
data/lua/wml/object.lua
4
2799
local helper = wesnoth.require "lua/helper.lua" local utils = wesnoth.require "lua/wml-utils.lua" local T = helper.set_wml_tag_metatable {} local wml_actions = wesnoth.wml_actions local used_items = {} function wml_actions.object(cfg) local context = wesnoth.current.event_context -- If this item has already been used local unique = cfg.take_only_once if unique == nil then unique = true end local obj_id = utils.check_key(cfg.id, "id", "object", true) if obj_id and unique and used_items[obj_id] then return end local unit, command_type, text local filter = helper.get_child(cfg, "filter") if filter then unit = wesnoth.get_units(filter)[1] else unit = wesnoth.get_unit(context.x1, context.y1) end -- If a unit matches the filter, proceed if unit then text = tostring(cfg.description or "") else text = tostring(cfg.cannot_use_message or "") command_type = "else" end -- Default to silent if object has no description local silent = cfg.silent if silent == nil then silent = (text:len() == 0) end if unit then command_type = "then" if cfg.no_write ~= nil then wesnoth.log("wml", "[object]no_write=yes is deprecated in favour of placing [effect] tags in [modify_unit]") end local dvs = cfg.delayed_variable_substitution local add = cfg.no_write ~= true if dvs then wesnoth.add_modification(unit, "object", helper.literal(cfg), add) else wesnoth.add_modification(unit, "object", helper.parsed(cfg), add) end if not silent then wesnoth.select_unit(unit, false) wesnoth.highlight_hex(unit.x, unit.y) end -- Mark this item as used up if obj_id and unique then used_items[obj_id] = true end end if not silent then wml_actions.redraw{} local name = tostring(cfg.name or "") wesnoth.show_popup_dialog(name, text, cfg.image) end for cmd in helper.child_range(cfg, command_type) do local action = utils.handle_event_commands(cmd, "conditional") if action ~= "none" then break end end end local old_on_load = wesnoth.game_events.on_load function wesnoth.game_events.on_load(cfg) for i = 1,#cfg do if cfg[i][1] == "used_items" then -- Not quite sure if this will work -- Might need to loop through and copy each ID separately used_items = cfg[i][2] table.remove(cfg, i) break end end old_on_load(cfg) end local old_on_save = wesnoth.game_events.on_save function wesnoth.game_events.on_save() local cfg = old_on_save() table.insert(cfg, T.used_items(used_items) ) return cfg end function wml_actions.remove_object(cfg) local obj_id = cfg.object_id for _,unit in ipairs(wesnoth.get_units(cfg)) do wesnoth.remove_modifications(unit, {id = obj_id}) end end function wesnoth.wml_conditionals.found_item(cfg) return used_items[utils.check_key(cfg.id, "id", "found_item", true)] end
gpl-2.0
AdamGagorik/darkstar
scripts/globals/abilities/addendum_white.lua
7
1610
----------------------------------- -- Ability: Addendum: White -- Allows access to additional White Magic spells while using Light Arts. -- Obtained: Scholar Level 10 -- Recast Time: Stratagem Charge -- Duration: 2 hours -- -- Level |Charges |Recharge Time per Charge -- ----- -------- --------------- -- 10 |1 |4:00 minutes -- 30 |2 |2:00 minutes -- 50 |3 |1:20 minutes -- 70 |4 |1:00 minute -- 90 |5 |48 seconds ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_ADDENDUM_WHITE) then return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) player:delStatusEffectSilent(EFFECT_DARK_ARTS); player:delStatusEffectSilent(EFFECT_ADDENDUM_BLACK); player:delStatusEffectSilent(EFFECT_LIGHT_ARTS); local skillbonus = player:getMod(MOD_LIGHT_ARTS_SKILL); local effectbonus = player:getMod(MOD_LIGHT_ARTS_EFFECT); local regenbonus = 0; if (player:getMainJob() == JOB_SCH and player:getMainLvl() >= 20) then regenbonus = 3 * math.floor((player:getMainLvl() - 10) / 10); end player:addStatusEffectEx(EFFECT_ADDENDUM_WHITE,EFFECT_ADDENDUM_WHITE,effectbonus,0,7200,0,regenbonus,true); return EFFECT_ADDENDUM_WHITE; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Rabao/npcs/Brave_Wolf.lua
13
1524
----------------------------------- -- Area: Rabao -- NPC: Brave Wolf -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Rabao/TextIDs"] = nil; require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,BRAVEWOLF_SHOP_DIALOG); stock = {0x300D,31201, --Buckler 0x300E,60260, --Darksteel Buckler 0x369B,24373, --Silver Bangles 0x310A,66066, --Banded Mail 0x318A,35285, --Mufflers 0x320A,52552, --Breeches 0x328A,32382, --Sollerets 0x3141,9423, --Black Tunic 0x31C1,4395, --White Mitts 0x3241,6279, --Black Slacks 0x32C1,4084, --Sandals 0x3122,28654, --Padded Armor 0x31A2,15724, --Iron Mittens 0x3224,23063, --Iron Subligar 0x32A2,14327} --Leggins showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Nashmau/npcs/Yoyoroon.lua
13
1691
----------------------------------- -- Area: Nashmau -- NPC: Yoyoroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,YOYOROON_SHOP_DIALOG); stock = {0x08BF,4940, -- Tension Spring 0x08C0,9925, -- Inhibitor 0x08C2,9925, -- Mana Booster 0x08C3,4940, -- Loudspeaker 0x08C6,4940, -- Accelerator 0x08C7,9925, -- Scope 0x08CA,9925, -- Shock Absorber 0x08CB,4940, -- Armor Plate 0x08CE,4940, -- Stabilizer 0x08CF,9925, -- Volt Gun 0x08D2,4940, -- Mana Jammer 0x08D4,9925, -- Stealth Screen 0x08D6,4940, -- Auto-Repair Kit 0x08D8,9925, -- Damage Gauge 0x08DA,4940, -- Mana Tank 0x08DC,9925} -- Mana Conserver showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Palborough_Mines/npcs/Mythril_Seam.lua
13
2827
----------------------------------- -- Area: Palborough Mines -- NPC: Mythril Seam -- Involved In Mission: Journey Abroad -- Involved in quest: Rock Racketeer -- @zone 143 -- @pos -68 -7 173 // Rock Racketeer @pos 210 -32 -63 ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Palborough_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) RRvar = player:getVar("rockracketeer_sold"); --Rock Racketeer if (trade:hasItemQty(605,1) and trade:getItemCount() == 1 and RRvar == 5) then if (player:getFreeSlotsCount() >= 1) then rand = math.random(); rand = math.random(); rand = math.random(); if (rand <= 0.47) then -- 47% player:startEvent(0x0033,12,598); -- Sharp Stone (598) else player:startEvent(0x0034,8,598); -- pickaxe breaks player:tradeComplete(); end else player:startEvent(0x0035); -- cannot carry any more end -- Standard elseif (trade:hasItemQty(605,1) and trade:getItemCount() == 1) then -- Trade Pickaxe if (player:getFreeSlotsCount() >= 1) then rand = math.random(); rand = math.random(); rand = math.random(); if (rand <= 0.47) then -- 47% player:startEvent(0x002b,12,0,597); -- chunk of mine gravel (597) else player:startEvent(0x001f,8,0,597); -- pickaxe breaks player:tradeComplete(); end else player:startEvent(0x0021); -- cannot carry any more end -- need a pickaxe else player:startEvent(0x0020); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x001e,12,0,597); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x002b) then player:tradeComplete(); player:addItem(597); player:messageSpecial(ITEM_OBTAINED,597); -- Mine Gravel end end;
gpl-3.0
adib1380/anti2
plugins/twitter.lua
632
2555
local OAuth = require "OAuth" -- EDIT data/twitter.lua with the API keys local twitter_config = load_from_file('data/twitter.lua', { -- DON'T EDIT HERE. consumer_key = "", consumer_secret = "", access_token = "", access_token_secret = "" }) local client = OAuth.new(twitter_config.consumer_key, twitter_config.consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/twitter_config.access_token" }, { OAuthToken = twitter_config.access_token, OAuthTokenSecret = twitter_config.access_token_secret }) function run(msg, matches) if twitter_config.consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter.lua" end if twitter_config.consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter.lua" end if twitter_config.access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter.lua" end if twitter_config.access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter.lua" end local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. matches[1] .. ".json" local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url) local response = json:decode(response_body) local header = "Tweet from " .. response.user.name .. " (@" .. response.user.screen_name .. ")\n" local text = response.text -- replace short URLs if response.entities.url then for k, v in pairs(response.entities.urls) do local short = v.url local long = v.expanded_url text = text:gsub(short, long) end end -- remove images local images = {} if response.extended_entities and response.extended_entities.media then for k, v in pairs(response.extended_entities.media) do local url = v.url local pic = v.media_url text = text:gsub(url, "") table.insert(images, pic) end end -- send the parts local receiver = get_receiver(msg) send_msg(receiver, header .. "\n" .. text, ok_cb, false) send_photos_from_url(receiver, images) return nil end return { description = "When user sends twitter URL, send text and images to origin. Requires OAuth Key.", usage = "", patterns = { "https://twitter.com/[^/]+/status/([0-9]+)" }, run = run }
gpl-2.0
virgo-agent-toolkit/luvit-pkg
lib/spawn.lua
1
1119
local childprocess = require('childprocess') local core = require('core') local stream = require('stream') local Process = core.Emitter:extend() function Process:initialize() self._uv_process = nil self.stdin = stream.Writable:new() self.stdout = stream.Readable:new() self.stderr = stream.Readable:new() end function wrap_readable(uv_readable, readable) readable:wrap(uv_readable) end function wrap_writable(uv_writable, writable) writable._write = function(self, data, encoding, callback) uv_writable:write(data, callback) end writable:once('finish', function() uv_writable:close() end) end function relay_events(proc, events) for k,v in pairs(events) do proc._uv_process:on(v, function(...) proc:emit(v, ...) end) end end return function(command, args, options) local proc = Process:new() proc._uv_process = childprocess.spawn(command, args, options) wrap_writable(proc._uv_process.stdin, proc.stdin) wrap_readable(proc._uv_process.stdout, proc.stdout) wrap_readable(proc._uv_process.stderr, proc.stderr) relay_events(proc, {'exit'}) return proc end
apache-2.0
AdamGagorik/darkstar
scripts/zones/Chateau_dOraguille/npcs/Chaloutte.lua
13
1068
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Chaloutte -- Type: Event Scene Replayer -- @zone: 233 -- @pos 10.450 -1 -11.985 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x022d); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/South_Gustaberg/Zone.lua
13
4384
----------------------------------- -- -- Zone: South_Gustaberg (107) -- ----------------------------------- package.loaded["scripts/zones/South_Gustaberg/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/globals/zone"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/icanheararainbow"); require("scripts/zones/South_Gustaberg/TextIDs"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 17296, 252, DIGREQ_NONE }, { 17396, 227, DIGREQ_NONE }, { 846, 156, DIGREQ_NONE }, { 880, 133, DIGREQ_NONE }, { 936, 83, DIGREQ_NONE }, { 869, 80, DIGREQ_NONE }, { 749, 32, DIGREQ_NONE }, { 847, 23, DIGREQ_NONE }, { 644, 5, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 4545, 5, DIGREQ_BURROW }, { 636, 63, DIGREQ_BURROW }, { 617, 63, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, { 575, 14, DIGREQ_NIGHT }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17216207,17216208}; SetFieldManual(manuals); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-601.433,35.204,-520.031,1); end if (player:getCurrentMission(COP) == THE_CALL_OF_THE_WYRMKING and player:getVar("VowsDone") == 1) then cs= 0x038A; elseif (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x0385; elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x0025; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0385) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x0025) then if (player:getXPos() > -390) then if (player:getZPos() > -301) then player:updateEvent(0,0,0,0,0,6); else player:updateEvent(0,0,0,0,0,7); end end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x038A) then if (player:getCurrentMission(COP) == A_TRANSIENT_DREAM) then player:completeMission(COP,A_TRANSIENT_DREAM); player:addMission(COP,THE_CALL_OF_THE_WYRMKING); end player:setVar("VowsDone",0); elseif (csid == 0x0385) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Throne_Room_[S]/Zone.lua
32
1271
----------------------------------- -- -- Zone: Throne_Room_[S] (156) -- ----------------------------------- package.loaded["scripts/zones/Throne_Room_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Throne_Room_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(114.308,-7.639,0.022,128); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Anarchid/Zero-K-Infrastructure
MissionEditor/MissionEditor2/MissionBase/LuaUI/Widgets/mission_messenger.lua
9
6973
-- $Id: mission_messenger.lua 3171 2008-11-06 09:06:29Z det $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Messenger", desc = "Displays Messages. Click on them to make them go away.", author = "quantum", date = "June 29, 2007", license = "GPL v2 or later", layer = -4, enabled = true, -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local viewSizeX, viewSizeY local gl, GL = gl, GL local fontHandler = loadstring(VFS.LoadFile(LUAUI_DIRNAME.."modfonts.lua", VFS.ZIP_FIRST))() local messages = {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function Split(s, separator) local results = {} for part in s:gmatch("[^"..separator.."]+") do results[#results + 1] = part end return results end -- remove first n elemets from t, return them local function Take(t, n) local removed = {} for i=1, n do removed[#removed+1] = table.remove(t, 1) end return removed end -- appends t1 to t2 in-place local function Append(t1, t2) local l = #t1 for i = 1, #t2 do t1[i + l] = t2[i] end end local function WordWrap(text, font, maxWidth, size) fontHandler.UseFont(font) text = text:gsub("\r\n", "\n") local spaceWidth = fontHandler.GetTextWidth(" ", size) local allLines = {} local paragraphs = Split(text, "\n") for _, paragraph in ipairs(paragraphs) do lines = {} local words = Split(paragraph, "%s") local widths = {} for i, word in ipairs(words) do widths[i] = fontHandler.GetTextWidth(fontHandler.StripColors(word), size) end repeat local width = 0 local i = 1 for j=1, #words do newWidth = width + widths[j] if (newWidth > maxWidth) then break else width = newWidth + spaceWidth end i = j end Take(widths, i) lines[#lines+1] = table.concat(Take(words, i), " ") until (i > #words) if (#words > 0) then lines[#lines+1] = table.concat(words, " ") end Append(allLines, lines) end return allLines end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function DrawBox(width, height) gl.Color(0, 0, 0, 0.5) gl.Vertex(0.5, 0.5) gl.Color(0, 0, 0, 0.8) gl.Vertex(0.5, height + 0.5) gl.Color(0, 0, 0, 0.5) gl.Vertex(width + 0.5, height + 0.5) gl.Color(0.4, 0.4, 0.4, 0.5) gl.Vertex(width+ 0.5, 0.5) end local function DrawBorders(width, height) gl.Color(1, 1, 1, 1) gl.Vertex(0.5, 0.5) gl.Vertex(0.5, height + 0.5) gl.Vertex(width + 0.5, height + 0.5) gl.Vertex(width + 0.5, 0.5) end local function List(width, height, texture) if (texture) then gl.Color(1, 1, 1, 1) gl.Texture(texture) gl.TexRect(0, 0, width, height) else gl.BeginEnd(GL.QUADS, DrawBox, width, height) gl.BeginEnd(GL.LINE_LOOP, DrawBorders, width, height) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local Message = { font = "LuaUI/Fonts/FreeSansBold_16", marginX = 20, marginY = 20, spacing = 10, width = 300, height = 100, x1 = 200, y1 = 200, autoSize = true, relX = 0.5, relY = 0.5, pause = false, } Message.__index = Message WG.Message = Message function Message:Show(m) setmetatable(m, self) fontHandler.UseFont(m.font) m.fontSize = fontHandler.GetFontSize() messages[m] = true if (type(m.text) == 'string') then m.text = WordWrap(m.text, m.font, m.width - m.marginX * 2) end if (m.text and m.autoSize and #m.text > 0 and not m.texture) then local maxWidth = 0 for _, line in ipairs(m.text) do maxWidth = math.max(maxWidth, fontHandler.GetTextWidth(fontHandler.StripColors(line), m.fontSize)) end m.width = maxWidth + m.marginX * 2 m.height = #m.text * m.fontSize + (#m.text - 1) * m.spacing + m.marginY * 2 end m.displayList = gl.CreateList(List, m.width, m.height, m.texture) local _, _, paused = Spring.GetGameSpeed() if m.pause and not paused then Spring.SendCommands"pause" end return message end function Message:Draw(viewSizeX, viewSizeY) if (self.relX) then self.x1 = self.relX*viewSizeX-self.width/2 end if (self.relY) then self.y1 = self.relY*viewSizeY-self.height/2 end self.x1 = math.floor(self.x1) self.y1 = math.floor(self.y1) gl.PushMatrix() gl.Translate(self.x1, self.y1, 0) gl.CallList(self.displayList) if (self.text) then -- gl.Translate(-0.5, -0.5, 0) fontHandler.UseFont(self.font) gl.Color(1, 1, 1, 1) for i, line in ipairs(self.text) do local x = self.marginX local y = self.height - self.marginY - self.fontSize * i - self.spacing * (i - 1) fontHandler.Draw(line, x, y) end end gl.PopMatrix() end function Message:Delete() local _, _, paused = Spring.GetGameSpeed() if self.pause and paused then Spring.SendCommands"pause" end gl.DeleteList(self.displayList) messages[self] = nil end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:DrawScreen() local viewSizeX, viewSizeY = gl.GetViewSizes() for message in pairs(messages) do message:Draw(viewSizeX, viewSizeY) end end function widget:MousePress(x, y, button) local capture for message in pairs(messages) do if ( x > message.x1 and x < message.x1 + message.width and y > message.y1 and y < message.y1 + message.height) then message.closing = true capture = true end end return capture end function widget:MouseRelease(x, y, button) local capture for message in pairs(messages) do if (message.closing and x > message.x1 and x < message.x1 + message.width and y > message.y1 and y < message.y1 + message.height) then capture = true message:Delete() end end return capture end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-3.0
Wiladams/cream
testy/test_std_optparse.lua
1
1331
local OptionParser = require("std.optparse") local parser = OptionParser[[ any text VERSION Additional lines of text to show when the --version option is passed. Several lines or paragraphs are permitted. Usage: PROGNAME Banner text. Optional long description text to show when the --help option is passed. Several lines or paragraphs of long description are permitted. Options: -b a short option with no long option --long a long option with no short option --another-long a long option with internal hypen -v, --verbose a combined short and long option -n, --dryrun, --dry-run several spellings of the same option -u, --name=USER require an argument -o, --output=[FILE] accept an optional argument --version display version information, then exit --help display this help, then exit Footer text. Several lines or paragraphs are permitted. Please report bugs at bug-list@yourhost.com --]] _G.arg, _G.opts = parser:parse (_G.arg) local function printTable(tbl, title) if title then print(title) end if not table then return end for k,v in pairs(tbl) do print(k,v) end end print("==== PARSED OPTIONS ====") print("opts: ", opts) printTable(opts) exit();
mit
AdamGagorik/darkstar
scripts/globals/abilities/healing_waltz.lua
19
1588
----------------------------------- -- Ability: Healing Waltz -- Removes one detrimental status effect from target party member. -- Obtained: Dancer Level 35 -- TP Required: 20% -- Recast Time: 00:15 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (target:getHP() == 0) then return MSGBASIC_CANNOT_ON_THAT_TARG,0; elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then return MSGBASIC_UNABLE_TO_USE_JA2, 0; elseif (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 200) then return MSGBASIC_NOT_ENOUGH_TP,0; else -- apply waltz recast modifiers if (player:getMod(MOD_WALTZ_RECAST)~=0) then local recastMod = -150 * (player:getMod(MOD_WALTZ_RECAST)); -- 750 ms or 5% per merit if (recastMod <0) then --TODO end end return 0,0; end; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(200); end; local effect = target:healingWaltz(); if (effect == EFFECT_NONE) then ability:setMsg(283); -- no effect else ability:setMsg(123); end return effect; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/West_Ronfaure/Zone.lua
13
3884
----------------------------------- -- -- Zone: West_Ronfaure (100) -- ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/globals/zone"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/conquest"); require("scripts/globals/icanheararainbow"); require("scripts/zones/West_Ronfaure/TextIDs"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 4504, 167, DIGREQ_NONE }, { 688, 15, DIGREQ_NONE }, { 17396, 20, DIGREQ_NONE }, { 698, 5, DIGREQ_NONE }, { 840, 117, DIGREQ_NONE }, { 691, 83, DIGREQ_NONE }, { 833, 83, DIGREQ_NONE }, { 639, 10, DIGREQ_NONE }, { 694, 63, DIGREQ_NONE }, { 918, 12, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 4545, 5, DIGREQ_BURROW }, { 636, 63, DIGREQ_BURROW }, { 617, 63, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, { 573, 23, DIGREQ_NIGHT }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17187570,17187571}; SetFieldManual(manuals); SetRegionalConquestOverseers(zone:getRegionID()) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-24.427,-53.107,140,127); end if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x0033; elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x0035; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0033) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x0035) then player:updateEvent(0,0,0,0,0,5); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0033) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end;
gpl-3.0
Hostle/luci
applications/luci-app-statistics/luasrc/statistics/datatree.lua
58
4177
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.datatree", package.seeall) local util = require("luci.util") local sys = require("luci.sys") local fs = require("nixio.fs") local uci = require("luci.model.uci").cursor() local sections = uci:get_all("luci_statistics") Instance = util.class() function Instance.__init__( self, host ) self._host = host or sections.collectd.Hostname or sys.hostname() self._libdir = sections.collectd.PluginDir or "/usr/lib/collectd" self._rrddir = sections.collectd_rrdtool.DataDir or "/tmp/rrd" self._libdir = self._libdir:gsub("/$","") self._rrddir = self._rrddir:gsub("/$","") self._plugins = { } self:_scan() end function Instance._mkpath( self, plugin, pinstance ) local dir = self._rrddir .. "/" .. self._host if type(plugin) == "string" and plugin:len() > 0 then dir = dir .. "/" .. plugin if type(pinstance) == "string" and pinstance:len() > 0 then dir = dir .. "-" .. pinstance end end return dir end function Instance._ls( self, ... ) local ditr = fs.dir(self:_mkpath(...)) if ditr then local dirs = { } while true do local d = ditr() if not d then break end dirs[#dirs+1] = d end return dirs end end function Instance._notzero( self, table ) for k in pairs(table) do return true end return false end function Instance._scan( self ) local dirs = self:_ls() if not dirs then return end -- for i, plugin in ipairs( dirs ) do -- if plugin:match("%w+.so") then -- self._plugins[ plugin:gsub("%.so$", "") ] = { } -- end -- end for _, dir in ipairs(dirs) do if dir ~= "." and dir ~= ".." and fs.stat(self:_mkpath(dir)).type == "dir" then local plugin = dir:gsub("%-.+$", "") if not self._plugins[plugin] then self._plugins[plugin] = { } end end end for plugin, instances in pairs( self._plugins ) do local dirs = self:_ls() if type(dirs) == "table" then for i, dir in ipairs(dirs) do if dir:find( plugin .. "%-" ) or dir == plugin then local instance = "" if dir ~= plugin then instance = dir:gsub( plugin .. "%-", "", 1 ) end instances[instance] = { } end end end for instance, data_instances in pairs( instances ) do dirs = self:_ls(plugin, instance) if type(dirs) == "table" then for i, file in ipairs(dirs) do if file:find("%.rrd") then file = file:gsub("%.rrd","") local data_type local data_instance if file:find("%-") then data_type = file:gsub( "%-.+","" ) data_instance = file:gsub( "[^%-]-%-", "", 1 ) else data_type = file data_instance = "" end if not data_instances[data_type] then data_instances[data_type] = { data_instance } else table.insert( data_instances[data_type], data_instance ) end end end end end end end function Instance.plugins( self ) local rv = { } for plugin, val in pairs( self._plugins ) do if self:_notzero( val ) then table.insert( rv, plugin ) end end return rv end function Instance.plugin_instances( self, plugin ) local rv = { } for instance, val in pairs( self._plugins[plugin] ) do table.insert( rv, instance ) end return rv end function Instance.data_types( self, plugin, instance ) local rv = { } local p = self._plugins[plugin] if type(p) == "table" and type(p[instance]) == "table" then for type, val in pairs(p[instance]) do table.insert( rv, type ) end end return rv end function Instance.data_instances( self, plugin, instance, dtype ) local rv = { } local p = self._plugins[plugin] if type(p) == "table" and type(p[instance]) == "table" and type(p[instance][dtype]) == "table" then for i, instance in ipairs(p[instance][dtype]) do table.insert( rv, instance ) end end return rv end function Instance.host_instances( self ) local hosts_path = fs.glob(self._rrddir..'/*') local hosts = { } if hosts_path then local path for path in hosts_path do hosts[#hosts+1] = fs.basename(path) end end return hosts end
apache-2.0
talldan/lua-reactor
tests/specs/reactor/component.lua
1
1099
local componentModule = require('reactor.component') local expectedLifecycle = 'test-lifecycle' local mockReactor = { lifecycle = function() return expectedLifecycle end } local component = componentModule(mockReactor) describe('#component', function() describe('errors', function() it('causes an error if the component definition does not have a `name` property', function() local componentWithoutName = { render = function() end } expect(function() component(componentWithoutName) end) .to.fail() end) it('causes an error if the component definition does not have a `render` property', function() local componentWithoutRender = { name = 'test' } expect(function() component(componentWithoutRender) end) .to.fail() end) end) describe('behaviour', function() it('returns the result of the lifecycle function', function() local output = component{ name = 'test', render = function() end } expect(output) .to.be(expectedLifecycle) end) end) end)
mit
rinstrum/LUA-LIB
src/rinLibrary/K400Setpoint.lua
2
16174
------------------------------------------------------------------------------- --- Setpoint Functions. -- Functions to control setpoint outputs -- @module rinLibrary.Device.Setpoint -- @author Darren Pearson -- @author Merrick Heley -- @copyright 2014 Rinstrum Pty Ltd ------------------------------------------------------------------------------- local math = math local ipairs = ipairs local tonumber = tonumber local bit32 = require "bit" local timers = require 'rinSystem.rinTimers' local dbg = require "rinLibrary.rinDebug" local naming = require 'rinLibrary.namings' local pow2 = require 'rinLibrary.powersOfTwo' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- Submodule function begins here return function (_M, private, deprecated) private.addRegisters{ io_status = 0x0051 } local REG_IO_ENABLE = 0x0054 local REG_SETP_NUM = 0xA400 -- add Repeat to each registers below for each setpoint 0..15 local REG_SETP_REPEAT = 0x0020 local REG_SETP_TYPE = 0xA401 local REG_SETP_OUTPUT = 0xA402 local REG_SETP_LOGIC = 0xA403 local REG_SETP_ALARM = 0xA404 local REG_SETP_NAME = 0xA40E local REG_SETP_SOURCE = 0xA406 local REG_SETP_HYS = 0xA409 local REG_SETP_SOURCE_REG = 0xA40A -- There are no wrapper functions for these five yet. local REG_SETP_TIMING = 0xA410 local REG_SETP_RESET = 0xA411 local REG_SETP_PULSE_NUM = 0xA412 local REG_SETP_TIMING_DELAY = 0xA40C local REG_SETP_TIMING_ON = 0xA40D -- targets are stored in the product database rather than the settings one local REG_SETP_TARGET = 0xB080 -- add setpoint offset (0..15) for the other 16 setpoint targets --- Setpoint Logic Types. --@table Logic -- @field high High -- @field low Low local logicMap = { high = 0, low = 1 } --- Setpoint Alarms Types. --@table Alarms -- @field none No alarm -- @field single Beep once per second -- @field double Beep twice per second -- @field flash Flash the display local alarmTypeMap = { none = 0, single = 1, double = 2, flash = 3 } --- Setpoint Timing Types. --@table Timing -- @field level Level -- @field edge Edge -- @field pulse Pulse -- @field latch Latch local timingMap = { level = 0, edge = 1, pulse = 2, latch = 3 } --- Setpoint Source Types. --@table Source -- @field gross Setpoint uses the gross weight -- @field net Setpoint uses the net weight -- @field disp Setpoint uses the displayed weight -- @field alt_gross Setpoint uses the gross weight in secondary units -- @field alt_net Setpoint uses the net weight in secondary units -- @field alt_disp Setpoint uses the displayed weight in secondary units -- @field piece Setpoint uses the piece count value -- @field reg Setpoint uses the value from the supplied register local SOURCE_REG = 7 local sourceMap private.registerDeviceInitialiser(function() sourceMap = { gross = 0, net = 1, disp = 2, alt_gross = private.nonbatching(3), alt_net = private.nonbatching(4), alt_disp = private.nonbatching(5), piece = private.nonbatching(6), reg = private.nonbatching(SOURCE_REG) } end) --- Setpoint Types. --@table Types -- @field off Setpoint is always inactive -- @field on Setpoint is always active -- @field over Setpoint is active when the source is over the target amount -- @field under Setpoint is active when the source is under the target amount -- @field coz Setpoint is active when the source is in the centre of zero -- @field zero Setpoint is active when the source is in the zero band -- @field net Setpoint is active when net weight is displayed -- @field motion Setpoint is active when the weight is unstable -- @field error Setpoint is active when there is an error -- @field logic_and A binary logic AND is performed on the source with the mask value -- @field logic_or A binary logic OR is performed on the source with the mask value -- @field logic_xor A binary logic XOR is performed on the source with the mask value -- @field scale_ready Setpoint is active when the scale is stable in the zero band for the set period of time (non-batching units only) -- @field scale_exit Setpoint is active when there has been a print since the weight left the zero band (non-batching units only) -- @field tol Setpoint is active when (batching units only) -- @field pause Setpoint is active when (batching units only) -- @field wait Setpoint is active when (batching units only) -- @field run Setpoint is active when (batching units only) -- @field fill Setpoint is active when (batching units only) -- @field buzzer Setpoint is active when the buzzer is beeping local typeMap private.registerDeviceInitialiser(function() typeMap = { off = 0, on = 1, over = 2, under = 3, coz = 4, zero = 5, net = 6, motion = 7, error = 8, logic_and = 9, logic_or = 10, logic_xor = 11, scale_ready = private.nonbatching(12), scale_exit = private.nonbatching(13), tol = private.batching(12), pause = private.batching(13), wait = private.batching(14), run = private.batching(15), fill = private.batching(16), buzzer = private.batching(17) or 14 } end) local lastOutputs = nil local timedOutputs = 0 -- keeps track of which IO are already running off timers -- bits set if under LUA control, clear if under instrument control local lastIOEnable = nil local NUM_SETP = nil ------------------------------------------------------------------------------- -- Write the bit mask of the IOs, bits must first be enabled for comms control. -- @param outp 32 bit mask of IOs -- @see setOutputEnable -- @usage -- -- set IO3 on -- setOutputEnable(0x04) -- setOutputs(0x04) -- @local local function setOutputs(outp) if outp ~= lastOutputs then private.writeRegAsync('io_status', outp) lastOutputs = outp end end ------------------------------------------------------------------------------- -- Enable IOs for comms control. -- @param en 32 bit mask of IOs -- @see setOutputs -- @usage -- -- set IO3 on -- setOutputEnable(0x04) -- setOutputs(0x04) -- @local local function setOutputEnable(en) if en ~= lastIOEnable then private.writeRegAsync(REG_IO_ENABLE, en) lastIOEnable = en end end ------------------------------------------------------------------------------- -- Turns IO Output on. -- @int ... List of IO to turn on 1..32 -- @see enableOutput -- @usage -- -- set IOs 3 and 4 on -- device.turnOn(3, 4) function _M.turnOn(...) local curOutputs = lastOutputs or 0 for _,v in ipairs{...} do if v < 32 and v > 0 and private.checkOutput(v) then curOutputs = bit32.bor(curOutputs, pow2[v-1]) end end setOutputs(curOutputs) end ------------------------------------------------------------------------------- -- Turns IO Output off. -- @int ... List of IO to turn off 1..32 -- @see enableOutput -- @usage -- -- set IOs 3 and 4 off -- device.turnOff(3, 4) function _M.turnOff(...) local curOutputs = lastOutputs or 0 for _,v in ipairs{...} do if v < 32 and v > 0 and private.checkOutput(v) then curOutputs = bit32.band(curOutputs, bit32.bnot(pow2[v-1])) end end setOutputs(curOutputs) end ------------------------------------------------------------------------------- -- Turns IO Output on for a period of time. -- @int IO Output 1..32 -- @int t Time in seconds -- @see enableOutput -- @usage -- -- turn IO 1 on for 5 seconds -- device.turnOnTimed(1, 5) function _M.turnOnTimed(IO, t) if private.checkOutput(IO) then local IOMask = pow2[IO - 1] if bit32.band(timedOutputs, IOMask) == 0 then _M.turnOn(IO) timers.addTimer(0, t, function () timedOutputs = bit32.band(timedOutputs, bit32.bnot(IOMask)) _M.turnOff(IO) end) timedOutputs = bit32.bor(timedOutputs, IOMask) else dbg.warn('IO Timer overlap: ', IO) end end end ------------------------------------------------------------------------------- -- Sets IO Output under LUA control. -- @int ... List of IO to enable (input 1..32) -- @see releaseOutput -- @usage -- device.enableOutput(1,2,3,4) -- device.turnOn(1) -- device.turnOff(2) -- device.turnOnTimed(3, 0.500) -- pulse output 3 for 500 milliseconds -- device.releaseOutput(1,2,3,4) function _M.enableOutput(...) local curIOEnable = lastIOEnable or 0 for i,v in ipairs(arg) do v = tonumber(v) curIOEnable = bit32.bor(curIOEnable, pow2[v-1]) private.setIOkind(v, true) end setOutputEnable(curIOEnable) end ------------------------------------------------------------------------------- -- Sets IO Output under instrument control. -- @int ... List of IO to release to the instrument (input 1..32) -- @see enableOutput -- @usage -- device.enableOutput(1, 2, 3, 4) -- device.turnOn(1) -- device.turnOff(2) -- device.turnOnTimed(3, 0.500) -- pulse output 3 for 500 milliseconds -- device.releaseOutput(1, 2, 3, 4) function _M.releaseOutput(...) local curIOEnable = lastIOEnable or 0 for i,v in ipairs(arg) do v = tonumber(v) curIOEnable = bit32.band(curIOEnable, bit32.bnot(pow2[v-1])) private.setIOkind(v, false) end setOutputEnable(curIOEnable) end -------------------------------------------------------------------------------- -- Returns actual register address for a particular setpoint parameter. -- @int setp Setpoint 1 .. setPointCount() -- @tparam register register device.REG_SETP_* -- @see setPointCount -- @treturn int Address of this register for setpoint setp -- @usage -- -- edit the target for setpoint 3 -- device.editReg(device.setpRegAddress(3, device.REG_SETP_TARGET)) function _M.setpRegAddress(setp, register) local reg = private.getRegisterNumber(register) if (setp > _M.setPointCount()) or (setp < 1) then dbg.error('Setpoint Invalid: ', setp) return nil elseif reg == REG_SETP_TARGET then return reg+setp-1 else return reg+((setp-1)*REG_SETP_REPEAT) end end -------------------------------------------------------------------------------- -- Write to a set point register. -- @int setp Setpoint 1 .. setPointCount() -- @tparam register reg device.REG_SETP_* -- @int v Value to write -- @see setPointCount -- @local local function setpParam(setp, reg, v) local r = private.getRegisterNumber(reg) private.writeReg(_M.setpRegAddress(setp, r), v) end ------------------------------------------------------------------------------- -- Set the number of enabled Setpoints. -- this disables all setpoints above the set number -- @int n Setpoint 1 .. setPointCount() -- @see setPointCount -- @usage -- -- reduce the number of active setpoints to setpoints 1 to 4 temporarily -- device.setNumSetp(4) -- ... -- -- re-enable previously disabled setpoints -- device.setNumSetp(8) function _M.setNumSetp(n) if (n > _M.setPointCount()) or (n < 1) then dbg.error('Setpoint Invalid: ', n) else private.writeReg(REG_SETP_NUM, n-1) end end ------------------------------------------------------------------------------- -- Set Target for setpoint. -- @int setp Setpoint 1 .. setPointCount() -- @int target Target value -- @see setPointCount -- @usage -- -- set the target for setpoint 5 to 150 -- device.setpTarget(5, 150) function _M.setpTarget(setp,target) private.writeReg(_M.setpRegAddress(setp, REG_SETP_TARGET), target) end ------------------------------------------------------------------------------- -- Set which Output the setpoint controls. -- @int setp Setpoint 1 .. setPointCount() -- @int IO Output 1..32, 0 for none -- @see setPointCount -- @usage -- -- make setpoint 12 use IO 3 -- device.setpIO(12, 3) function _M.setpIO(setp, IO) setpParam(setp, REG_SETP_OUTPUT, IO) end ------------------------------------------------------------------------------- -- Set the TYPE of the setpoint controls. -- @int setp Setpoint 1 .. setPointCount() -- @tparam Types sType is setpoint type -- @see setPointCount -- @usage -- -- set setpoint 10 to over -- device.setpType(10, 'over') function _M.setpType(setp, sType) local v = naming.convertNameToValue(sType, typeMap) setpParam(setp, REG_SETP_TYPE, v) end ------------------------------------------------------------------------------- -- Set the Logic for the setpoint controls. -- High means the output will be on when the setpoint is active and -- low means the output will be on when the setpoint is inactive. -- @int setp Setpoint 1 .. setPointCount() -- @tparam Logic lType Setpoint logic type "high" or "low" -- @see setPointCount -- @usage -- -- make setpoint 4 active high -- device.setpLogic(4, 'high') function _M.setpLogic(setp, lType) local v = naming.convertNameToValue(lType, logicMap) setpParam(setp, REG_SETP_LOGIC, v) end ------------------------------------------------------------------------------- -- Set the Alarm for the setpoint. -- The alarm can beep once a second, twice a second or flash the display when -- the setpoint is active -- @int setp Setpoint 1 .. setPointCount() -- @tparam Alarms aType is alarm type -- @see setPointCount -- @usage -- -- disable the alarm on setpoint 11 -- device.setpAlarm(11, 'none') function _M.setpAlarm(setp, aType) local v = naming.convertNameToValue(aType, alarmTypeMap) setpParam(setp, REG_SETP_ALARM, v) end ------------------------------------------------------------------------------- -- Set the Name of the setpoint. -- This name will be displayed when editing targets via the keys. -- @function setpName -- @int setp Setpoint 1 .. setPointCount() -- @string v Setpoint name (8 character string) -- @see setPointCount -- @usage -- -- name setpoint 6 fred -- device.setpName(6, 'fred') function _M.setpName(setp, v) dbg.error("K400Setpoint:", "unable to name setpoints on this device") end private.registerDeviceInitialiser(function() if private.nonbatching(true) then _M.setpName = function(setp, v) setpParam(setp, REG_SETP_NAME, v) end end end) ------------------------------------------------------------------------------- -- Set the data source of the setpoint controls. -- @int setp Setpoint 1 .. setPointCount() -- @tparam Source sType Setpoint source type -- @tparam register reg Register address for setpoints using source register type source data. -- For other setpoint source types parameter reg is not required. -- @see setPointCount -- @usage -- -- set setpoint 1 to use the displayed weight -- device.setpSource(1, 'disp') -- -- -- set setpoint 2 to use the total weight -- device.setpSource(2, 'reg', 'grandtotal') function _M.setpSource(setp, sType, reg) local v = naming.convertNameToValue(sType, sourceMap) setpParam(setp, REG_SETP_SOURCE, v) if (v == SOURCE_REG) and reg then setpParam(setp, REG_SETP_SOURCE_REG, private.getRegisterNumber(reg)) end end ------------------------------------------------------------------------------- -- Set the Hysteresis for of the setpoint controls. -- @int setp Setpoint 1 .. setPointCount() -- @int v Setpoint hysteresis -- @see setPointCount -- @usage -- -- set setpoint 1 target to 1200 and hysteresis to 10 -- device.setTarget(1, 1200) -- device.setpHys(1, 10) function _M.setpHys(setp, v) setpParam(setp, REG_SETP_HYS, _M.toPrimary(v)) end ------------------------------------------------------------------------------- -- Query the number of set points that are available. -- @treturn int The number of set points -- @usage -- local n = device.setPointCount() function _M.setPointCount() if NUM_SETP == nil then local n = private.getRegMax(REG_SETP_NUM) if n ~= nil then NUM_SETP = tonumber(n, 16) + 1 end end return NUM_SETP end end
gpl-3.0
Wiladams/cream
testy/collections.lua
1
2726
--[[ Collections.lua This file contains a few collection classes that are useful for many things. The most basic object is the simple list. From the list is implemented a queue --]] local setmetatable = setmetatable; --[[ A bag behaves similar to a dictionary. You can add values to it using simple array indexing You can also retrieve values based on array indexing The one addition is the '#' length operator works --]] local Bag = {} setmetatable(Bag, { __call = function(self, ...) return self:_new(...); end, }) local Bag_mt = { __index = function(self, key) --print("__index: ", key) return self.tbl[key] end, __newindex = function(self, key, value) --print("__newindex: ", key, value) if value == nil then self.__Count = self.__Count - 1; else self.__Count = self.__Count + 1; end --rawset(self, key, value) self.tbl[key] = value; end, __len = function(self) -- print("__len: ", self.__Count) return self.__Count; end, __pairs = function(self) return pairs(self.tbl) end, } function Bag._new(self, obj) local obj = { tbl = {}, __Count = 0, } setmetatable(obj, Bag_mt); return obj; end -- The basic list type -- This will be used to implement queues and other things local List = {} local List_mt = { __index = List; } function List.new(params) local obj = params or {first=0, last=-1} setmetatable(obj, List_mt) return obj end function List:PushLeft (value) local first = self.first - 1 self.first = first self[first] = value end function List:PushRight(value) local last = self.last + 1 self.last = last self[last] = value end function List:PopLeft() local first = self.first if first > self.last then return nil, "list is empty" end local value = self[first] self[first] = nil -- to allow garbage collection self.first = first + 1 return value end function List:PopRight() local last = self.last if self.first > last then return nil, "list is empty" end local value = self[last] self[last] = nil -- to allow garbage collection self.last = last - 1 return value end --[[ Stack --]] local Stack = {} setmetatable(Stack,{ __call = function(self, ...) return self:new(...); end, }); local Stack_mt = { __len = function(self) return self.Impl.last - self.Impl.first+1 end, __index = Stack; } Stack.new = function(self, ...) local obj = { Impl = List.new(); } setmetatable(obj, Stack_mt); return obj; end Stack.len = function(self) return self.Impl.last - self.Impl.first+1 end Stack.push = function(self, item) return self.Impl:PushRight(item); end Stack.pop = function(self) return self.Impl:PopRight(); end return { Bag = Bag; List = List; Stack = Stack; }
mit
AdamGagorik/darkstar
scripts/zones/Apollyon/mobs/Water_Elemental.lua
49
2612
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [1] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [2] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead()==true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/RuAun_Gardens/mobs/Groundskeeper.lua
5
1348
----------------------------------- -- Area: RuAun Gardens -- MOB: Groundskeeper -- Note: Place holder Despot ----------------------------------- require("scripts/zones/RuAun_Gardens/MobIDs"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) checkRegime(ally,mob,143,2); checkRegime(ally,mob,144,1); -- Get Groundskeeper ID and check if it is a PH of Despot local mobID = mob:getID(); -- Check if Groundskeeper is within the Despot_PH table if (Despot_PH[mobID] ~= nil) then -- printf("%u is a PH",mobID); -- Get Despot previous ToD local Despot_ToD = GetServerVariable("[POP]Despot"); -- Check if Despot window is open, and there is not an Despot popped already(ACTION_NONE = 0) if (Despot_ToD <= os.time(t) and GetMobAction(Despot) == 0) then -- printf("Despot window open"); -- Give Groundskeeper 5 percent chance to pop Despot if (math.random(1,20) == 5) then -- printf("Despot will pop"); GetMobByID(Despot):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Despot", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/chunk_of_sweet_lizard.lua
18
1244
----------------------------------------- -- ID: 5738 -- Item: chunk_of_sweet_lizard -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 5 -- MP 5 -- Dexterity 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5738); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 5); target:addMod(MOD_MP, 5); target:addMod(MOD_DEX, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 5); target:delMod(MOD_MP, 5); target:delMod(MOD_DEX, 1); end;
gpl-3.0
r1k/vlc
share/lua/intf/luac.lua
116
2333
--[==========================================================================[ luac.lua: lua compilation module for VLC (duplicates luac) --[==========================================================================[ 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. --]==========================================================================] usage = [[ To compile a lua script to bytecode (luac) run: vlc -I luaintf --lua-intf --lua-config 'luac={input="file.lua",output="file.luac"}' Output will be similar to that of the luac command line tool provided with lua with the following arguments: luac -o file.luac file.lua ]] require "string" require "io" function compile() vlc.msg.info("About to compile lua file") vlc.msg.info(" Input is '"..tostring(config.input).."'") vlc.msg.info(" Output is '"..tostring(config.output).."'") if not config.input or not config.output then vlc.msg.err("Input and output config options must be set") return false end local bytecode, msg = loadfile(config.input) if not bytecode then vlc.msg.err("Error while loading file '"..config.input.."': "..msg) return false end local output, msg = io.open(config.output, "wb") if not output then vlc.msg.err("Error while opening file '"..config.output.."' for output: "..msg) return false else output:write(string.dump(bytecode)) return true end end if not compile() then for line in string.gmatch(usage,"([^\n]+)\n*") do vlc.msg.err(line) end end vlc.misc.quit()
gpl-2.0
AdamGagorik/darkstar
scripts/globals/items/slab_of_ruszor_meat.lua
18
1340
----------------------------------------- -- ID: 5755 -- Item: Slab of Ruszor Meat -- Food Effect: 30Min, Galka only ----------------------------------------- -- Strength 5 -- Intelligence -7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:getRace() ~= 8) then result = 247; end if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5755); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_INT, -7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_INT, -7); end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/sazanbaligi.lua
18
1311
----------------------------------------- -- ID: 5459 -- Item: Sazanbaligi -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 4 -- Mind -6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5459); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -6); end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/silken_smile.lua
18
1218
----------------------------------------- -- ID: 5628 -- Item: Silken Smile -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- Intelligence 2 -- MP Recovered while healing 7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5628); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 2); target:addMod(MOD_MPHEAL, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 2); target:delMod(MOD_MPHEAL, 7); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Sacrarium/npcs/Small_Keyhole.lua
29
1201
----------------------------------- -- NPC: Small Keyhole -- Area: Sacrarium -- @pos 99.772 -1.614 51.545 28 ----------------------------------- package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Sacrarium/TextIDs"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SmallKeyholeID = npc:getID(); local DoorID = GetNPCByID(SmallKeyholeID):getID() - 3; if (player:hasKeyItem(TEMPLE_KNIGHT_KEY)) then GetNPCByID(DoorID):openDoor(15); else player:messageSpecial(SMALL_KEYHOLE); end end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1659,1) and trade:getItemCount() == 1) then player:messageSpecial(CORAL_KEY_TRADE); SetServerVariable("SACRARIUM_Coral_Key_trade",os.time()); player:tradeComplete(); -- print(os.time()); end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) end;
gpl-3.0
sjznxd/lc-20130204
modules/niu/luasrc/model/cbi/niu/wireless/brdevice.lua
51
1132
--[[ LuCI - Lua Configuration Interface Copyright 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local niulib = require "luci.niulib" m = Map("wireless", translate("Join a local WDS network")) s = m:section(NamedSection, "bridge", "wifi-iface", translate("Wireless Radio Device"), translate( "Select the wireless radio device that should be used to run the interface.".. " Note that wireless radios will not show up here if you already use".. " them for other wireless services and are not capable of being used by".. " more than one service simultaneously or run this specific service at all.")) s.anonymous = true s.addremove = false l = s:option(ListValue, "device", translate("Wireless Device")) for _, wifi in ipairs(niulib.wifi_get_available("bridge", {atheros = true, mac80211 = true})) do l:value(wifi, translate("WLAN-Adapter (%s)") % wifi) end l:value("none", translate("Disable Bridge")) return m
apache-2.0
master00041/gpsuper
plugins/català.lua
1
19139
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -- Translated by: @gtrabal -- -- -- -------------------------------------------------- local LANG = 'cat' 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ó versió 0.1') ------------- -- Plugins -- ------------- -- global plugins -- set_text(LANG, 'require_sudo', 'Aquest plugin requereix permissos de sudo') set_text(LANG, 'require_admin', 'Aquest plugin requereix permissos administrador o superior') set_text(LANG, 'require_mod', 'Aquest plugin requereix permissos mod o superior') -- Spam.lua -- set_text(LANG, 'reportUser', 'USUARI') set_text(LANG, 'reportReason', 'Motiu del report') set_text(LANG, 'reportGroup', 'Grup') set_text(LANG, 'reportMessage', 'Missatge') set_text(LANG, 'allowedSpamT', 'Spam permès en aquest grup') set_text(LANG, 'allowedSpamL', 'Spam permès en aquest supergrup') set_text(LANG, 'notAllowedSpamT', 'Spam no permès en aquest grup') set_text(LANG, 'notAllowedSpamL', 'Spam no permès en aquest supergrup') -- bot.lua -- set_text(LANG, 'botOn', 'Estic llest, som-hi!') set_text(LANG, 'botOff', 'No tinc res a fer aquí') -- settings.lua -- set_text(LANG, 'user', 'Usuari') set_text(LANG, 'isFlooding', 'està fent flood.') set_text(LANG, 'noStickersT', 'Stickers no permesos en aquest grup.') set_text(LANG, 'noStickersL', 'Stickers no permesos en aquest supergrup.') set_text(LANG, 'stickersT', 'Stickers permesos en aquest grup.') set_text(LANG, 'stickersL', 'Stickers permesos en aquest supergrup.') set_text(LANG, 'LinksT', 'Links permesos en aquest grup.') set_text(LANG, 'LinksL', 'Links permesos en aquest supergrup.') set_text(LANG, 'noLinksT', 'Links no permesos en aquest grup.') set_text(LANG, 'noLinksL', 'Links no permesos en aquest supergrup.') set_text(LANG, 'gifsT', 'Gifs permesos en aquest grup.') set_text(LANG, 'gifsL', 'Gifs permesos en aquest supergrup.') set_text(LANG, 'noGifsT', 'Gifs no permesos en aquest grup.') set_text(LANG, 'noGifsL', 'Gifs no permesos en aquest supergrup.') set_text(LANG, 'photosT', 'Fotos permeses en aquest grup.') set_text(LANG, 'photosL', 'Fotos permeses en aquest supergrup.') set_text(LANG, 'noPhotosT', 'Fotos no permeses en aquest grup.') set_text(LANG, 'noPhotosL', 'Fotos no permeses en aquest supergrup.') set_text(LANG, 'botsT', 'Bots permesos en aquest grup.') set_text(LANG, 'botsL', 'Bots permesos en aquest supergrup.') set_text(LANG, 'noBotsT', 'Bots no permesos en aquest grup.') set_text(LANG, 'noBotsL', 'Bots no permesos en aquest supergrup.') set_text(LANG, 'arabicT', 'Àrab permès en aquest grup.') set_text(LANG, 'arabicL', 'Àrab permès en aquest supergrup.') set_text(LANG, 'noArabicT', 'Àrab no permès en aquest grup.') set_text(LANG, 'noArabicL', 'Àrab no permès en aquest supergrup.') set_text(LANG, 'audiosT', 'Àudios permesos en aquest grup.') set_text(LANG, 'audiosL', 'Àudios permesos en aquest supergrup.') set_text(LANG, 'noAudiosT', 'Àudios no permesos en aquest grup.') set_text(LANG, 'noAudiosL', 'Àudios no permesos en aquest supergrup.') set_text(LANG, 'kickmeT', 'Autoexpulsió permesa en aquest grup.') set_text(LANG, 'kickmeL', 'Autoexpulsió permesa en aquest supergrup.') set_text(LANG, 'noKickmeT', 'Autoexpulsió no permesa en aquest grup.') set_text(LANG, 'noKickmeL', 'Autoexpulsió no permesa en aquest supergrup.') set_text(LANG, 'floodT', 'Flood permès en aquest grup.') set_text(LANG, 'floodL', 'Flood permès en aquest supergrup.') set_text(LANG, 'noFloodT', 'Flood no permès en aquest grup.') set_text(LANG, 'noFloodL', 'Flood no permès en aquest supergrup.') set_text(LANG, 'floodTime', 'Temps màxim de flood establert a ') set_text(LANG, 'floodMax', 'Número màxim de missatges flood establert a ') set_text(LANG, 'gSettings', 'Configuració del grup') set_text(LANG, 'sSettings', 'Configuració del supergrup') set_text(LANG, 'allowed', 'permès') set_text(LANG, 'noAllowed', 'no permès') set_text(LANG, 'noSet', 'no establert') set_text(LANG, 'stickers', 'Stickers') set_text(LANG, 'links', 'Enllaços') set_text(LANG, 'arabic', 'àrab') set_text(LANG, 'bots', 'Bots') set_text(LANG, 'gifs', 'Gifs') set_text(LANG, 'photos', 'Fotos') set_text(LANG, 'audios', 'Àudios') set_text(LANG, 'kickme', 'Autoexpulsió') set_text(LANG, 'spam', 'Spam') set_text(LANG, 'gName', 'Nom del grup') set_text(LANG, 'flood', 'Flood') set_text(LANG, 'language', 'Idioma') set_text(LANG, 'mFlood', 'Límit de flood') set_text(LANG, 'tFlood', 'Temps de flood') set_text(LANG, 'setphoto', 'Establir foto') set_text(LANG, 'photoSaved', 'Foto guardada!') set_text(LANG, 'photoFailed', 'Error, intenta de nou!') set_text(LANG, 'setPhotoAborted', 'Parant el procés per establir foto...') set_text(LANG, 'sendPhoto', 'Envia una foto siusplau') set_text(LANG, 'chatSetphoto', 'Ara tu pots establir foto en aquest xat.') set_text(LANG, 'channelSetphoto', 'Ara tu pots establir foto en aquest canal.') set_text(LANG, 'notChatSetphoto', 'Ara tu no pots establir foto en aquest xat.') set_text(LANG, 'notChannelSetphoto', 'Ara tu no pots establir foto en aquest canal.') set_text(LANG, 'setPhotoError', 'Siusplau, activa la configuració per establir foto (setphoto settings).') set_text(LANG, 'linkSaved', 'El link ha estat guardat') set_text(LANG, 'groupLink', 'Link del grup') set_text(LANG, 'sGroupLink', 'Link del supergrup') set_text(LANG, 'noLinkSet', 'No hi ha cap link establert. Siusplau, afegeix un amb #setlink [Link].') set_text(LANG, 'chatRename', 'Ara pots renombrar el xat.') set_text(LANG, 'channelRename', 'Ara pots renombrar el supergrup.') set_text(LANG, 'notChatRename', 'Ara no pots renombrar el xat.') set_text(LANG, 'notChannelRename', 'Ara no pots renombrar el supergrup.') set_text(LANG, 'lockMembersT', 'El número de membres del xat ha estat bloquejat.') set_text(LANG, 'lockMembersL', 'El número de membres del supergrup ha estat bloquejat.') set_text(LANG, 'notLockMembersT', 'El número de membres del xat ha estat desbloquejat.') set_text(LANG, 'notLockMembersL', 'El número de membres del supergrup ha estat desbloquejat.') set_text(LANG, 'langUpdated', 'La llengua ha estat cambiada a: ') set_text(LANG, 'chatUpgrade', 'Xat convertit en supergrup amb èxit.') set_text(LANG, 'notInChann', 'Aquest xat ja és supergrup') set_text(LANG, 'desChanged', 'La descripció del supergrup ha estat canviada.') set_text(LANG, 'desOnlyChannels', 'La descripció només pot ser canviada en supergrups.') set_text(LANG, 'muteAll', 'Tots els membres estan silenciats.') set_text(LANG, 'unmuteAll', 'Tots els membres poden parlar ara.') set_text(LANG, 'muteAllX:1', 'Aquest grup ha estat silenciat durant') set_text(LANG, 'muteAllX:2', 'segons.') set_text(LANG, 'createGroup:1', 'Grup') set_text(LANG, 'createGroup:2', 'creat.') set_text(LANG, 'newGroupWelcome', 'Benvingut al teu nou grup.') -- export_gban.lua -- set_text(LANG, 'accountsGban', 'comptes globalment banejades') -- giverank.lua -- set_text(LANG, 'alreadyAdmin', 'Aquest usuari ja és admin.') set_text(LANG, 'alreadyMod', 'Aquest usuari ja és mod.') set_text(LANG, 'newAdmin', 'Nou admin') set_text(LANG, 'newMod', 'Nou mod') set_text(LANG, 'nowUser', 'ara és un usuari.') set_text(LANG, 'modList', 'Llista de mods') set_text(LANG, 'adminList', 'Llista de administradors') set_text(LANG, 'modEmpty', 'La llista de mods està buida en aquest xat.') set_text(LANG, 'adminEmpty', 'La llista de administradors està buida.') -- id.lua -- set_text(LANG, 'user', 'Usuari') set_text(LANG, 'supergroupName', 'Nom del SuperGrup') set_text(LANG, 'chatName', 'Nom del xat') set_text(LANG, 'supergroup', 'SuperGrup') set_text(LANG, 'chat', 'Xat') -- moderation.lua -- set_text(LANG, 'userUnmuted:1', 'El membre') set_text(LANG, 'userUnmuted:2', 'ara pot parlar.') set_text(LANG, 'userMuted:1', 'El membre') set_text(LANG, 'userMuted:2', 'està silenciat.') set_text(LANG, 'kickUser:1', 'Usuari') set_text(LANG, 'kickUser:2', 'expulsat.') set_text(LANG, 'banUser:1', 'Usuari') set_text(LANG, 'banUser:2', 'banejat.') set_text(LANG, 'unbanUser:1', 'Usuari') set_text(LANG, 'unbanUser:2', 'està desbanejat.') set_text(LANG, 'gbanUser:1', 'Usuari') set_text(LANG, 'gbanUser:2', 'globalment banejat.') set_text(LANG, 'ungbanUser:1', 'Usuari') set_text(LANG, 'ungbanUser:2', 'desbanejat globalment.') set_text(LANG, 'addUser:1', 'Usuari') set_text(LANG, 'addUser:2', 'afegit al xat.') set_text(LANG, 'addUser:3', 'afegit al supergrup.') set_text(LANG, 'kickmeBye', 'adéu.') -- plugins.lua -- set_text(LANG, 'plugins', 'Plugins') set_text(LANG, 'installedPlugins', 'plugins instal·lats.') set_text(LANG, 'pEnabled', 'activats.') set_text(LANG, 'pDisabled', 'desactivats.') set_text(LANG, 'isEnabled:1', 'Plugin') set_text(LANG, 'isEnabled:2', 'està activat.') set_text(LANG, 'notExist:1', 'Plugin') set_text(LANG, 'notExist:2', 'no existeix.') set_text(LANG, 'notEnabled:1', 'Plugin') set_text(LANG, 'notEnabled:2', 'no activat.') set_text(LANG, 'pNotExists', 'No existeix el plugin.') set_text(LANG, 'pDisChat:1', 'Plugin') set_text(LANG, 'pDisChat:2', 'desactivat en aquest xat.') set_text(LANG, 'anyDisPlugin', 'No hi ha plugins desactivats.') set_text(LANG, 'anyDisPluginChat', 'No hi ha plugins desactivats en aquest xat.') set_text(LANG, 'notDisabled', 'Aquest plugin no està desactivat') set_text(LANG, 'enabledAgain:1', 'Plugin') set_text(LANG, 'enabledAgain:2', 'està activat de nou') -- commands.lua -- set_text(LANG, 'commandsT', 'Ordres') set_text(LANG, 'errorNoPlug', 'Aquest plugin no existeix o no té ordres.') -- rules.lua -- set_text(LANG, 'setRules', 'Les normes del xat han estat establertes.') set_text(LANG, 'remRules', 'Les normes del xat han estat eliminades.') ------------ -- Usages -- ------------ -- bot.lua -- set_text(LANG, 'bot:0', 2) set_text(LANG, 'bot:1', '#bot on: activa el bot al xat actual.') set_text(LANG, 'bot:2', '#bot off: desactiva el bot al xat actual.') -- commands.lua -- set_text(LANG, 'commands:0', 2) set_text(LANG, 'commands:1', '#commands: Mostra les ordres per a tots els plugins.') set_text(LANG, 'commands:2', '#commands [plugin]: ordres per aquest plugin.') -- export_gban.lua -- set_text(LANG, 'export_gban:0', 2) set_text(LANG, 'export_gban:1', '#gbans installer: Retorna un arxiu lua instalador per a compartir gbans i afegir-ho a un altre bot amb una única ordre.') set_text(LANG, 'export_gban:2', '#gbans list: Retorna un arxiu amb la llista de gbans.') -- gban_installer.lua -- set_text(LANG, 'gban_installer:0', 1) set_text(LANG, 'gban_installer:1', '#install gbans: Afegeix una llista de gbans a la teva base de dates redis.') -- giverank.lua -- set_text(LANG, 'giverank:0', 9) set_text(LANG, 'giverank:1', '#rank admin (reply): converteixes la persona que respons en administrador.') set_text(LANG, 'giverank:2', '#rank admin <user_id>/<user_name>: afegeix un administrador mitjançant la seva ID/usuari.') set_text(LANG, 'giverank:3', '#rank mod (reply): converteixes la persona que respons en moderador.') set_text(LANG, 'giverank:4', '#rank mod <user_id>/<user_name>: afegeix un moderador mitjançant la seva ID/usuari.') set_text(LANG, 'giverank:5', '#rank guest (reply): borra el rang de administrador a la persona que respons.') set_text(LANG, 'giverank:6', '#rank guest <user_id>/<user_name>: borra el rang de administrador mitjançant el seu ID/usuari.') set_text(LANG, 'giverank:7', '#admins: llista de tots els admins.') set_text(LANG, 'giverank:8', '#mods: llista de tots els mods.') set_text(LANG, 'giverank:9', '#members: llista de tots els membres del xat.') -- id.lua -- set_text(LANG, 'id:0', 6) set_text(LANG, 'id:1', '#id: retorna la teva id i la del xat si estas en algun.') set_text(LANG, 'id:2', '#ids chat: retorna les IDs dels membres actuals del grup.') set_text(LANG, 'id:3', '#ids channel: retorna les IDs dels membres actuals del supergrup.') set_text(LANG, 'id:4', '#id <user_name>: retorna la ID del usuari present al xat.') set_text(LANG, 'id:5', '#whois <user_id>/<user_name>: Retorna la ID/alies del usuari.') set_text(LANG, 'id:6', '#whois (reply): Retorna la ID del usuari.') -- moderation.lua -- set_text(LANG, 'moderation:0', 18) set_text(LANG, 'moderation:1', '#add: responent un missatge, afegiras a aquest usuari al grup o supergrup actual.') set_text(LANG, 'moderation:2', '#add <id>/<username>: afegeix a un usuari, per ID o alies, al grup o supergrup actual.') set_text(LANG, 'moderation:3', '#kick: responent a un missatge, expulsará al membre del grup o supergrup actual.') set_text(LANG, 'moderation:4', '#kick <id>/<username>: expulsa a un usuari, pel seu ID/alies del grup o supergrup actual.') set_text(LANG, 'moderation:5', '#kickme: autokick.') set_text(LANG, 'moderation:6', '#ban: responent un missatge, expulsarà i banejarà a aquest usuari del grup o supergrup actual.') set_text(LANG, 'moderation:7', '#ban <id>/<username>: expulsa i baneja a un usuari pel seu ID/alies, impedint-ne el seu retorn.') set_text(LANG, 'moderation:8', '#unban: responent a un missatge, desbaneja a aquest usuari del grup o supergrup.') set_text(LANG, 'moderation:9', '#unban <id>/<username>: desbaneja al membre pel seu ID/alies del grup o supergrup.') set_text(LANG, 'moderation:10', '#gban: responent a un missatge, el membre serà banejat de tots els grups i supergrups.') set_text(LANG, 'moderation:11', '#gban <id>/<username>: expulsa i baneja al membre, pel seu ID/ales de tots els grups o supergrups impedint-ne el retorn.') set_text(LANG, 'moderation:12', '#ungban: responent a un missatge, el membre serà desbanejat de tots els grups i supergrups.') set_text(LANG, 'moderation:13', '#ungban <id>/<username>: treu el ban al membre, pel seu ID/alies de tots els grups i supergrups.') set_text(LANG, 'moderation:14', '#mute: responent a un missatge silencia al membre eliminant els missatges del supergrup actual.') set_text(LANG, 'moderation:15', '#mute <id>/<username>: silencia a un membre, pel seu ID/alies, eliminant els seus missatges al supergrup actual.') set_text(LANG, 'moderation:16', '#unmute: respondent a un missatge, treu el silenci al membre.') set_text(LANG, 'moderation:17', '#unmute <id>/<username>: treu el silenci al membre, pel seu ID/alies, al supergrup actual.') set_text(LANG, 'moderation:18', '#rem: responent a un missatge, aquest missatge serà borrat.') -- settings.lua -- set_text(LANG, 'settings:0', 19) set_text(LANG, 'settings:1', '#settings stickers enable/disable: podràs enviar stickers quan estigui actiu.') set_text(LANG, 'settings:2', '#settings links enable/disable: podràs enviar links quan estigui actiu.') set_text(LANG, 'settings:3', '#settings arabic enable/disable: podràs parlar en àrab i persa quan estigui actiu.') set_text(LANG, 'settings:4', '#settings bots enable/disable: podràs convidar bots al grup quan estigui actiu.') set_text(LANG, 'settings:5', '#settings gifs enable/disable: podràs enviar gifs quan estigui actiu.') set_text(LANG, 'settings:6', '#settings photos enable/disable: podràs enviar fotos quan estigui actiu.') set_text(LANG, 'settings:7', '#settings audios enable/disable: podràs enviar àudios quan estigui actiu.') set_text(LANG, 'settings:8', '#settings kickme enable/disable: els usuaris podran autoexpulsar-se quan estigui actiu.') set_text(LANG, 'settings:9', '#settings spam enable/disable: podràs enviar enllaços de spam quan estigui actiu.') set_text(LANG, 'settings:10', '#settings setphoto enable/disable: si un usuari canvia la foto del grup, el bot la canviarà per la foto guardada quan estigui actiu.') set_text(LANG, 'settings:11', '#settings setname enable/disable: si un usuari canvia el nom del grup, el bot la canviarà per la foto guardada quan estigui actiu.') set_text(LANG, 'settings:12', '#settings lockmember enable/disable: el bot expulsarà a tota la gent que entri al grup quan estigui actiu.') set_text(LANG, 'settings:13', '#settings floodtime <secs>: estableix el temps de mesurament del flood.') set_text(LANG, 'settings:14', '#settings maxflood <secs>: estableix el número de missatges màxim en un temps determinat per a ser considerat flood.') set_text(LANG, 'settings:15', '#setname <título del grupo>: el bot canviarà el nom del grup.') set_text(LANG, 'settings:16', '#setphoto <después envía la foto>: el bot canviarà la foto del grup.') set_text(LANG, 'settings:17', '#lang <language (en, es...)>: canvia la llengua del bot.') set_text(LANG, 'settings:18', '#setlink <link>: guarda el link del grup.') set_text(LANG, 'settings:19', '#link: mostra el link del grup.') -- plugins.lua -- set_text(LANG, 'plugins:0', 4) set_text(LANG, 'plugins:1', '#plugins: mostra una llista de tots els plugins.') set_text(LANG, 'plugins:2', '#plugins <enable>/<disable> [plugin]: activa/desactiva el plugin especificat.') set_text(LANG, 'plugins:3', '#plugins <enable>/<disable> [plugin] chat: activa/desactiva el plugin especificat, només al actual grup/supergrup.') set_text(LANG, 'plugins:4', '#plugins reload: recarrega tots els plugins.') -- version.lua -- set_text(LANG, 'version:0', 1) set_text(LANG, 'version:1', '#version: mostra la versió del bot.') -- version.lua -- set_text(LANG, 'rules:0', 1) set_text(LANG, 'rules:1', '#rules: mostra les normes del xat.') if matches[1] == 'install' then return '?? El llenguatge català ha estat instal·lat a la seva base de dates.' elseif matches[1] == 'update' then return '?? El llenguatge català ha estat actualitzat a la seva base de dates.' end else return "Aquest plugin requereix de permisos sudo." end end return { patterns = { '[!/#](install) (catalan_lang)$', '[!/#](update) (catalan_lang)$' }, run = run, } Status API Training Shop Blog About © 2016 GitHub, Inc. Terms Privacy Security Contact Help
gpl-2.0
yaoqi/Atlas
lib/proxy/test.lua
44
6366
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] module("proxy.test", package.seeall) local function boom(msg, usermsg) local trace = debug.traceback() local e = { message = msg, testmessage = usermsg, } e.trace = "\n" local after_assert = false for line in trace:gmatch("([^\n]*)\n") do if after_assert then e.trace = e.trace .. line .. "\n" else after_assert = line:find("assert", 1, true) end end error(("%s (%s): %s"):format(e.message or "assertion failed", e.testmessage or "", e.trace)) end function assertEquals(is, expected, msg) if type(is) ~= type(expected) then boom(string.format("got type '%s' for <%s>, expected type '%s' for <%s>", type(is), tostring(is), type(expected), tostring(expected)), msg) end if is ~= expected then boom(string.format("got '%s' <%s>, expected '%s' <%s>", tostring(is), type(is), tostring(expected), type(expected)), msg) end end function assertNotEquals(is, expected, msg) if is == expected then boom(string.format("got '%s' <%s>, expected all but '%s' <%s>", tostring(is), type(is), tostring(expected), type(expected)), msg) end end --- -- base class for all tests -- -- overwrite setUp() and tearDown() when needed BaseTest = { } function BaseTest:setUp() end function BaseTest:tearDown() end function BaseTest:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end -- extend the base class ProxyBaseTest = BaseTest:new() function ProxyBaseTest:setDefaultScope() -- the fake script scope local proxy = { global = { config = {} }, queries = { data = {}, append = function (self, id, query, attr) self.data[#self.data + 1] = { id = id, query = query, attr = attr } end, reset = function (self) self.data = { } end, len = function (self) return #self.data end }, connection = { server = { }, client = { } }, PROXY_SEND_RESULT = 1, PROXY_SEND_QUERY = 2, PROXY_IGNORE_RESULT = 4, COM_SLEEP = 0, COM_QUIT = 1, COM_INIT_DB = 2, COM_QUERY = 3, COM_FIELD_LIST = 4, COM_CREATE_DB = 5, COM_DROP_DB = 6, COM_REFRESH = 7, COM_SHUTDOWN = 8, COM_STATISTICS = 9, COM_PROCESS_INFO = 10, COM_CONNECT = 11, COM_PROCESS_KILL = 12, COM_DEBUG = 13, COM_PING = 14, COM_TIME = 15, COM_DELAYED_INSERT = 16, COM_CHANGE_USER = 17, COM_BINLOG_DUMP = 18, COM_TABLE_DUMP = 19, COM_CONNECT_OUT = 20, COM_REGISTER_SLAVE = 21, COM_STMT_PREPARE = 22, COM_STMT_EXECUTE = 23, COM_STMT_SEND_LONG_DATA = 24, COM_STMT_CLOSE = 25, COM_STMT_RESET = 26, COM_SET_OPTION = 27, COM_STMT_FETCH = 28, COM_DAEMON = 29, MYSQLD_PACKET_OK = 0, MYSQLD_PACKET_EOF = 254, MYSQLD_PACKET_ERR = 255, MYSQL_TYPE_STRING = 254, response = { } } -- make access to the proxy.* strict setmetatable(proxy, { __index = function (tbl, key) error(("proxy.[%s] is unknown, please adjust the mock here"):format(key)) end }) _G.proxy = proxy end --- -- result class for the test suite -- -- feel free to overwrite print() to match your needs Result = { passed = 0, failed = 0, failed_tests = { } } function Result:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function Result:print() if self.failed > 0 then print("FAILED TESTS:") print(string.format("%-20s %-20s %-20s", "Class", "Testname", "Message")) print(string.rep("-", 63)) for testclass, methods in pairs(self.failed_tests) do for methodname, err in pairs(methods) do print(string.format("%-20s %-20s %-20s\n%s", testclass, methodname, tostring(err.message), tostring(err.trace))) print(string.rep("-", 63)) end end end print(string.format("%.02f%%, %d passed, %d failed", self.passed * 100 / ( self.passed + self.failed), self.passed, self.failed)) end --- -- bundle tests into a test-suite -- -- calls the setUp() and tearDown() methods before and after each -- test Suite = { } function Suite:new(o) o = o or {} setmetatable(o, self) self.__index = self assert(o.result, "Suite:new(...) has be called with result = Result:new() to init the result handler") return o end function Suite:run(runclasses) if not runclasses then runclasses = { } for testclassname, testclass in pairs(_G) do -- exec all the classes which start with Test if type(testclass) == "table" and testclassname:sub(1, 4) == "Test" then runclasses[#runclasses + 1] = testclassname end end end for runclassndx, testclassname in pairs(runclasses) do -- init the test-script local testclass = assert(_G[testclassname], "Class " .. testclassname .. " isn't known") local t = testclass:new() for testmethodname, testmethod in pairs(_G[testclassname]) do -- execute all the test functions if type(testmethod) == "function" and testmethodname:sub(1, 4) == "test" then t:setUp() local ok, err = pcall(t[testmethodname], t) if not ok then self.result.failed = self.result.failed + 1 self.result.failed_tests[testclassname] = self.result.failed_tests[testclassname] or { } if type(err) == "string" then self.result.failed_tests[testclassname][testmethodname] = { message = "compile error", trace = "\n "..err } else self.result.failed_tests[testclassname][testmethodname] = err end else self.result.passed = self.result.passed + 1 end t:tearDown() end end end end function Suite:exit_code() return ((self.result.failed == 0) and 0 or 1) end -- export the assert functions globally _G.assertEquals = assertEquals _G.assertNotEquals = assertNotEquals
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Norg/npcs/Jaucribaix.lua
17
10694
----------------------------------- -- Area: Norg -- NPC: Jaucribaix -- Starts and Finishes Quest: Forge Your Destiny, The Sacred Katana, Yomi Okuri, A Thief in Norg!? -- @pos 91 -7 -8 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); if (player:getQuestStatus(OUTLANDS,FORGE_YOUR_DESTINY) == QUEST_ACCEPTED) then if (trade:hasItemQty(1153,1) and trade:hasItemQty(1152,1) and count == 2) then -- Trade Sacred branch and Bomb Steel player:startEvent(0x001b); end end if (player:getQuestStatus(OUTLANDS,THE_SACRED_KATANA) == QUEST_ACCEPTED) then if (player:hasKeyItem(HANDFUL_OF_CRYSTAL_SCALES) and trade:hasItemQty(17809,1) and count == 1) then -- Trade Mumeito player:startEvent(0x008d); end end if (player:getQuestStatus(OUTLANDS,A_THIEF_IN_NORG) == QUEST_ACCEPTED) then if (player:hasKeyItem(CHARRED_HELM) and trade:hasItemQty(823,1) and count == 1) then -- Trade Gold Thread player:startEvent(0x00a2); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ForgeYourDestiny = player:getQuestStatus(OUTLANDS, FORGE_YOUR_DESTINY); local theSacredKatana = player:getQuestStatus(OUTLANDS,THE_SACRED_KATANA); local yomiOkuri = player:getQuestStatus(OUTLANDS,YOMI_OKURI); local aThiefinNorg = player:getQuestStatus(OUTLANDS,A_THIEF_IN_NORG); local mLvl = player:getMainLvl(); local mJob = player:getMainJob(); if (mLvl >= ADVANCED_JOB_LEVEL and ForgeYourDestiny == QUEST_AVAILABLE) then player:startEvent(0x0019,1153,1152); -- Sacred branch, Bomb Steel elseif (ForgeYourDestiny == QUEST_ACCEPTED) then local swordTimer = player:getVar("ForgeYourDestiny_timer"); if (swordTimer > os.time()) then player:startEvent(0x001c,(swordTimer - os.time())/144); elseif (swordTimer < os.time() and swordTimer ~= 0) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(CARRYING_TOO_MUCH_ALREADY); else player:startEvent(0x001d, 17809); -- Finish Quest "Forge Your Destiny" end else player:startEvent(0x001a); end elseif (theSacredKatana == QUEST_AVAILABLE and mJob == 12 and mLvl >= AF1_QUEST_LEVEL) then player:startEvent(0x008b); -- Start Quest "The Sacred Katana" elseif (theSacredKatana == QUEST_ACCEPTED) then if (player:hasItem(17809) == false) then player:startEvent(0x008f); -- CS without Mumeito else player:startEvent(0x008c); -- CS with Mumeito end elseif (theSacredKatana == QUEST_COMPLETED and yomiOkuri == QUEST_AVAILABLE and mJob == 12 and mLvl >= AF2_QUEST_LEVEL) then if (player:needToZone() or tonumber(os.date("%j")) == player:getVar("Wait1DayForYomiOkuri_date")) then player:startEvent(0x008e); -- Need to zone and wait midnight after "The Sacred Katana" else player:startEvent(0x0092); -- Start Quest "Yomi Okuri" end elseif (yomiOkuri == QUEST_ACCEPTED) then local yomiOkuriCS = player:getVar("yomiOkuriCS"); local yomotsuFeather = player:hasKeyItem(YOMOTSU_FEATHER); if (yomiOkuriCS <= 3 and yomotsuFeather == false) then player:startEvent(0x0093); elseif (yomotsuFeather) then player:startEvent(0x0098); elseif (yomiOkuriCS == 4 and (tonumber(os.date("%j")) == player:getVar("Wait1DayForYomiOkuri2_date") or player:needToZone())) then player:startEvent(0x0099); elseif (yomiOkuriCS == 4) then player:startEvent(0x009a); elseif (yomiOkuriCS == 5 and player:hasKeyItem(YOMOTSU_HIRASAKA)) then player:startEvent(0x009b); elseif (player:hasKeyItem(FADED_YOMOTSU_HIRASAKA)) then player:startEvent(0x009c); -- Finish Quest "Yomi Okuri" end elseif (yomiOkuri == QUEST_COMPLETED and aThiefinNorg == QUEST_AVAILABLE and mJob == 12 and mLvl >= 50) then if (player:needToZone() or tonumber(os.date("%j")) == player:getVar("Wait1DayForAThiefinNorg_date")) then player:startEvent(0x009d); -- Need to zone and wait midnight after "Yomi Okuri" else player:startEvent(0x009e); -- Start Quest "A Thief in Norg!?" end elseif (aThiefinNorg == QUEST_ACCEPTED) then local aThiefinNorgCS = player:getVar("aThiefinNorgCS"); if (aThiefinNorgCS < 5) then player:startEvent(0x009f); elseif (aThiefinNorgCS == 5) then player:startEvent(0x00a6); elseif (aThiefinNorgCS == 6 and player:hasItem(1166)) then -- Banishing Charm player:startEvent(0x00a7); -- Go to the battlefield elseif (aThiefinNorgCS == 6) then player:startEvent(0x00a8); -- If you delete the item elseif (aThiefinNorgCS == 7) then player:startEvent(0x00a0); elseif (aThiefinNorgCS == 8) then player:startEvent(0x00a1); elseif (aThiefinNorgCS == 9 and (player:needToZone() or tonumber(os.date("%j")) == player:getVar("Wait1DayForAThiefinNorg2_date"))) then player:startEvent(0x00a3); elseif (aThiefinNorgCS == 9) then player:startEvent(0x00a4); -- Finish Quest "A Thief in Norg!?" end elseif (aThiefinNorg == QUEST_COMPLETED) then player:startEvent(0x00a5); -- New Standard dialog else player:startEvent(0x0047); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0019 and option == 1) then player:addQuest(OUTLANDS,FORGE_YOUR_DESTINY); elseif (csid == 0x001b) then player:tradeComplete(); player:setVar("ForgeYourDestiny_timer", os.time() + 10368); --Add 3 game days elseif (csid == 0x001d) then player:tradeComplete(); player:addTitle(BUSHIDO_BLADE); player:addItem(17809); player:messageSpecial(YOU_CAN_NOW_BECOME_A_SAMURAI, 17809); -- You can now become a samurai player:unlockJob(12); -- Samurai Job Unlocked player:setVar("ForgeYourDestiny_timer",0); player:setVar("ForgeYourDestiny_Event",0); player:addFame(OUTLANDS, 30); player:completeQuest(OUTLANDS, FORGE_YOUR_DESTINY); elseif (csid == 0x008b and option == 1) then player:addQuest(OUTLANDS,THE_SACRED_KATANA); elseif (csid == 0x008d) then player:tradeComplete(); player:delKeyItem(HANDFUL_OF_CRYSTAL_SCALES); player:needToZone(true); player:setVar("Wait1DayForYomiOkuri_date", os.date("%j")); -- %M for next minute, %j for next day player:setVar("Wait1DayForYomiOkuri",VanadielDayOfTheYear()); player:addItem(17812); player:messageSpecial(ITEM_OBTAINED,17812); -- Magoroku player:addFame(OUTLANDS,AF1_FAME); player:completeQuest(OUTLANDS,THE_SACRED_KATANA); elseif (csid == 0x0092 and option == 1) then player:addQuest(OUTLANDS,YOMI_OKURI); player:setVar("Wait1DayForYomiOkuri_date",0); player:setVar("yomiOkuriCS",1); elseif (csid == 0x0098) then player:delKeyItem(YOMOTSU_FEATHER); player:setVar("yomiOkuriCS",4); player:needToZone(true); player:setVar("Wait1DayForYomiOkuri2_date", os.date("%j")); -- %M for next minute, %j for next day elseif (csid == 0x009a) then player:setVar("yomiOkuriCS",5); player:setVar("Wait1DayForYomiOkuri2_date",0); player:addKeyItem(YOMOTSU_HIRASAKA); player:messageSpecial(KEYITEM_OBTAINED,YOMOTSU_HIRASAKA); elseif (csid == 0x009c) then if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14100); else player:delKeyItem(FADED_YOMOTSU_HIRASAKA); player:addItem(14100); player:messageSpecial(ITEM_OBTAINED,14100); -- Myochin Sune-Ate player:setVar("yomiOkuriCS",0); player:needToZone(true); player:setVar("Wait1DayForAThiefinNorg_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(OUTLANDS,AF2_FAME); player:completeQuest(OUTLANDS,YOMI_OKURI); end elseif (csid == 0x009e and option == 1) then player:addQuest(OUTLANDS,A_THIEF_IN_NORG); player:setVar("Wait1DayForAThiefinNorg_date",0); player:setVar("aThiefinNorgCS",1); elseif (csid == 0x00a6 or csid == 0x00a8) then if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1166); else player:addItem(1166); player:messageSpecial(ITEM_OBTAINED,1166); -- Banishing Charm player:setVar("aThiefinNorgCS",6); end elseif (csid == 0x00a0) then player:setVar("aThiefinNorgCS",8); elseif (csid == 0x00a2) then player:tradeComplete(); player:delKeyItem(CHARRED_HELM); player:setVar("aThiefinNorgCS",9); player:needToZone(true); player:setVar("Wait1DayForAThiefinNorg2_date", os.date("%j")); -- %M for next minute, %j for next day elseif (csid == 0x00a4) then if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13868); else player:addItem(13868); player:messageSpecial(ITEM_OBTAINED,13868); -- Myochin Kabuto player:addTitle(PARAGON_OF_SAMURAI_EXCELLENCE); player:setVar("aThiefinNorgCS",0); player:setVar("Wait1DayForAThiefinNorg2_date",0); player:addFame(OUTLANDS,AF3_FAME); player:completeQuest(OUTLANDS,A_THIEF_IN_NORG); end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Valkurm_Dunes/npcs/qm1.lua
13
1226
----------------------------------- -- Area: Valkurm Dunes -- NPC: qm1 (???) -- Involved In Quest: An Empty Vessel -- @pos 238.524 2.661 -148.784 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getFreeSlotsCount() > 0 and player:hasItem(503) == false) then player:addItem(503); player:messageSpecial(ITEM_OBTAINED,503); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,503); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/North_Gustaberg/npcs/Field_Manual.lua
29
1069
----------------------------------- -- Area: North Gustaberg -- NPC: Field Manual ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startFov(FOV_EVENT_NORTH_GUSTABERG,player); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,menuchoice) updateFov(player,csid,menuchoice,16,17,18,19,59); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) finishFov(player,csid,option,16,17,18,19,59,FOV_MSG_NORTH_GUSTABERG); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Aydeewa_Subterrane/npcs/qm1.lua
30
1345
----------------------------------- -- Area: Aydeewa Subterrane -- NPC: ??? (Spawn Nosferatu(ZNM T3)) -- @pos -199 8 -62 68 ----------------------------------- package.loaded["scripts/zones/Aydeewa_Subterrane/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aydeewa_Subterrane/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 17056157; if (trade:hasItemQty(2584,1) and trade:getItemCount() == 1) then -- Trade Pure Blood if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/commands/addkeyitem.lua
3
1298
--------------------------------------------------------------------------------------------------- -- func: @addkeyitem <ID> <player> -- desc: Adds a key item to the player. --------------------------------------------------------------------------------------------------- require("scripts/globals/keyitems"); cmdprops = { permission = 1, parameters = "is" }; function onTrigger(player, keyId, target) if (keyId == nil or tonumber(keyId) == nil or tonumber(keyId) == 0 or keyId == 0) then player:PrintToPlayer( "You must enter a valid KeyItem ID." ); player:PrintToPlayer( "@addkeyitem <ID> <player>" ); return; end if (target == nil) then target = player:getName(); end local targ = GetPlayerByName(target); if (targ ~= nil) then local TextIDs = "scripts/zones/" .. targ:getZoneName() .. "/TextIDs"; package.loaded[TextIDs] = nil; require(TextIDs); targ:addKeyItem( keyId ); targ:messageSpecial( KEYITEM_OBTAINED, keyId ); player:PrintToPlayer( string.format( "Keyitem ID '%u' added to player!", keyId ) ); else player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) ); player:PrintToPlayer( "@addkeyitem <ID> <player>" ); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Dynamis-Buburimu/bcnms/dynamis_Buburimu.lua
22
1291
----------------------------------- -- Area: dynamis_Buburimu -- Name: dynamis_Buburimu ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaBuburimu]UniqueID",player:getDynamisUniqueID(1287)); SetServerVariable("[DynaBuburimu]Boss_Trigger",0); SetServerVariable("[DynaBuburimu]Already_Received",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaBuburimu]UniqueID")); local realDay = os.time(); if (DYNA_MIDNIGHT_RESET == true) then realDay = getMidnight() - 86400; end local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then SetServerVariable("[DynaBuburimu]UniqueID",0); end end;
gpl-3.0
rigeirani/bbb
plugins/info.lua
84
1882
do local function action_by_reply(extra, success, result) local user_info = {} local uhash = 'user:'..result.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.from.id..':'..result.to.id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..result.from.id..']' local msgs = '6-messages sent : '..user_info.msgs if result.from.username then user_name = '@'..result.from.username else user_name = '' end local msg = result local user_id = msg.from.id local chat_id = msg.to.id local user = 'user#id'..msg.from.id local chat = 'chat#id'..msg.to.id local data = load_data(_config.moderation.data) if data[tostring('admins')][tostring(user_id)] then who = 'Admim' elseif data[tostring(msg.to.id)]['moderators'][tostring(user_id)] then who = 'Moderator' elseif data[tostring(msg.to.id)]['set_owner'] == tostring(user_id) then who = 'Owner' elseif tonumber(result.from.id) == tonumber(our_id) then who = 'Group creator' else who = 'Member' end for v,user in pairs(_config.sudo_users) do if user == user_id then who = 'Sudo' end end local text = '1-Full name : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'2-First name : '..(result.from.first_name or '')..'\n' ..'3-Last name : '..(result.from.last_name or '')..'\n' ..'4-Username : '..user_name..'\n' ..'5-ID : '..result.from.id..'\n' ..msgs..'\n' ..'7-Position in group : '..who send_large_msg(extra.receiver, text) end local function run(msg, matches) if matches[1] == 'info' and msg.reply_id then get_message(msg.reply_id, action_by_reply, {receiver=get_receiver(msg)}) end end return { patterns = { "^([Ii]nfo)$" }, run = run } end
gpl-2.0
paritoshmmmec/kong
kong/dao/schemas/plugins_configurations.lua
13
2385
local utils = require "kong.tools.utils" local DaoError = require "kong.dao.error" local constants = require "kong.constants" local function load_value_schema(plugin_t) if plugin_t.name then local loaded, plugin_schema = utils.load_module_if_exists("kong.plugins."..plugin_t.name..".schema") if loaded then return plugin_schema else return nil, "Plugin \""..(plugin_t.name and plugin_t.name or "").."\" not found" end end end return { name = "Plugin configuration", primary_key = {"id"}, clustering_key = {"name"}, fields = { id = { type = "id", dao_insert_value = true }, created_at = { type = "timestamp", dao_insert_value = true }, api_id = { type = "id", required = true, foreign = "apis:id", queryable = true }, consumer_id = { type = "id", foreign = "consumers:id", queryable = true, default = constants.DATABASE_NULL_ID }, name = { type = "string", required = true, immutable = true, queryable = true }, value = { type = "table", schema = load_value_schema }, enabled = { type = "boolean", default = true } }, self_check = function(self, plugin_t, dao, is_update) -- Load the value schema local value_schema, err = self.fields.value.schema(plugin_t) if err then return false, DaoError(err, constants.DATABASE_ERROR_TYPES.SCHEMA) end -- Check if the schema has a `no_consumer` field if value_schema.no_consumer and plugin_t.consumer_id ~= nil and plugin_t.consumer_id ~= constants.DATABASE_NULL_ID then return false, DaoError("No consumer can be configured for that plugin", constants.DATABASE_ERROR_TYPES.SCHEMA) end if value_schema.self_check and type(value_schema.self_check) == "function" then local ok, err = value_schema.self_check(value_schema, plugin_t.value and plugin_t.value or {}, dao, is_update) if not ok then return false, err end end if not is_update then local res, err = dao.plugins_configurations:find_by_keys({ name = plugin_t.name, api_id = plugin_t.api_id, consumer_id = plugin_t.consumer_id }) if err then return nil, DaoError(err, constants.DATABASE_ERROR_TYPES.DATABASE) end if res and #res > 0 then return false, DaoError("Plugin configuration already exists", constants.DATABASE_ERROR_TYPES.UNIQUE) end end end }
mit
AdamGagorik/darkstar
scripts/zones/Kazham/npcs/Kobhi_Sarhigamya.lua
13
1039
---------------------------------- -- Area: Kazham -- NPC: Kobhi Sarhigamya -- Type: Item Deliverer -- @zone: 250 -- @pos -115.29 -11 -22.609 -- ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/bowl_of_loach_slop.lua
18
1471
----------------------------------------- -- ID: 5669 -- Item: Bowl of Loach Slop -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Make Group Effect -- Accuracy 7% Cap 15 -- HP 7% Cap 15 -- Evasion 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5669); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_ACCP, 7); target:addMod(MOD_FOOD_ACC_CAP, 15); target:addMod(MOD_FOOD_HPP, 7); target:addMod(MOD_FOOD_HP_CAP, 15); target:addMod(MOD_EVA, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_ACCP, 7); target:delMod(MOD_FOOD_ACC_CAP, 15); target:delMod(MOD_FOOD_HPP, 7); target:delMod(MOD_FOOD_HP_CAP, 15); target:delMod(MOD_EVA, 3); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Southern_San_dOria/npcs/Camereine.lua
27
2405
----------------------------------- -- Area: Southern San d'Oria -- NPC: Camereine -- Type: Chocobo Renter -- @pos -8 1 -100 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/chocobo"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); if (level >= 20) then level = 0; end player:startEvent(0x0257,price,gil,level); else player:startEvent(0x025A); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x0257 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); if (player:getMainLvl() >= 20) then local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true); else player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,900,true); end player:setPos(-126,-62,274,0x65,0x64); end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Temenos/mobs/Goblin_Warlord.lua
7
1168
----------------------------------- -- Area: Temenos N T -- NPC: Goblin_Warlord ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) GetMobByID(16928831):updateEnmity(target); GetMobByID(16928832):updateEnmity(target); GetMobByID(16928833):updateEnmity(target); GetMobByID(16928834):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) if (IsMobDead(16928831)==true and IsMobDead(16928832)==true and IsMobDead(16928833)==true and IsMobDead(16928834)==true and IsMobDead(16928835)==true ) then GetNPCByID(16928768+39):setPos(-599,85,438); GetNPCByID(16928768+39):setStatus(STATUS_NORMAL); GetNPCByID(16928768+456):setStatus(STATUS_NORMAL); end end;
gpl-3.0
mahmedhany128/Mr_BOT
plugins/addsudo.lua
2
1274
--[[ BY faeder BY @xXxDev_iqxXx CH > @Dev_faed --]] local function getindex(t,id) for i,v in pairs(t) do if v == id then return i end end return nil end function reload_plugins( ) plugins = {} load_plugins() end function h_k_a(msg, matches) if tonumber (msg.from.id) == 259142888 then if matches[1]:lower() == "اضف مطور" then table.insert(_config.sudo_users, tonumber(matches[2])) print(matches[2] ..' تم اضافه مطور جديد في البوت') save_config() reload_plugins(true) return matches[2] ..' تم اضافه مطور جديد في البوت' elseif matches[1]:lower() == "حذف مطور" then local k = tonumber(matches[2]) table.remove(_config.sudo_users, getindex( _config.sudo_users, k)) print(matches[2] ..' تم حذف المطور من البوت') save_config() reload_plugins(true) return matches[2] ..' تم حذف المطور من البوت' end end end return { patterns = { "^(اضف مطور) (%d+)$", "^(حذف مطور) (%d+)$", "^[#!/](اضف مطور) (%d+)$", "^[#!/](حذف مطور) (%d+)$" }, run = h_k_a } --[[ BY faeder BY @xXxDev_iqxXx CH > @Dev_faed --]]
gpl-2.0
khoshhalbot/khoshhal
plugins/weather.lua
12
5458
local function temps(K) local F = (K*1.8)-459.67 local C = K-273.15 return F,C end local function run(msg, matches) local res = http.request("http://api.openweathermap.org/data/2.5/weather?q="..URL.escape(matches[2]).."&appid=269ed82391822cc692c9afd59f4aabba") local jtab = JSON.decode(res) if jtab.name then if jtab.weather[1].main == "Thunderstorm" then status = "طوفاني" elseif jtab.weather[1].main == "Drizzle" then status = "نمنم باران" elseif jtab.weather[1].main == "Rain" then status = "باراني" elseif jtab.weather[1].main == "Snow" then status = "برفي" elseif jtab.weather[1].main == "Atmosphere" then status = "مه - غباز آلود" elseif jtab.weather[1].main == "Clear" then status = "صاف" elseif jtab.weather[1].main == "Clouds" then status = "ابري" elseif jtab.weather[1].main == "Extreme" then status = "-------" elseif jtab.weather[1].main == "Additional" then status = "-------" else status = "-------" end local F1,C1 = temps(jtab.main.temp) local F2,C2 = temps(jtab.main.temp_min) local F3,C3 = temps(jtab.main.temp_max) send_document(get_receiver(msg), "file/weatherIcon/"..jtab.weather[1].icon..".webp", ok_cb, false) if jtab.rain then rain = jtab.rain["3h"].." ميليمتر" else rain = "-----" end if jtab.snow then snow = jtab.snow["3h"].." ميليمتر" else snow = "-----" end today = "هم اکنون دماي هوا در "..jtab.name.."\n" .." "..C1.."° درجه سانتيگراد (سلسيوس)\n" .." "..F1.."° فارنهايت\n" .." "..jtab.main.temp.."° کلوين\n" .."بوده و هوا "..status.." ميباشد\n\n" .."حداقل دماي امروز: C"..C2.."° F"..F2.."° K"..jtab.main.temp_min.."°\n" .."حداکثر دماي امروز: C"..C3.."° F"..F3.."° K"..jtab.main.temp_max.."°\n" .."رطوبت هوا: "..jtab.main.humidity.."% درصد\n" .."مقدار ابر آسمان: "..jtab.clouds.all.."% درصد\n" .."سرعت باد: "..(jtab.wind.speed or "------").."m/s متر بر ثانيه\n" .."جهت باد: "..(jtab.wind.deg or "------").."° درجه\n" .."فشار هوا: "..(jtab.main.pressure/1000).." بار (اتمسفر)\n" .."بارندگي 3ساعت اخير: "..rain.."\n" .."بارش برف 3ساعت اخير: "..snow.."\n\n" after = "" local res = http.request("http://api.openweathermap.org/data/2.5/forecast?q="..URL.escape(matches[2]).."&appid=269ed82391822cc692c9afd59f4aabba") local jtab = JSON.decode(res) for i=1,5 do local F1,C1 = temps(jtab.list[i].main.temp_min) local F2,C2 = temps(jtab.list[i].main.temp_max) if jtab.list[i].weather[1].main == "Thunderstorm" then status = "طوفاني" elseif jtab.list[i].weather[1].main == "Drizzle" then status = "نمنم باران" elseif jtab.list[i].weather[1].main == "Rain" then status = "باراني" elseif jtab.list[i].weather[1].main == "Snow" then status = "برفي" elseif jtab.list[i].weather[1].main == "Atmosphere" then status = "مه - غباز آلود" elseif jtab.list[i].weather[1].main == "Clear" then status = "صاف" elseif jtab.list[i].weather[1].main == "Clouds" then status = "ابري" elseif jtab.list[i].weather[1].main == "Extreme" then status = "-------" elseif jtab.list[i].weather[1].main == "Additional" then status = "-------" else status = "-------" end local file = io.open("./file/weatherIcon/"..jtab.list[i].weather[1].icon..".char") if file then local file = io.open("./file/weatherIcon/"..jtab.list[i].weather[1].icon..".char", "r") icon = file:read("*all") else icon = "" end if i == 1 then day = "فردا هوا " elseif i == 2 then day = "پس فردا هوا " elseif i == 3 then day = "3روز بعد هوا " elseif i == 4 then day = "4روز بعد هوا " elseif i == 5 then day = "5روز بعد هوا " end after = after.."- "..day..status.." ميباشد. "..icon.."\n🔺C"..C2.."° - F"..F2.."°\n🔻C"..C1.."° - F"..F1.."°\n" end return today.."وضعيت آب و هوا در پنج روز آينده:\n"..after else return "مکان وارد شده صحيح نيست" end end return { description = "Weather Status", usagehtm = '<tr><td align="center">weather شهر</td><td align="right">اين پلاگين به شما اين امکان را ميدهد که به کاملترين شکل ممکن از وضعيت آب و هواي شهر مورد نظر آگاه شويد همپنين اطلاعات آب و هواي پنجج روز آينده نيز اراه ميشود. دقت کنيد نام شهر را لاتين وارد کنيد</td></tr>', usage = {"weather (city) : وضعيت آب و هوا"}, patterns = {"^([Ww]eather) (.*)$"}, run = run, } -- https://query.yahooapis.com/v1/public/yql?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20in%20%28select%20woeid%20from%20geo.places%281%29%20where%20text%3D%22"..URL.escape(matches[1]).."%22%29&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys -- celsius = string.format("%.0f", (data.temp - 32) * 5/9) -- jtab.weather[1].description clear sky", -- "مختصات جغرافيايي: "..jtab.coord.lon..","..jtab.coord.lat.."" -- jtab.list[i].weather.description scattered clouds", -- jtab.list[i].main.humidity
gpl-2.0
AdamGagorik/darkstar
scripts/globals/spells/hyoton_ichi.lua
5
1221
----------------------------------------- -- Spell: Hyoton: Ichi -- Deals ice damage to an enemy and lowers its resistance against fire. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_HYOTON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_HYOTON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower(); end local dmg = doNinjutsuNuke(28,0.5,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_FIRERES); return dmg; end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/spells/bluemagic/magic_fruit.lua
27
1743
----------------------------------------- -- Spell: Magic Fruit -- Restores HP for the target party member -- Spell cost: 72 MP -- Monster Type: Beasts -- Spell Type: Magical (Light) -- Blue Magic Points: 3 -- Stat Bonus: CHR+1 HP+5 -- Level: 58 -- Casting Time: 3.5 seconds -- Recast Time: 6 seconds -- -- Combos: Resist Sleep ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local minCure = 250; local divisor = 0.6666; local constant = 130; local power = getCurePowerOld(caster); local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true); local diff = (target:getMaxHP() - target:getHP()); if (power > 559) then divisor = 2.8333; constant = 391.2 elseif (power > 319) then divisor = 1; constant = 210; end final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then --Applying server mods.... final = final * CURE_POWER; end if (final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); spell:setMsg(7); return final; end;
gpl-3.0
D-m-L/evonara
modules/libs/Peep/LoveFrames/objects/form.lua
3
7641
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2012-2014 Kenny Shields -- --]]------------------------------------------------ -- form object local newobject = loveframes.NewObject("form", "loveframes_object_form", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize() self.type = "form" self.name = "Form" self.layout = "vertical" self.width = 200 self.height = 50 self.padding = 5 self.spacing = 5 self.topmargin = 12 self.internal = false self.children = {} end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the element --]]--------------------------------------------------------- function newobject:update(dt) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end local children = self.children local parent = self.parent local base = loveframes.base local update = self.Update -- move to parent if there is a parent if parent ~= base and parent.type ~= "list" then self.x = self.parent.x + self.staticx self.y = self.parent.y + self.staticy end self:CheckHover() for k, v in ipairs(children) do v:update(dt) end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local children = self.children local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawForm or skins[defaultskin].DrawForm local draw = self.Draw local drawcount = loveframes.drawcount -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end -- loop through the object's children and draw them for k, v in ipairs(children) do v:draw() end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local children = self.children local hover = self.hover if hover and button == "l" then local baseparent = self:GetBaseParent() if baseparent and baseparent.type == "frame" then baseparent:MakeTop() end end for k, v in ipairs(children) do v:mousepressed(x, y, button) end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local children = self.children if not visible then return end for k, v in ipairs(children) do v:mousereleased(x, y, button) end end --[[--------------------------------------------------------- - func: AddItem(object) - desc: adds an item to the object --]]--------------------------------------------------------- function newobject:AddItem(object) local objtype = object.type if objtype == "frame" then return end local children = self.children local state = self.state object:Remove() object.parent = self object:SetState(state) table.insert(children, object) self:LayoutObjects() end --[[--------------------------------------------------------- - func: RemoveItem(object or number) - desc: removes an item from the object --]]--------------------------------------------------------- function newobject:RemoveItem(data) local dtype = type(data) if dtype == "number" then local children = self.children local item = children[data] if item then item:Remove() end else data:Remove() end self:LayoutObjects() end --[[--------------------------------------------------------- - func: LayoutObjects() - desc: positions the object's children and calculates a new size for the object --]]--------------------------------------------------------- function newobject:LayoutObjects() local layout = self.layout local padding = self.padding local spacing = self.spacing local topmargin = self.topmargin local children = self.children local width = padding * 2 local height = padding * 2 + topmargin local x = padding local y = padding + topmargin if layout == "vertical" then local largest_width = 0 for k, v in ipairs(children) do v.staticx = x v.staticy = y y = y + v.height + spacing height = height + v.height + spacing if v.width > largest_width then largest_width = v.width end end height = height - spacing self.width = width + largest_width self.height = height elseif layout == "horizontal" then local largest_height = 0 for k, v in ipairs(children) do v.staticx = x v.staticy = y x = x + v.width + spacing width = width + v.width + spacing if v.height > largest_height then largest_height = v.height end end width = width - spacing self.width = width self.height = height + largest_height end end --[[--------------------------------------------------------- - func: SetLayoutType(ltype) - desc: sets the object's layout type --]]--------------------------------------------------------- function newobject:SetLayoutType(ltype) self.layout = ltype end --[[--------------------------------------------------------- - func: GetLayoutType() - desc: gets the object's layout type --]]--------------------------------------------------------- function newobject:GetLayoutType() return self.layout end --[[--------------------------------------------------------- - func: SetTopMargin(margin) - desc: sets the margin between the top of the object and its children --]]--------------------------------------------------------- function newobject:SetTopMargin(margin) self.topmargin = margin end --[[--------------------------------------------------------- - func: GetTopMargin() - desc: gets the margin between the top of the object and its children --]]--------------------------------------------------------- function newobject:GetTopMargin() return self.topmargin end --[[--------------------------------------------------------- - func: SetName(name) - desc: sets the object's name --]]--------------------------------------------------------- function newobject:SetName(name) self.name = name end --[[--------------------------------------------------------- - func: GetName() - desc: gets the object's name --]]--------------------------------------------------------- function newobject:GetName() return self.name end
mit
AdamGagorik/darkstar
scripts/zones/Windurst_Walls/npcs/Esmeralda.lua
13
1053
----------------------------------- -- Area: Windurst Walls -- NPC: Esmeralda -- Type: Consul. Rep. -- @zone: 239 -- @pos 128.629 -12.5 139.387 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x010c); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
sjznxd/lc-20130204
modules/freifunk/luasrc/controller/freifunk/freifunk.lua
13
8676
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.freifunk.freifunk", package.seeall) function index() local uci = require "luci.model.uci".cursor() local page -- Frontend page = node() page.lock = true page.target = alias("freifunk") page.subindex = true page.index = false page = node("freifunk") page.title = _("Freifunk") page.target = alias("freifunk", "index") page.order = 5 page.setuser = "nobody" page.setgroup = "nogroup" page.i18n = "freifunk" page.index = true page = node("freifunk", "index") page.target = template("freifunk/index") page.title = _("Overview") page.order = 10 page.indexignore = true page = node("freifunk", "contact") page.target = template("freifunk/contact") page.title = _("Contact") page.order = 15 page = node("freifunk", "status") page.target = template("freifunk/public_status") page.title = _("Status") page.order = 20 page.i18n = "base" page.setuser = false page.setgroup = false entry({"freifunk", "status.json"}, call("jsonstatus")) entry({"freifunk", "status", "zeroes"}, call("zeroes"), "Testdownload") entry({"freifunk", "status", "public_status_json"}, call("public_status_json")).leaf = true if nixio.fs.access("/usr/sbin/luci-splash") then assign({"freifunk", "status", "splash"}, {"splash", "publicstatus"}, _("Splash"), 40) end assign({"freifunk", "olsr"}, {"admin", "status", "olsr"}, _("OLSR"), 30) if nixio.fs.access("/etc/config/luci_statistics") then assign({"freifunk", "graph"}, {"admin", "statistics", "graph"}, _("Statistics"), 40) end -- backend assign({"mini", "freifunk"}, {"admin", "freifunk"}, _("Freifunk"), 5) entry({"admin", "freifunk"}, alias("admin", "freifunk", "index"), _("Freifunk"), 5) page = node("admin", "freifunk") page.target = template("freifunk/adminindex") page.title = _("Freifunk") page.order = 5 page = node("admin", "freifunk", "basics") page.target = cbi("freifunk/basics") page.title = _("Basic Settings") page.order = 5 page = node("admin", "freifunk", "basics", "profile") page.target = cbi("freifunk/profile") page.title = _("Profile") page.order = 10 page = node("admin", "freifunk", "basics", "profile_expert") page.target = cbi("freifunk/profile_expert") page.title = _("Profile (Expert)") page.order = 20 page = node("admin", "freifunk", "Index-Page") page.target = cbi("freifunk/user_index") page.title = _("Index Page") page.order = 50 page = node("admin", "freifunk", "contact") page.target = cbi("freifunk/contact") page.title = _("Contact") page.order = 15 entry({"freifunk", "map"}, template("freifunk-map/frame"), _("Map"), 50) entry({"freifunk", "map", "content"}, template("freifunk-map/map"), nil, 51) entry({"admin", "freifunk", "profile_error"}, template("freifunk/profile_error")) end local function fetch_olsrd() local sys = require "luci.sys" local util = require "luci.util" local table = require "table" local rawdata = sys.httpget("http://127.0.0.1:2006/") if #rawdata == 0 then if nixio.fs.access("/proc/net/ipv6_route", "r") then rawdata = sys.httpget("http://[::1]:2006/") if #rawdata == 0 then return nil end else return nil end end local data = {} local tables = util.split(util.trim(rawdata), "\r?\n\r?\n", nil, true) for i, tbl in ipairs(tables) do local lines = util.split(tbl, "\r?\n", nil, true) local name = table.remove(lines, 1):sub(8) local keys = util.split(table.remove(lines, 1), "\t") local split = #keys - 1 data[name] = {} for j, line in ipairs(lines) do local fields = util.split(line, "\t", split) data[name][j] = {} for k, key in pairs(keys) do data[name][j][key] = fields[k] end if data[name][j].Linkcost then data[name][j].LinkQuality, data[name][j].NLQ, data[name][j].ETX = data[name][j].Linkcost:match("([%w.]+)/([%w.]+)[%s]+([%w.]+)") end end end return data end function zeroes() local string = require "string" local http = require "luci.http" local zeroes = string.rep(string.char(0), 8192) local cnt = 0 local lim = 1024 * 1024 * 1024 http.prepare_content("application/x-many-zeroes") while cnt < lim do http.write(zeroes) cnt = cnt + #zeroes end end function jsonstatus() local root = {} local sys = require "luci.sys" local uci = require "luci.model.uci" local util = require "luci.util" local http = require "luci.http" local json = require "luci.json" local ltn12 = require "luci.ltn12" local version = require "luci.version" local webadmin = require "luci.tools.webadmin" local cursor = uci.cursor_state() local ffzone = webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and cursor:get("firewall", ffzone, "network") local ffwifs = ffznet and util.split(ffznet, " ") or {} root.protocol = 1 root.system = { uptime = {sys.uptime()}, loadavg = {sys.loadavg()}, sysinfo = {sys.sysinfo()}, hostname = sys.hostname() } root.firmware = { luciname=version.luciname, luciversion=version.luciversion, distname=version.distname, distversion=version.distversion } root.freifunk = {} cursor:foreach("freifunk", "public", function(s) root.freifunk[s[".name"]] = s end) cursor:foreach("system", "system", function(s) root.geo = { latitude = s.latitude, longitude = s.longitude } end) root.network = {} root.wireless = {devices = {}, interfaces = {}, status = {}} local wifs = root.wireless.interfaces local netdata = luci.sys.net.deviceinfo() or {} for _, vif in ipairs(ffwifs) do root.network[vif] = cursor:get_all("network", vif) root.wireless.devices[vif] = cursor:get_all("wireless", vif) cursor:foreach("wireless", "wifi-iface", function(s) if s.device == vif and s.network == vif then wifs[#wifs+1] = s if s.ifname then local iwinfo = luci.sys.wifi.getiwinfo(s.ifname) if iwinfo then root.wireless.status[s.ifname] = { } local _, f for _, f in ipairs({ "channel", "txpower", "bitrate", "signal", "noise", "quality", "quality_max", "mode", "ssid", "bssid", "encryption", "ifname" }) do root.wireless.status[s.ifname][f] = iwinfo[f] end end end end end) end root.olsrd = fetch_olsrd() http.prepare_content("application/json") ltn12.pump.all(json.Encoder(root):source(), http.write) end function public_status_json(devs) local twa = require "luci.tools.webadmin" local sys = require "luci.sys" local i18n = require "luci.i18n" local rv = { } local dev for dev in devs:gmatch("[%w%.%-]+") do local j = { id = dev } local iw = luci.sys.wifi.getiwinfo(dev) if iw then local f for _, f in ipairs({ "channel", "txpower", "bitrate", "signal", "noise", "quality", "quality_max", "mode", "ssid", "bssid", "encryption", "ifname" }) do j[f] = iw[f] end end rv[#rv+1] = j end local load1, load5, load15 = sys.loadavg() local _, _, memtotal, memcached, membuffers, memfree = sys.sysinfo() local mem = string.format("%.2f MB (%.2f %s, %.2f %s, %.2f %s, %.2f %s)", tonumber(memtotal) / 1024, tonumber(memtotal - memfree) / 1024, tostring(i18n.translate("used")), memfree / 1024, tostring(i18n.translate("free")), memcached / 1024, tostring(i18n.translate("cached")), membuffers / 1024, tostring(i18n.translate("buffered")) ) local dr4 = sys.net.defaultroute() local dr6 = sys.net.defaultroute6() if dr6 then def6 = { gateway = dr6.nexthop:string(), dest = dr6.dest:string(), dev = dr6.device, metr = dr6.metric } end if dr4 then def4 = { gateway = dr4.gateway:string(), dest = dr4.dest:string(), dev = dr4.device, metr = dr4.metric } else local dr = sys.exec("ip r s t olsr-default") if dr then local dest, gateway, dev, metr = dr:match("^(%w+) via (%d+.%d+.%d+.%d+) dev (%w+) +metric (%d+)") def4 = { dest = dest, gateway = gateway, dev = dev, metr = metr } end end rv[#rv+1] = { time = os.date("%a, %d %b %Y, %H:%M:%S"), uptime = twa.date_format(tonumber(sys.uptime())), load = string.format("%.2f, %.2f, %.2f", load1, load5, load15), mem = mem, defroutev4 = def4, defroutev6 = def6 } luci.http.prepare_content("application/json") luci.http.write_json(rv) return end
apache-2.0
AdamGagorik/darkstar
scripts/zones/Qulun_Dome/npcs/_440.lua
13
1586
----------------------------------- -- Area: Qulun Dome -- NPC: Door -- Involved in Mission: Magicite -- @pos 60 24 -2 148 ----------------------------------- package.loaded["scripts/zones/Qulun_Dome/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Qulun_Dome/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(SILVER_BELL) and player:hasKeyItem(CORUSCANT_ROSARY) and player:hasKeyItem(BLACK_MATINEE_NECKLACE)) then if (player:getZPos() < -7.2) then player:startEvent(0x0033); else player:startEvent(0x0032); end else player:messageSpecial(IT_SEEMS_TO_BE_LOCKED_BY_POWERFUL_MAGIC); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if ((csid == 0x0032 or csid == 0x0033) and option == 1) then player:messageSpecial(THE_3_ITEMS_GLOW_FAINTLY,SILVER_BELL,CORUSCANT_ROSARY,BLACK_MATINEE_NECKLACE); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Bastok_Markets/npcs/Fatimah.lua
53
2085
----------------------------------- -- Area: Bastok Markets -- NPC: Fatimah -- Type: Goldsmithing Adv. Synthesis Image Support -- @pos -193.849 -7.824 -56.372 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,6); local SkillLevel = player:getSkillLevel(SKILL_GOLDSMITHING); local Cost = getAdvImageSupportCost(player, SKILL_GOLDSMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == false) then player:startEvent(0x012E,Cost,SkillLevel,0,0xB0001AF,player:getGil(),0,0,0); -- Event doesn't work else player:startEvent(0x012E,Cost,SkillLevel,0,0xB0001AF,player:getGil(),28674,0,0); end else player:startEvent(0x012E); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local Cost = getAdvImageSupportCost(player, SKILL_GOLDSMITHING); if (csid == 0x012E and option == 1) then if (player:getGil() >= Cost) then player:messageSpecial(GOLDSMITHING_SUPPORT,0,3,0); player:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,3,0,480); player:delGil(Cost); else player:messageSpecial(NOT_HAVE_ENOUGH_GIL); end end end;
gpl-3.0
Hostle/luci
applications/luci-app-asterisk/luasrc/model/cbi/asterisk.lua
68
5120
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. cbimap = Map("asterisk", "asterisk", "") asterisk = cbimap:section(TypedSection, "asterisk", "Asterisk General Options", "") asterisk.anonymous = true agidir = asterisk:option(Value, "agidir", "AGI directory", "") agidir.rmempty = true cache_record_files = asterisk:option(Flag, "cache_record_files", "Cache recorded sound files during recording", "") cache_record_files.rmempty = true debug = asterisk:option(Value, "debug", "Debug Level", "") debug.rmempty = true dontwarn = asterisk:option(Flag, "dontwarn", "Disable some warnings", "") dontwarn.rmempty = true dumpcore = asterisk:option(Flag, "dumpcore", "Dump core on crash", "") dumpcore.rmempty = true highpriority = asterisk:option(Flag, "highpriority", "High Priority", "") highpriority.rmempty = true initcrypto = asterisk:option(Flag, "initcrypto", "Initialise Crypto", "") initcrypto.rmempty = true internal_timing = asterisk:option(Flag, "internal_timing", "Use Internal Timing", "") internal_timing.rmempty = true logdir = asterisk:option(Value, "logdir", "Log directory", "") logdir.rmempty = true maxcalls = asterisk:option(Value, "maxcalls", "Maximum number of calls allowed", "") maxcalls.rmempty = true maxload = asterisk:option(Value, "maxload", "Maximum load to stop accepting new calls", "") maxload.rmempty = true nocolor = asterisk:option(Flag, "nocolor", "Disable console colors", "") nocolor.rmempty = true record_cache_dir = asterisk:option(Value, "record_cache_dir", "Sound files Cache directory", "") record_cache_dir.rmempty = true record_cache_dir:depends({ ["cache_record_files"] = "true" }) rungroup = asterisk:option(Flag, "rungroup", "The Group to run as", "") rungroup.rmempty = true runuser = asterisk:option(Flag, "runuser", "The User to run as", "") runuser.rmempty = true spooldir = asterisk:option(Value, "spooldir", "Voicemail Spool directory", "") spooldir.rmempty = true systemname = asterisk:option(Value, "systemname", "Prefix UniquID with system name", "") systemname.rmempty = true transcode_via_sln = asterisk:option(Flag, "transcode_via_sln", "Build transcode paths via SLINEAR, not directly", "") transcode_via_sln.rmempty = true transmit_silence_during_record = asterisk:option(Flag, "transmit_silence_during_record", "Transmit SLINEAR silence while recording a channel", "") transmit_silence_during_record.rmempty = true verbose = asterisk:option(Value, "verbose", "Verbose Level", "") verbose.rmempty = true zone = asterisk:option(Value, "zone", "Time Zone", "") zone.rmempty = true hardwarereboot = cbimap:section(TypedSection, "hardwarereboot", "Reload Hardware Config", "") method = hardwarereboot:option(ListValue, "method", "Reboot Method", "") method:value("web", "Web URL (wget)") method:value("system", "program to run") method.rmempty = true param = hardwarereboot:option(Value, "param", "Parameter", "") param.rmempty = true iaxgeneral = cbimap:section(TypedSection, "iaxgeneral", "IAX General Options", "") iaxgeneral.anonymous = true iaxgeneral.addremove = true allow = iaxgeneral:option(MultiValue, "allow", "Allow Codecs", "") allow:value("alaw", "alaw") allow:value("gsm", "gsm") allow:value("g726", "g726") allow.rmempty = true canreinvite = iaxgeneral:option(ListValue, "canreinvite", "Reinvite/redirect media connections", "") canreinvite:value("yes", "Yes") canreinvite:value("nonat", "Yes when not behind NAT") canreinvite:value("update", "Use UPDATE rather than INVITE for path redirection") canreinvite:value("no", "No") canreinvite.rmempty = true static = iaxgeneral:option(Flag, "static", "Static", "") static.rmempty = true writeprotect = iaxgeneral:option(Flag, "writeprotect", "Write Protect", "") writeprotect.rmempty = true sipgeneral = cbimap:section(TypedSection, "sipgeneral", "Section sipgeneral", "") sipgeneral.anonymous = true sipgeneral.addremove = true allow = sipgeneral:option(MultiValue, "allow", "Allow codecs", "") allow:value("ulaw", "ulaw") allow:value("alaw", "alaw") allow:value("gsm", "gsm") allow:value("g726", "g726") allow.rmempty = true port = sipgeneral:option(Value, "port", "SIP Port", "") port.rmempty = true realm = sipgeneral:option(Value, "realm", "SIP realm", "") realm.rmempty = true moh = cbimap:section(TypedSection, "moh", "Music On Hold", "") application = moh:option(Value, "application", "Application", "") application.rmempty = true application:depends({ ["asterisk.moh.mode"] = "custom" }) directory = moh:option(Value, "directory", "Directory of Music", "") directory.rmempty = true mode = moh:option(ListValue, "mode", "Option mode", "") mode:value("system", "program to run") mode:value("files", "Read files from directory") mode:value("quietmp3", "Quite MP3") mode:value("mp3", "Loud MP3") mode:value("mp3nb", "unbuffered MP3") mode:value("quietmp3nb", "Quiet Unbuffered MP3") mode:value("custom", "Run a custom application") mode.rmempty = true random = moh:option(Flag, "random", "Random Play", "") random.rmempty = true return cbimap
apache-2.0
AdamGagorik/darkstar
scripts/globals/items/mutton_tortilla.lua
18
1726
----------------------------------------- -- ID: 4506 -- Item: mutton_tortilla -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 10 -- Strength 3 -- Vitality 1 -- Intelligence -1 -- Attack % 27 -- Attack Cap 30 -- Ranged ATT % 27 -- Ranged ATT Cap 30 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4506); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_STR, 3); target:addMod(MOD_VIT, 1); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 27); target:addMod(MOD_FOOD_ATT_CAP, 30); target:addMod(MOD_FOOD_RATTP, 27); target:addMod(MOD_FOOD_RATT_CAP, 30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_STR, 3); target:delMod(MOD_VIT, 1); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 27); target:delMod(MOD_FOOD_ATT_CAP, 30); target:delMod(MOD_FOOD_RATTP, 27); target:delMod(MOD_FOOD_RATT_CAP, 30); end;
gpl-3.0