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/globals/abilities/pets/earthen_fury.lua
34
1118
--------------------------------------------------- -- Earthen Fury --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/magic"); --------------------------------------------------- function onAbilityCheck(player, target, ability) local level = player:getMainLvl() * 2; if(player:getMP()<level) then return 87,0; end return 0,0; end; function onPetAbility(target, pet, skill, master) local dINT = math.floor(pet:getStat(MOD_INT) - target:getStat(MOD_INT)); local level = pet:getMainLvl() local damage = 48 + (level * 8); damage = damage + (dINT * 1.5); damage = MobMagicalMove(pet,target,skill,damage,ELE_EARTH,1,TP_NO_EFFECT,0); damage = mobAddBonuses(pet, nil, target, damage.dmg, ELE_EARTH); damage = AvatarFinalAdjustments(damage,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,1); master:setMP(0); target:delHP(damage); target:updateEnmityFromDamage(pet,damage); return damage; end
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Lower_Jeuno/npcs/Aldo.lua
13
1956
----------------------------------- -- Area: Lower Jeuno -- NPC: Aldo -- Involved in Mission: Magicite, Return to Delkfutt's Tower (Zilart) -- @pos 20 3 -58 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ZilartMission = player:getCurrentMission(ZILART); local ZilartStatus = player:getVar("ZilartStatus"); if (player:hasKeyItem(LETTERS_TO_ALDO)) then player:startEvent(0x0098); elseif (player:getCurrentMission(player:getNation()) == 13 and player:getVar("MissionStatus") == 3) then player:startEvent(0x00B7); elseif (ZilartMission == RETURN_TO_DELKFUTTS_TOWER and ZilartStatus == 0) then player:startEvent(0x0068); elseif (ZilartMission == THE_SEALED_SHRINE and ZilartStatus == 1) then player:startEvent(111); 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 == 0x0098) then player:delKeyItem(LETTERS_TO_ALDO); player:addKeyItem(SILVER_BELL); player:messageSpecial(KEYITEM_OBTAINED,SILVER_BELL); player:setVar("MissionStatus",3); elseif (csid == 0x0068) then player:setVar("ZilartStatus",1); end end;
gpl-3.0
rinstrum/LUA-LIB
K400Examples/protobuf/server.lua
2
3900
#!/usr/bin/env lua ------------------------------------------------------------------------------- local rinApp = require "rinApp" -- load in the application framework local sockets = require 'rinSystem.rinSockets' local dbg = require 'rinLibrary.rinDebug' require "struct" require "pb" require "messages" --============================================================================= -- Connect to the instruments you want to control --============================================================================= local device = rinApp.addK400() -- make a connection to the instrument ------------------------------------------------------------------------------- -- Callback to handle PWR+ABORT key and end application device.setKeyCallback('pwr_cancel', rinApp.finish, 'long') ------------------------------------------------------------------------------- --============================================================================= -- Create a new socket on port 2224 that allows bidirection communications -- with an extenal device --============================================================================= ------------------------------------------------------------------------------- -- We need somewhere to keep the socket descriptor so we can send messages to it local bidirectionalSocket = nil -- Write to the bidirectional socket -- @param msg The message to write local function sendMessage(msg) if bidirectionalSocket ~= nil and msg ~= nil then local s = msg:Serialize() local p = struct.pack("I2c0", #s, s) sockets.writeSocket(bidirectionalSocket, p) end end ------------------------------------------------------------------------------- -- Callback function for client connections on the bidirectional socket. -- @param sock Socket that has something ready to read. local function bidirectionalFromExternal(sock) m, err = sockets.readSocket(sock) if err ~= nil then sockets.removeSocket(sock) bidirectionalSocket = nil else local protoMessage = struct.unpack("I2c0", m) local message = protodemo.ToM4223():Parse(protoMessage) local resp, send = protodemo.FromM4223(), false if message.add_request then local addRes = protodemo.AddResult() addRes.result = message.add_request.arg1 + message.add_request.arg2 resp.add_result = addRes send = true end if message.mul_request then local mulRes = protodemo.MulResult() mulRes.result = message.mul_request.arg1 * message.mul_request.arg2 resp.mul_result = mulRes send = true end if send then sendMessage(resp) end end end ------------------------------------------------------------------------------- -- Three callback functions that are called when a new socket connection is -- established. These functions should add the socket to the sockets management -- module and set any required timouts local function socketBidirectionalAccept(sock, ip, port) if bidirectionalSocket ~= nil then dbg.info('second bidirectional connection from', ip, port) else bidirectionalSocket = sock sockets.addSocket(sock, bidirectionalFromExternal) sockets.setSocketTimeout(sock, 0.010) dbg.info('bidirectional connection from', ip, port) end end ------------------------------------------------------------------------------- -- Create the server socket sockets.createServerSocket(2224, socketBidirectionalAccept) -- Set up a timer to periodically send data --============================================================================= -- Main Application Loop --============================================================================= -- Main Application logic goes here rinApp.run() -- run the application framework
gpl-3.0
tahashakiba/xx
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
nerdclub-tfg/telegram-bot
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
mosy210/PERSION-BOT
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Xarcabard/npcs/qm1.lua
13
1423
----------------------------------- -- Area: Xarcabard -- NPC: qm1 (???) -- Involved in Quests: The Three Magi -- @pos -331 -29 -49 112 ----------------------------------- package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Xarcabard/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,THE_THREE_MAGI) == QUEST_ACCEPTED and player:hasItem(1104) == false) then if (trade:hasItemQty(613,1) and trade:getItemCount() == 1) then -- Trade Faded Crystal player:tradeComplete(); SpawnMob(17236201,180):updateClaim(player); npc:setStatus(STATUS_DISAPPEAR); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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/Meriphataud_Mountains/npcs/Akane_IM.lua
13
3343
----------------------------------- -- Area: Meriphataud Mountains -- NPC: Akane, I.M. -- Type: Outpost Conquest Guards -- @pos -294.470 15.806 420.117 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Meriphataud_Mountains/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ARAGONEU; local csid = 0x7ff9; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
mynameiscraziu/karizma
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Bastok_Mines/npcs/Gawful.lua
13
1105
----------------------------------- -- Area: Bastok Mines -- NPC: Gawful -- Type: Item Deliverer -- @zone: 234 -- @pos -22.416 -3.999 -56.076 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/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
sjznxd/lc-20130204
applications/luci-diag-devinfo/luasrc/controller/luci_diag/devinfo_common.lua
76
5638
--[[ Luci diag - Diagnostics controller module (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module("luci.controller.luci_diag.devinfo_common", package.seeall) require("luci.i18n") require("luci.util") require("luci.sys") require("luci.cbi") require("luci.model.uci") local translate = luci.i18n.translate local DummyValue = luci.cbi.DummyValue local SimpleSection = luci.cbi.SimpleSection function index() return -- no-op end function run_processes(outnets, cmdfunc) i = next(outnets, nil) while (i) do outnets[i]["output"] = luci.sys.exec(cmdfunc(outnets, i)) i = next(outnets, i) end end function parse_output(devmap, outnets, haslink, type, mini, debug) local curnet = next(outnets, nil) while (curnet) do local output = outnets[curnet]["output"] local subnet = outnets[curnet]["subnet"] local ports = outnets[curnet]["ports"] local interface = outnets[curnet]["interface"] local netdevs = {} devlines = luci.util.split(output) if not devlines then devlines = {} table.insert(devlines, output) end local j = nil j = next(devlines, j) local found_a_device = false while (j) do if devlines[j] and ( devlines[j] ~= "" ) then found_a_device = true local devtable local row = {} devtable = luci.util.split(devlines[j], ' | ') row["ip"] = devtable[1] if (not mini) then row["mac"] = devtable[2] end if ( devtable[4] == 'unknown' ) then row["vendor"] = devtable[3] else row["vendor"] = devtable[4] end row["type"] = devtable[5] if (not mini) then row["model"] = devtable[6] end if (haslink) then row["config_page"] = devtable[7] end if (debug) then row["raw"] = devlines[j] end table.insert(netdevs, row) end j = next(devlines, j) end if not found_a_device then local row = {} row["ip"] = curnet if (not mini) then row["mac"] = "" end if (type == "smap") then row["vendor"] = luci.i18n.translate("No SIP devices") else row["vendor"] = luci.i18n.translate("No devices detected") end row["type"] = luci.i18n.translate("check other networks") if (not mini) then row["model"] = "" end if (haslink) then row["config_page"] = "" end if (debug) then row["raw"] = output end table.insert(netdevs, row) end local s if (type == "smap") then if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet .. " (" .. subnet .. ":" .. ports .. interfacestring .. ")") end s.template = "diag/smapsection" else if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet .. " (" .. subnet .. interfacestring .. ")") end end s:option(DummyValue, "ip", translate("IP Address")) if (not mini) then s:option(DummyValue, "mac", translate("MAC Address")) end s:option(DummyValue, "vendor", translate("Vendor")) s:option(DummyValue, "type", translate("Device Type")) if (not mini) then s:option(DummyValue, "model", translate("Model")) end if (haslink) then s:option(DummyValue, "config_page", translate("Link to Device")) end if (debug) then s:option(DummyValue, "raw", translate("Raw")) end curnet = next(outnets, curnet) end end function get_network_device(interface) local state = luci.model.uci.cursor_state() state:load("network") local dev return state:get("network", interface, "ifname") end function cbi_add_networks(field) uci.cursor():foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then field:value(section[".name"]) end end ) field.titleref = luci.dispatcher.build_url("admin", "network", "network") end function config_devinfo_scan(map, scannet) local o o = scannet:option(luci.cbi.Flag, "enable", translate("Enable")) o.optional = false o.rmempty = false o = scannet:option(luci.cbi.Value, "interface", translate("Interface")) o.optional = false luci.controller.luci_diag.devinfo_common.cbi_add_networks(o) local scansubnet scansubnet = scannet:option(luci.cbi.Value, "subnet", translate("Subnet")) scansubnet.optional = false o = scannet:option(luci.cbi.Value, "timeout", translate("Timeout"), translate("Time to wait for responses in seconds (default 10)")) o.optional = true o = scannet:option(luci.cbi.Value, "repeat_count", translate("Repeat Count"), translate("Number of times to send requests (default 1)")) o.optional = true o = scannet:option(luci.cbi.Value, "sleepreq", translate("Sleep Between Requests"), translate("Milliseconds to sleep between requests (default 100)")) o.optional = true end
apache-2.0
AdamGagorik/darkstar
scripts/globals/items/dish_of_spaghetti_nero_di_seppia_+1.lua
18
1800
----------------------------------------- -- ID: 5202 -- Item: Dish of Spaghetti Nero Di Seppia +1 -- Food Effect: 60 Mins, All Races ----------------------------------------- -- HP % 17 (cap 140) -- Dexterity 3 -- Vitality 2 -- Agility -1 -- Mind -2 -- Charisma -1 -- Double Attack 1 -- Store TP 6 ----------------------------------------- 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,3600,5202); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 17); target:addMod(MOD_FOOD_HP_CAP, 140); target:addMod(MOD_DEX, 3); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, -1); target:addMod(MOD_MND, -2); target:addMod(MOD_CHR, -1); target:addMod(MOD_DOUBLE_ATTACK, 1); target:addMod(MOD_STORETP, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 17); target:delMod(MOD_FOOD_HP_CAP, 140); target:delMod(MOD_DEX, 3); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, -1); target:delMod(MOD_MND, -2); target:delMod(MOD_CHR, -1); target:delMod(MOD_DOUBLE_ATTACK, 1); target:delMod(MOD_STORETP, 6); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/Gravestone.lua
13
1339
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Gravestone -- Involved in Quests: fire and brimstone (Rng AF2) -- @zone 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- rng af2 local FireAndBrimstoneCS = player:getVar("fireAndBrimstone"); if (FireAndBrimstoneCS == 3) then player:startEvent(0x0005); 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 == 5) then player:setVar("fireAndBrimstone",4); end end;
gpl-3.0
saeeidbeygi/saeedbot012
plugins/banhammer.lua
214
11956
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end local bots_protection = "Yes" local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = '' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if member_id == our_id then return false end if get_cmd == 'kick' then if is_momod2(member_id, chat_id) then return send_large_msg(receiver, "you can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) then return send_large_msg(receiver, "you can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') return unbanall_user(member_id, chat_id) end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end local receiver = get_receiver(msg) if matches[1]:lower() == 'kickme' then-- /kickme if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return nil end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(tonumber(matches[2]), msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'ban' local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end return end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unban' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'kick' local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'banall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unbanall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
Laeeth/dub
test/class_test.lua
4
2876
--[[------------------------------------------------------ dub.Class --------- ... --]]------------------------------------------------------ local lub = require 'lub' local lut = require 'lut' local dub = require 'dub' local should = lut.Test 'dub.Class' local ins = dub.Inspector { doc_dir = 'test/tmp', INPUT = { 'test/fixtures/simple/include', 'test/fixtures/constants', 'test/fixtures/namespace', 'test/fixtures/inherit', }, } local Simple = ins:find('Simple') local Car = ins:find('Car') local A = ins:find('Nem::A') local Child = ins:find('Child') --=============================================== TESTS function should.autoload() assertType('table', dub.Class) end function should.createClass() local c = dub.Class() assertEqual('dub.Class', c.type) end function should.inheritNewInSubClass() local Sub = setmetatable({}, dub.Class) local c = Sub() assertEqual('dub.Class', c.type) end function should.beAClass() assertEqual('dub.Class', Simple.type) end function should.detectConscructor() local method = Simple:method('Simple') assertTrue(method.ctor) end function should.detectDestructor() local method = Simple:method('~Simple') assertTrue(method.dtor) end function should.listMethods() local m for method in Simple:methods() do if method.name == 'setValue' then m = method break end end assertEqual(m, Simple:method('setValue')) end function should.notListIgnoredMethods() local m for method in Child:methods() do if method.name == 'virtFunc' then fail("Method 'virtFunc' ignored but listed by 'methods()' iterator") end end assertTrue(true) end function should.haveHeader() local path = lub.absolutizePath(lub.path '|fixtures/simple/include/simple.h') assertEqual(path, Simple.header) end function should.detectDestructor() local method = Simple:method('~Simple') assertTrue(Simple:isDestructor(method)) end function should.respondToAttributes() local r = {} for att in Car:attributes() do lub.insertSorted(r, att.name) end assertValueEqual({ 'brand', 'name_', }, r) end function should.respondToAttributes() local r = {} for att in car:attributes() do lub.insertSorted(r, att.name) end assertValueEqual({ 'brand', 'name_', }, r) end function should.respondToConstants() local r = {} for c in Car:constants() do lub.insertSorted(r, c) end assertValueEqual({ 'Dangerous', 'Noisy', 'Polluty', 'Smoky', }, r) end function should.respondToFindChild() local f = Car:findChild 'setBrand' assertEqual('dub.Function', f.type) end function should.respondToNamespace() local n = A:namespace() assertEqual('dub.Namespace', n.type) end function should.respondToNeedCast() assertFalse(A:needCast()) assertTrue(Child:needCast()) end should:test()
mit
D-m-L/evonara
modules/libs/quickie/core.lua
15
3418
--[[ Copyright (c) 2012 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local BASE = (...):match("(.-)[^%.]+$") local group = require(BASE .. 'group') local mouse = require(BASE .. 'mouse') local keyboard = require(BASE .. 'keyboard') -- -- Helper functions -- -- evaluates all arguments local function strictAnd(...) local n = select("#", ...) local ret = true for i = 1,n do ret = select(i, ...) and ret end return ret end local function strictOr(...) local n = select("#", ...) local ret = false for i = 1,n do ret = select(i, ...) or ret end return ret end -- -- Widget ID -- local maxid, uids = 0, {} setmetatable(uids, {__index = function(t, i) t[i] = {} return t[i] end}) local function generateID() maxid = maxid + 1 return uids[maxid] end -- -- Drawing / Frame update -- local draw_items = {n = 0} local function registerDraw(id, f, ...) assert(type(f) == 'function' or (getmetatable(f) or {}).__call, 'Drawing function is not a callable type!') local font = love.graphics.getFont() local state = 'normal' if mouse.isHot(id) or keyboard.hasFocus(id) then state = mouse.isActive(id) and 'active' or 'hot' end local rest = {n = select('#', ...), ...} draw_items.n = draw_items.n + 1 draw_items[draw_items.n] = function() if font then love.graphics.setFont(font) end f(state, unpack(rest, 1, rest.n)) end end -- actually update-and-draw local function draw() keyboard.endFrame() mouse.endFrame() group.endFrame() -- save graphics state local c = {love.graphics.getColor()} local f = love.graphics.getFont() local lw = love.graphics.getLineWidth() local ls = love.graphics.getLineStyle() for i = 1,draw_items.n do draw_items[i]() end -- restore graphics state love.graphics.setLineWidth(lw) love.graphics.setLineStyle(ls) if f then love.graphics.setFont(f) end love.graphics.setColor(c) draw_items.n = 0 maxid = 0 group.beginFrame() mouse.beginFrame() keyboard.beginFrame() end -- -- The Module -- return { generateID = generateID, style = require((...):match("(.-)[^%.]+$") .. 'style-default'), registerDraw = registerDraw, draw = draw, strictAnd = strictAnd, strictOr = strictOr, }
mit
AdamGagorik/darkstar
scripts/globals/spells/bluemagic/body_slam.lua
35
1710
----------------------------------------- -- Spell: Body Slam -- Delivers an area attack. Damage varies with TP -- Spell cost: 74 MP -- Monster Type: Dragon -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: VIT+1, MP+5 -- Level: 62 -- Casting Time: 1 seconds -- Recast Time: 27.75 seconds -- Skillchain Element(s): Lightning (can open Liquefaction or Detonation; can close Impaction or Fusion) -- Combos: Max HP 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 params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_IMPACTION; params.numhits = 1; params.multiplier = 1.5; params.tp150 = 1.5; params.tp300 = 1.5; params.azuretp = 1.5; params.duppercap = 75; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.4; params.agi_wsc = 0.0; 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
rinstrum/LUA-LIB
src/rinLibrary/K400Batch.lua
1
32008
------------------------------------------------------------------------------- --- Batching scale functions. -- Functions to support the K410 Batching and products -- @module rinLibrary.Device.Batch -- @author Pauli -- @copyright 2015 Rinstrum Pty Ltd ------------------------------------------------------------------------------- local csv = require 'rinLibrary.rinCSV' local naming = require 'rinLibrary.namings' local dbg = require "rinLibrary.rinDebug" local utils = require 'rinSystem.utilities' local timers = require 'rinSystem.rinTimers' local canonical = naming.canonicalisation local deepcopy = utils.deepcopy local null, cb = utils.null, utils.cb local pcall = pcall local loadfile = loadfile local os = os local io = io local pairs = pairs local type = type -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- Submodule function begins here return function (_M, private, deprecated) local REG_REC_NAME_EX = 0xB012 -- Recipe Name (used to rename K410 active recipe) local numStages, numMaterials = 0, 0 ------------------------------------------------------------------------------- -- Query the number of materials available in the display. -- @treturn int Number of material slots in display's database -- @usage -- print('We can deal with '..device.getNativeMaterialCount()..' materials.') function _M.getNativeMaterialCount() return numMaterials end ------------------------------------------------------------------------------- -- Query the number of batching stages available in the display. -- @treturn int Number of batching stages in display's database -- @usage -- print('We can deal with '..device.getNativeStageCount()..' stages.') function _M.getNativeStageCount() return numStages end -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- Submodule register definitions hinge on the model type private.registerDeviceInitialiser(function() local batching = private.batching(true) local recipes, materials = {}, {} local materialRegs, batchRegs = {}, {} local stageRegisters, extraStageRegisters = {}, {} local stageDevice = _M local materialRegisterInfo, stageRegisterInfo = {}, {} local REG_BATCH_STAGE_NUMBER = 0xC005 local REG_BATCH_START = 0x0361 local REG_BATCH_PAUSE = 0x0362 local REG_BATCH_ABORT = 0x0363 local stageTypes = { none = 0, fill = 1, dump = 2, pulse = 3, --start = 4 } local enumMaps = { fill_start_action = { none = 0, tare = 1, gross = 2 }, fill_correction = { flight = 0, jog = 1, auto_flight = 2, auto_jog = 3 }, fill_direction = { ['in'] = 0, out = 1 }, fill_feeder = { multiple = 0, single = 1 }, dump_correction = { none = 0, jog = 1 }, dump_type = { weight = 0, time = 1 }, dump_on_tol = { both = 0, ['in'] = 1, out = 2 }, pulse_start_action = { none = 0, tare = 1, gross = 2 }, pulse_link = { none = 0, prev = 1, next = 2 }, pulse_timer = { use = 0, ignore = 1 }, } if batching then numStages = 10 numMaterials = 1 ------------------------------------------------------------------------------- -- Add a block of registers to the register file -- Update the definition table so the value is the register name -- @param regs Table of register and base step pairs. -- @param qty Number of times to step for these registers -- @local local function blockRegs(regs, qty) local r, x = {}, {} for name, v in pairs(regs) do r[name] = v[1] for i = 1, qty do x[name .. '_' .. i] = v[1] + (i-1) * v[2] end end return r, x end -- Load material register names into the register database materialRegisterInfo = { name = { 0xC081, 0x01 }, flight = { 0xC101, 0x10 }, medium = { 0xC102, 0x10 }, fast = { 0xC103, 0x10 }, total = { 0xC104, 0x10, accumulator=true },-- MORE:change these to print tokens num = { 0xC105, 0x10, accumulator=true }, error = { 0xC106, 0x10, accumulator=true }, error_pc = { 0xC107, 0x10, accumulator=true }, error_average = { 0xC108, 0x10, accumulator=true } } materialRegs = blockRegs(materialRegisterInfo, numMaterials) -- Load stage register names into the register database stageRegisterInfo = { type = { 0xC400, 0x0100, default='none' }, fill_slow = { 0xC401, 0x0100, default=0 }, fill_medium = { 0xC402, 0x0100, default=0 }, fill_fast = { 0xC403, 0x0100, default=0 }, fill_ilock = { 0xC404, 0x0100, default=0 }, fill_output = { 0xC405, 0x0100, default=0 }, fill_feeder = { 0xC406, 0x0100, default='multiple' }, fill_material = { 0xC407, 0x0100, default=0 }, fill_start_action = { 0xC408, 0x0100, default='none' }, fill_correction = { 0xC409, 0x0100, default='flight' }, fill_jog_on_time = { 0xC40A, 0x0100, default=0, ms=true }, fill_jog_off_time = { 0xC40B, 0x0100, default=0, ms=true }, fill_jog_set = { 0xC40C, 0x0100, default=0 }, fill_delay_start = { 0xC40D, 0x0100, default=0, ms=true }, fill_delay_check = { 0xC40E, 0x0100, default=0, ms=true }, fill_delay_end = { 0xC40F, 0x0100, default=0, ms=true }, fill_max_set = { 0xC412, 0x0100, default=0 }, fill_input = { 0xC413, 0x0100, default=0 }, fill_direction = { 0xC414, 0x0100, default='in' }, fill_input_wait = { 0xC415, 0x0100, default=0 }, fill_tol_lo = { 0xC420, 0x0100, default=0 }, fill_tol_high = { 0xC421, 0x0100, default=0 }, fill_target = { 0xC422, 0x0100, default=0 }, dump_dump = { 0xC440, 0x0100, default=0 }, dump_output = { 0xC441, 0x0100, default=0 }, dump_enable = { 0xC442, 0x0100, default=0 }, dump_ilock = { 0xC443, 0x0100, default=0 }, dump_type = { 0xC444, 0x0100, default='weight' }, dump_correction = { 0xC445, 0x0100, default='none' }, dump_delay_start = { 0xC446, 0x0100, default=0, ms=true }, dump_delay_check = { 0xC447, 0x0100, default=0, ms=true }, dump_delay_end = { 0xC448, 0x0100, default=0, ms=true }, dump_jog_on_time = { 0xC449, 0x0100, default=0, ms=true }, dump_jog_off_time = { 0xC44A, 0x0100, default=0, ms=true }, dump_jog_set = { 0xC44B, 0x0100, default=0 }, dump_target = { 0xC44C, 0x0100, default=0 }, dump_pulse_time = { 0xC44D, 0x0100, default=0, ms=true }, dump_on_tol = { 0xC44E, 0x0100, default='both' }, dump_off_tol = { 0xC44F, 0x0100, default=0 }, pulse_output = { 0xC460, 0x0100, default=0 }, pulse_pulse = { 0xC461, 0x0100, default=0 }, pulse_delay_start = { 0xC462, 0x0100, default=0, ms=true }, pulse_delay_end = { 0xC463, 0x0100, default=0, ms=true }, pulse_start_action = { 0xC464, 0x0100, default='none' }, pulse_link = { 0xC466, 0x0100, default='none', ignore=true }, pulse_time = { 0xC467, 0x0100, default=0, ms=true }, pulse_name = { 0xC468, 0x0100, default='' }, pulse_prompt = { 0xC469, 0x0100, default='' }, pulse_input = { 0xC46A, 0x0100, default=0 }, pulse_timer = { 0xC46B, 0x0100, default='use' } } stageRegisters, extraStageRegisters = blockRegs(stageRegisterInfo, numStages) -- if private.a418(true) then -- local analogueRegisterInfo = { -- analog_slow_fill_percent = { 0xA80E, 0x0010 }, -- analog_medium_fill_percent = { 0xA80F, 0x0010 }, -- analog_fast_fill_percent = { 0xA810, 0x0010 } -- } -- local _, analogueRegisters = blockRegs(analogueRegisterInfo, _M.getAnalogModuleMaximum()) -- private.addRegisters(analogueRegisters) -- end private.addRegisters{ batch_start_ilock = 0xC021, batch_zero_ilock = 0xC029, batch_ilock = 0xC031 } end ------------------------------------------------------------------------------- -- Applies default values to the stage specified. -- The defaults come from the material if a fill stage, from the defaults recipe -- and finally a zero value. -- @param stage Stage to change -- @return The modified stage -- @local local function applyDefaultsToStage(stage) local material = {} local type, tlen = stage.type, stage.type:len() if type == 'fill' and stage.fill_material then material = _M.getMaterial(stage.fill_material) or material end for setting, _ in pairs(stageRegisters) do if setting:sub(1, tlen) == type then stage[setting] = stage[setting] or material[setting] or recipes[setting] or stageRegisterInfo[setting].default end end return stage end -- Join table t2 into table t1. Priority will be given to t2. local function recursiveTableJoin(t1, t2) for k,v in pairs(t2) do if type(t1[k]) == 'table' and type(v) == 'table' then t1[k] = recursiveTableJoin(t1[k], v) else t1[k] = v end end return t1 end ------------------------------------------------------------------------------- -- Load the material and stage data into memory. -- This is done automatically on start up and you should only need to call this -- function when the files have been modified (e.g. via a load from USB). -- @function loadBatchingDetails -- @string recipeFile Recipe file name to load data from. This will be updated with -- the material data (and cause reordering) if a materialLog is not specified. -- @string[opt] materialLog File name to store material data in. This will be re-loaded -- into the application if specified, but priority will be given to fields in -- the recipeFile. -- @usage -- device.loadBatchingDetails() -- reload the batching databases private.exposeFunction('loadBatchingDetails', batching, function(recipeFile, materialLog) materials, recipes = {}, {} local materialsStatic = {} -- Maintain backwards compatibility by preserving previous operation -- if the materials file isn't specified. if materialLog == nil then -- Load the materials and recipes tables from file pcall(function() materials, recipes = loadfile(recipeFile)() end) os.execute("cp '" .. recipeFile .. "' '" .. recipeFile .. ".old'") --dbg.info('recipes', recipes) --dbg.info('materials', materials) _M.saveBatchingChanges = function() local savname = recipeFile .. '.new' local savf, err = io.open(savname, 'w') if err == nil then utils.saveTableToFile(savf, materials, recipes) savf:close() os.rename(savname, recipeFile) utils.sync(true) end return err end -- New function with materialsLog file. else -- Load the data materials file pcall(function() materials = loadfile(materialLog)() end) pcall(function() materialsStatic, recipes = loadfile(recipeFile)() end) -- Join the table recursiveTableJoin(materials, materialsStatic) -- Save the batching changes _M.saveBatchingChanges = function() local savf, err = io.open(materialLog, 'w') utils.saveTableToFile(savf, materials) savf:close() utils.sync(true) return nil end end end) ------------------------------------------------------------------------------- -- Save the batching information back to the bacthing state files -- @function saveBatchingChanges -- @treturn string Error string on error, nil otherwise -- @usage -- device.saveBatchingChanges() private.exposeFunction('saveBatchingChanges', batching, function() return 'No batching details loaded' end) ------------------------------------------------------------------------------- -- Function that is called after all the stages in a batch are finished -- @local local function finishedBatch() _M.saveBatchingChanges() _M.lcdControl 'lua' end -- ----------------------------------------------------------------------------- -- Save the current batching details to a Lua script file -- @function saveBatchingDetails -- @param fname Name of the file to save to -- @usage -- device.saveBatchingDetails 'myBatches.lua' -- private.exposeFunction('saveBatchingDetails', batching, function(fname) -- local f = io.open(fname, 'w') -- if f then -- f:write '-- Generated batching details file\n' -- utils.saveTableToFile(f, materials, recipes) -- f:close() -- end -- end) ------------------------------------------------------------------------------- -- Return a material record -- @function getMaterial -- @string m Material name -- @treturn tab Record for the given material or nil on error -- @treturn string Error message or nil for no error -- @usage -- local sand = device.getMaterial('sand') private.exposeFunction('getMaterial', batching, function(m) local r = materials[canonical(m)] if r == nil then return nil, 'material does not exist' end return r end) ------------------------------------------------------------------------------- -- Set the current material in the indicator -- @function setMaterialRegisters -- @string m Material name to set to -- @treturn string nil if success, error message if failure -- @usage -- device.setCurrentMaterial 'sand' -- @local local function setMaterialRegisters(m) local rec, err = _M.getMaterial(m) if err == nil then for name, reg in pairs(materialRegs) do local v = rec[name] if v == nil or v == '' then v = 0 end private.writeRegAsync(reg, v) end end end ------------------------------------------------------------------------------- -- Load the current material accumulations back from the device -- @tab s Stage to load back data for -- @local local function loadMaterialAccumulations(s) if s.type == 'fill' and s.fill_material then local rec, err = _M.getMaterial(s.fill_material) if err == nil then for name, reg in pairs(materialRegs) do if materialRegisterInfo[name].accumulator then -- Modify this to use print tokens rec[name] = _M.getRegister(reg) end end end end end ------------------------------------------------------------------------------- -- Set the current stage in the indicator -- @function setStageRegisters -- @tab S Stage record to set to -- @usage -- device.setStageRegisters { type='', fill_slow=1 } -- @local local function setStageRegisters(s) local type = s.type or 'none' local tlen = type:len() if type == 'fill' and s.fill_material then setMaterialRegisters(s.fill_material) end private.writeReg(REG_BATCH_STAGE_NUMBER, 0) private.writeReg(stageRegisters.type, naming.convertNameToValue(type, stageTypes, 0)) for name, reg in pairs(stageRegisters) do if name:sub(1, tlen) == type and not stageRegisterInfo[name].ignore then local v = s[name] if v and v ~= '' then if name == 'fill_material' then v = 0 end local map = naming.convertNameToValue(name, enumMaps) if map ~= nil then v = naming.convertNameToValue(v, map, 0) end if stageRegisterInfo[name].ms then v = math.floor(v * 1000 + 0.5) end private.writeRegAsync(reg, v) end end end stageDevice = s.device or _M end ------------------------------------------------------------------------------- -- Return a table that contains the stages in a specified recipe. -- @function getRecipe -- @string r Names of recipe -- @treturn tab Recipe table or nil on error -- @treturn string Error indicator or nil for no error -- @usage -- local cement = device.getRecipe 'cement' private.exposeFunction('getRecipe', batching, function(r) local rec = recipes[canonical(r)] if rec == nil then return nil, 'recipe does not exist' end return rec end) ------------------------------------------------------------------------------- -- Return a table that contains the stages in a user selected recipe. -- @function selectRecipe -- @string prompt User prompt -- @string[opt] default Default selection, nil for none -- @treturn tab Recipe table or nil on error -- @treturn string Error indicator or nil for no error -- @usage -- local cement = device.selectRecipe('BATCH?', 'cement') private.exposeFunction('selectRecipe', batching, function(prompt, default) local names = {} for _, v in pairs(recipes) do table.insert(names, v.recipe) end table.sort(names) local q = _M.selectOption(prompt or 'RECIPE', names, default) if q ~= nil then return _M.getRecipe(q) end return nil, 'cancelled' end) ------------------------------------------------------------------------------- -- Run a stage. Wait until it begins before returning. -- @function runStage -- @tparam tab stage Stage record to run -- @usage -- local function stageState(stage) -- device.runStage(stage) -- end -- -- local f, err = device.recipeFSM { name, start=stageStart } -- f.trans { 'start', 'begin' } -- f.trans { 'finish', 'start' } -- app.setMainLoop(f.run) private.exposeFunction('runStage', batching, function(stage) setStageRegisters(stage) _M.reinitialise 'io' _M.runBatch() end) ------------------------------------------------------------------------------- -- Terminate the current batch -- @function abortBatch -- @usage -- device.abortBatch() private.exposeFunction('abortBatch', batching, function() private.exRegAsync(REG_BATCH_ABORT, 0) end) ------------------------------------------------------------------------------- -- Pause the current batch -- @function pauseBatch -- @usage -- device.pauseBatch() private.exposeFunction('pauseBatch', batching, function() private.exRegAsync(REG_BATCH_PAUSE, 0) end) ------------------------------------------------------------------------------- -- Continue the current batch -- @function runBatch -- @usage -- device.runBatch() private.exposeFunction('runBatch', batching, function() private.exRegAsync(REG_BATCH_START, 0) end) ------------------------------------------------------------------------------- -- Return the start delay associated with the specified stage or 0 if not defined -- @param stage Stage record to query -- @treturn number stage delay -- @local local function stageDelay(stage) local start = stage[(stage.type or '')..'_delay_start'] or 0 local finish = stage[(stage.type or '')..'_delay_end'] or 0 return start + finish end ------------------------------------------------------------------------------- -- Run a batching process, controlled by a FSM. -- -- The machine has a <i>start</i> state, a <i>begin</i> state from which the batching -- will begin and progress until it reaches a <i>finish</i> state. You need to define -- the transitions from start to begin and from finish back to start or begin. You are -- also free to add you own states before or after these three. -- @function recipeFSM -- @param args Batching recipe arguments -- The arguments consist of the first positional parameter, <i>name</i> which defines -- the recipe to use. -- -- Optionally, you can specify a <i>minimumTime</i> that must elapse before a batch stage -- can be considered complete. This is a function that is passed a stage record and -- it should return the minimum number of seconds that this stage must remain active. -- This function is called before any of the batching takes place so the time returned -- is immutable. By default, there is no minimum time. -- -- Optionally, you can specify a <i>start</i> function that is passed a stage table and it -- must initiate this stage. By default, the usual batching process will be used. -- -- Optionally, you can specify a <i>finished</i> function that is also passed a stage -- table and must return true if that stage has finished. -- -- Optionally, you can specify a <i>done</i> function that is passed a stage table after -- the stage has finished. By default, this does nothing. -- -- Finally, you can optionally pass a <i>device</i> function that returns the display -- device this stage runs on. It is passed a device name from the stage CSV file. By -- default, it returns this device. -- @return Finite state machine or nil on error -- @return Error code or nil on success -- @usage -- local fsm = device.recipeFSM 'cement' -- fsm.trans { 'start', 'begin', event='begin' } -- fsm.trans { 'finish', 'start', event='restart' } -- rinApp.setMainLoop(fsm.run) private.exposeFunction('recipeFSM', batching, function(args) local rname = args[1] or args.name local recipe, err = _M.getRecipe(rname) if err then return nil, err end local deviceFinder = cb(args.device, function() return _M end) local deviceStart = deepcopy(args.start or function() return function(stage) local d = deviceFinder(stage.device) d.runStage(stage) end end) local deviceFinished = deepcopy(args.finished or function(stage) local d = deviceFinder(stage.device) return d.allStatusSet('idle') end) local deviceDone = deepcopy(args.done or function() end) local minimumTime = deepcopy(args.minimumTime or function() return 0 end) -- Extract the stages from the recipe in a useable manner if #recipe < 1 then return nil, 'no stages' end local stageCanFinish, stageTimer local function stageReset(finish) private.setStatusMainCallback('run', nil) timers.removeTimer(stageTimer) stageCanFinish = finish stageTimer = nil end local stages = {} for _, r in ipairs(recipe) do table.insert(stages, applyDefaultsToStage(deepcopy(r))) end table.sort(stages, function(a, b) return a.order < b.order end) -- Execute the stages sequentially in a FSM local pos, prev = 1, nil local blocks = { } while pos <= #stages do local e = pos+1 table.insert(blocks, { idx=pos, name='ST'..(stages[pos].order or pos)}) if stages[pos].order then while e <= #stages and stages[pos].order == stages[e].order do e = e + 1 end end pos = e end table.insert(blocks, { idx=1+#stages, name='finish' }) -- Sanity check to prevent using the same device twice for bi = 1, #blocks-1 do local b1, b2 = blocks[bi], blocks[bi+1] local used = {} for i = b1.idx, b2.idx-1 do local d = stages[i].device or _M if used[d] then return nil, 'duplicate device in stage '..stages[b1.idx].order end used[d] = true end end -- Build the FSM states local fsm = _M.stateMachine { rname, trace=true } .state { 'start' } .state { 'begin' } .state { 'finish', enter=finishedBatch } for bi = 1, #blocks-1 do local b1, b2 = blocks[bi], blocks[bi+1] local function startStage() for i = b1.idx, b2.idx-1 do deviceStart(stages[i]) end stageReset(false) private.setStatusMainCallback('run', function(s, v) if v then stageReset(true) end end) stageTimer = timers.addTimer(0, 5, stageReset, true) end local function leaveStage() stageReset(true) for i = b1.idx, b2.idx-1 do loadMaterialAccumulations(stages[i]) deviceDone(stages[i]) end end fsm.state { b1.name, enter=startStage, leave=leaveStage } end -- Add transitions to the FSM fsm.trans { 'begin', blocks[1].name, activate=function() _M.lcdControl 'default' private.exReg(REG_REC_NAME_EX, rname) end} for bi = 1, #blocks-1 do local b1, b2 = blocks[bi], blocks[bi+1] local mt = 0 for i = b1.idx, b2.idx-1 do mt = math.max(mt, minimumTime(stages[i]), stageDelay(stages[i])) end local function testStage() if not stageCanFinish then return false end for i = b1.idx, b2.idx-1 do if not deviceFinished(stages[i]) then return false end end return true end fsm.trans { b1.name, b2.name, cond=testStage, time=mt } end return fsm, nil end) --- Material definition fields -- -- These are the fields in the materials.csv material definition file. --@table MaterialFields -- @field name Material name, this is the key field to specify a material by -- @field flight weight after switching off slow fill -- @field medium point at which turn off medium (weight before target) -- @field fast point at which turn off fast (weight before target) -- @field total total weight filled -- @field num number of batches -- @field error total error from target in weight units over all batches -- @field error_pc percentage error from target -- @field error_average average error in weight units --- Batching recipe definition fields -- -- These are the fields in the recipes.csv file and they link to individual -- CSV files for each different recipe. --@table RecipeFields -- @field recipe is the name of the recipe -- @field datafile is the name of the CSV file containing the actual recipe stages. --- Stages fields -- -- These define a stage. The individual recipe CSV files should -- contain some, but by no means all, of these fields for each stage. -- The CSV file for each recipe is defined in the RecipeFields CSV -- file. -- -- A stage which does not specify a field, leaves that field at its -- default setting. -- -- You can add custom fields here and they will be preserved but not acted -- on by the batch subsystem. --@table BatchingFields -- @field name of the stage. -- @field type for the stage (mandatory). Can be <i>fill</i>, <i>dump</i> or <i>pulse</i>. -- @field device the indicator to execute this stage on (default: this indicator) -- @field order this defines the sequence the stages are executed in, smallest is -- first. This field can be a real value and fractional parts do matter. Moreover, -- multiple stages can have the same order value and they will execute simultaneously. -- However, a single indicator cannot run more than one stage at a time. -- @field fill_slow IO output for slow fill -- @field fill_medium IO output for medium fill -- @field fill_fast IO output for fast fill -- @field fill_ilock IO input low means stop, high is run -- @field fill_output IO output on during in fill stage -- @field fill_feeder enable parallel filling (multiple or single) -- @field fill_material material number -- @field fill_start_action function at start (none, tare or gross) -- @field fill_correction turn on jogging to get closer to target (flight, jog, auto\_flight or auto\_jog) -- @field fill_jog_on_time time on during jog -- @field fill_jog_off_time time output off for -- @field fill_jog_set number of times to jog before looking at weight -- @field fill_delay_start delay before start -- @field fill_delay_check delay before checking weight -- to ignore spike at start -- @field fill_delay_end after finish, pause for this long -- @field fill_max_set maximum number of jogs -- @field fill_input IO input, ends fill stage (for manual fills) -- @field fill_direction weight increase or decrease (in or out) -- @field fill_input_wait always wait for fill input high to exit -- @field fill_tol_lo range band low value for being in tolerance -- @field fill_tol_high range band high value for being in tolerance -- @field fill_target weight to aim for -- @field dump_dump IO to dump -- @field dump_output IO output, on while stage active -- @field dump_enable IO input -- okay to dump -- @field dump_ilock IO low means stop, high is run -- @field dump_type by weight or by time option (weight or time) -- @field dump_correction turn on jogging to get closer to target (none or jog) -- @field dump_delay_start delay before start -- @field dump_delay_check delay before checking weight -- ignore spike at start -- @field dump_delay_end after finish, pause for this long -- @field dump_jog_on_time time on during jog -- @field dump_jog_off_time time output off for -- @field dump_jog_set number of times to jog before looking at weight -- @field dump_target target weight at end of dump -- close enough to zero -- @field dump_pulse_time time to dump for if set to time for time -- @field dump_on_tol commnand to execute on tolerance -- @field dump_off_tol commnand to execute for out of not tolerance -- @field pulse_output IO to pulse, on while stage active -- @field pulse_pulse IO to pulse -- @field pulse_delay_start delay before start -- @field pulse_delay_end after finish, pause for this long -- @field pulse_start_action function at start (tare, switch gross, none)... -- @field pulse_link only do if other stage ran / will run, not currently implemented -- (none, prev or next). -- @field pulse_time time to pulse for -- @field pulse_name name of stage -- @field pulse_prompt what is shown on display during stage -- @field pulse_input IO input to end pulse stage -- @field pulse_timer set to <i>use</i> or <i>ignore</i>. -- @see RecipeFields -- @field product_time total time spent filling per product -- @field product_time_average average time spent filling per product -- @field product_error total error per product -- @field product_error_pc percentage error per product -- @field product_error_average average error per product end) end
gpl-3.0
juesato/rnn
scripts/evaluate-rva.lua
7
4544
require 'dp' require 'rnn' require 'optim' -- References : -- A. http://papers.nips.cc/paper/5542-recurrent-models-of-visual-attention.pdf -- B. http://incompleteideas.net/sutton/williams-92.pdf --[[command line arguments]]-- cmd = torch.CmdLine() cmd:text() cmd:text('Evaluate a Recurrent Model for Visual Attention') cmd:text('Options:') cmd:option('--xpPath', '', 'path to a previously saved model') cmd:option('--cuda', false, 'model was saved with cuda') cmd:option('--evalTest', false, 'model was saved with cuda') cmd:option('--stochastic', false, 'evaluate the model stochatically. Generate glimpses stochastically') cmd:option('--dataset', 'Mnist', 'which dataset to use : Mnist | TranslattedMnist | etc') cmd:option('--overwrite', false, 'overwrite checkpoint') cmd:text() local opt = cmd:parse(arg or {}) -- check that saved model exists assert(paths.filep(opt.xpPath), opt.xpPath..' does not exist') if opt.cuda then require 'cunn' end xp = torch.load(opt.xpPath) model = xp:model().module tester = xp:tester() or xp:validator() -- dp.Evaluator tester:sampler()._epoch_size = nil conf = tester:feedback() -- dp.Confusion cm = conf._cm -- optim.ConfusionMatrix print("Last evaluation of "..(xp:tester() and 'test' or 'valid').." set :") print(cm) if opt.dataset == 'TranslatedMnist' then ds = torch.checkpoint( paths.concat(dp.DATA_DIR, 'checkpoint/dp.TranslatedMnist_test.t7'), function() local ds = dp[opt.dataset]{load_all=false} ds:loadTest() return ds end, opt.overwrite ) else ds = dp[opt.dataset]() end ra = model:findModules('nn.RecurrentAttention')[1] sg = model:findModules('nn.SpatialGlimpse')[1] -- stochastic or deterministic for i=1,#ra.actions do local rn = ra.action:getStepModule(i):findModules('nn.ReinforceNormal')[1] rn.stochastic = opt.stochastic end if opt.evalTest then conf:reset() tester:propagateEpoch(ds:testSet()) print((opt.stochastic and "Stochastic" or "Deterministic") .. "evaluation of test set :") print(cm) end inputs = ds:get('test','inputs') targets = ds:get('test','targets', 'b') input = inputs:narrow(1,1,10) model:training() -- otherwise the rnn doesn't save intermediate time-step states if not opt.stochastic then for i=1,#ra.actions do local rn = ra.action:getStepModule(i):findModules('nn.ReinforceNormal')[1] rn.stdev = 0 -- deterministic end end output = model:forward(input) function drawBox(img, bbox, channel) channel = channel or 1 local x1, y1 = torch.round(bbox[1]), torch.round(bbox[2]) local x2, y2 = torch.round(bbox[1] + bbox[3]), torch.round(bbox[2] + bbox[4]) x1, y1 = math.max(1, x1), math.max(1, y1) x2, y2 = math.min(img:size(3), x2), math.min(img:size(2), y2) local max = img:max() for i=x1,x2 do img[channel][y1][i] = max img[channel][y2][i] = max end for i=y1,y2 do img[channel][i][x1] = max img[channel][i][x2] = max end return img end locations = ra.actions input = nn.Convert(ds:ioShapes(),'bchw'):forward(input) glimpses = {} patches = {} params = nil for i=1,input:size(1) do local img = input[i] for j,location in ipairs(locations) do local glimpse = glimpses[j] or {} glimpses[j] = glimpse local patch = patches[j] or {} patches[j] = patch local xy = location[i] -- (-1,-1) top left corner, (1,1) bottom right corner of image local x, y = xy:select(1,1), xy:select(1,2) -- (0,0), (1,1) x, y = (x+1)/2, (y+1)/2 -- (1,1), (input:size(3), input:size(4)) x, y = x*(input:size(3)-1)+1, y*(input:size(4)-1)+1 local gimg = img:clone() for d=1,sg.depth do local size = sg.height*(sg.scale^(d-1)) local bbox = {y-size/2, x-size/2, size, size} drawBox(gimg, bbox, 1) end glimpse[i] = gimg local sg_, ps if j == 1 then sg_ = ra.rnn.initialModule:findModules('nn.SpatialGlimpse')[1] else sg_ = ra.rnn.sharedClones[j]:findModules('nn.SpatialGlimpse')[1] end patch[i] = image.scale(img:clone():float(), sg_.output[i]:narrow(1,1,1):float()) collectgarbage() end end paths.mkdir('glimpse') for j,glimpse in ipairs(glimpses) do local g = image.toDisplayTensor{input=glimpse,nrow=10,padding=3} local p = image.toDisplayTensor{input=patches[j],nrow=10,padding=3} image.save("glimpse/glimpse"..j..".png", g) image.save("glimpse/patch"..j..".png", p) end
bsd-3-clause
mahmedhany128/Mr_BOT
Feader/Feader.lua
1
7745
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./Feader/utils") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end msg = backward_msg_format(msg) local receiver = get_receiver(msg) print(receiver) --vardump(msg) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < os.time() - 5 then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then --send_large_msg(*group id*, msg.text) *login code will be sent to GroupID* return false end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Sudo user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "anti_spam", "helo", "addsudo", "all", "admin", "badword", "banhammer", "broadcast", "dev", "get", "getfile", "getlink", "image", "info", "inpm", "inrealm", "insta", "invite", "isup", "leave_ban", "lock-bot", "lock_fwd", "map", "msg_checks", "newgroup", "onservice", "owners", "plugins", "robot", "set", "sof", "sof2", "supergroup", "kickme", "LEADER1", "LEADER", "LEADER2", "LEADER3", "LEADER4", "LEADER5", "LEADER6", "njinji", "ar_me", "addbot", "save", "nedme", "echo", "ar-boomzain", "red", "redis", "@xXxDev_iqxXx", "tagall", "del", "reply", "ax" }, sudo_users = {259142888},--Sudo users moderation = {data = 'data/moderation.json'}, about_text = [[]], help_text_realm = [[ ]], help_text_super =[[ ]], } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
AdamGagorik/darkstar
scripts/globals/items/plate_of_tuna_sushi.lua
17
1537
----------------------------------------- -- ID: 5150 -- Item: plate_of_tuna_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Dexterity 3 -- Charisma 5 -- Accuracy % 15 -- Ranged ACC % 15 -- Sleep Resist 5 ----------------------------------------- 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,5150); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_CHR, 5); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_CHR, 5); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Dynamis-Tavnazia/Zone.lua
13
2401
----------------------------------- -- -- Zone: Dynamis-Tavnazia -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Dynamis-Tavnazia/TextIDs"] = nil; require("scripts/zones/Dynamis-Tavnazia/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) 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; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaTavnazia]UniqueID")) then if (player:isBcnmsFull() == 1) then if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then inst = player:addPlayerToDynamis(1289); if (inst == 1) then player:bcnmEnter(1289); else cs = 0x0065; end else player:bcnmEnter(1289); end else inst = player:bcnmRegister(1289); if (inst == 1) then player:bcnmEnter(1289); else cs = 0x0065; end end else cs = 0x0065; 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); if (csid == 0x0065) then player:setPos(0.0,-7,-23,195,26); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/weaponskills/tornado_kick.lua
9
2181
------------------------------- -- Auth : Thief -- Skill: Tornado Kick -- Class: H2H Weapon Skill -- Level: 225 -- Mods : STR:37.5% VIT:30% -- 100%TP 200%TP 300%TP -- 2.0x 2.75x 3.5x -- Delivers a twofold attack. Damage varies with TP. ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; -- number of normal hits for ws params.numHits = 2; -- stat-modifiers (0.0 = 0%, 0.2 = 20%, 0.5 = 50%..etc) params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; -- ftp damage mods (for Damage Varies with TP; lines are calculated in the function ftp) params.ftp100 = 2.0; params.ftp200 = 2.75; params.ftp300 = 3.5; -- critical modifiers (0.0 = 0%, 0.2 = 20%, 0.5 = 50%..etc) params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0; params.canCrit = false; -- params.accuracy modifiers (0.0 = 0%, 0.2 = 20%, 0.5 = 50%..etc) Keep 0 if ws doesn't have accuracy modification. params.acc100 = 0.0; params.acc200=0.0; params.acc300=0.0; -- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default. params.atkmulti = 1; -- Tornado kick is not considered a kick attack and is not modified by Footwork http://www.bluegartr.com/threads/121610-Rehauled-Weapon-Skills-tier-lists?p=6140907&viewfull=1#post6140907 if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 2.25; params.ftp200 = 4.25; params.ftp300 = 7.5; params.str_wsc = 0.4; params.dex_wsc = 0.4; 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.atkmulti = 1.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
chfg007/skynet
service/launcher.lua
51
3199
local skynet = require "skynet" local core = require "skynet.core" require "skynet.manager" -- import manager apis local string = string local services = {} local command = {} local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK) local function handle_to_address(handle) return tonumber("0x" .. string.sub(handle , 2)) end local NORET = {} function command.LIST() local list = {} for k,v in pairs(services) do list[skynet.address(k)] = v end return list end function command.STAT() local list = {} for k,v in pairs(services) do local stat = skynet.call(k,"debug","STAT") list[skynet.address(k)] = stat end return list end function command.KILL(_, handle) handle = handle_to_address(handle) skynet.kill(handle) local ret = { [skynet.address(handle)] = tostring(services[handle]) } services[handle] = nil return ret end function command.MEM() local list = {} for k,v in pairs(services) do local kb, bytes = skynet.call(k,"debug","MEM") list[skynet.address(k)] = string.format("%.2f Kb (%s)",kb,v) end return list end function command.GC() for k,v in pairs(services) do skynet.send(k,"debug","GC") end return command.MEM() end function command.REMOVE(_, handle, kill) services[handle] = nil local response = instance[handle] if response then -- instance is dead response(not kill) -- return nil to caller of newservice, when kill == false instance[handle] = nil end -- don't return (skynet.ret) because the handle may exit return NORET end local function launch_service(service, ...) local param = table.concat({...}, " ") local inst = skynet.launch(service, param) local response = skynet.response() if inst then services[inst] = service .. " " .. param instance[inst] = response else response(false) return end return inst end function command.LAUNCH(_, service, ...) launch_service(service, ...) return NORET end function command.LOGLAUNCH(_, service, ...) local inst = launch_service(service, ...) if inst then core.command("LOGON", skynet.address(inst)) end return NORET end function command.ERROR(address) -- see serivce-src/service_lua.c -- init failed local response = instance[address] if response then response(false) instance[address] = nil end services[address] = nil return NORET end function command.LAUNCHOK(address) -- init notice local response = instance[address] if response then response(true, address) instance[address] = nil end return NORET end -- for historical reasons, launcher support text command (for C service) skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, unpack = skynet.tostring, dispatch = function(session, address , cmd) if cmd == "" then command.LAUNCHOK(address) elseif cmd == "ERROR" then command.ERROR(address) else error ("Invalid text command " .. cmd) end end, } skynet.dispatch("lua", function(session, address, cmd , ...) cmd = string.upper(cmd) local f = command[cmd] if f then local ret = f(address, ...) if ret ~= NORET then skynet.ret(skynet.pack(ret)) end else skynet.ret(skynet.pack {"Unknown command"} ) end end) skynet.start(function() end)
mit
AdamGagorik/darkstar
scripts/zones/Metalworks/npcs/Baldric.lua
13
1772
----------------------------------- -- Area: Metalworks -- NPC: Baldric -- Type: Quest Giver -- @zone: 237 -- @pos -50.858 1.777 -31.141 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings") require("scripts/globals/quests"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,STARDUST) ~= QUEST_AVAILABLE) then if (trade:hasItemQty(503,1) and trade:getItemCount() == 1) then player:startEvent(0x022B); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,STARDUST) == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 2) then player:startEvent(0x022A); else player:startEvent(0x0228); 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 == 0x022A) then player:addQuest(BASTOK,STARDUST); elseif (csid == 0x022B) then player:tradeComplete(); player:addGil(300); player:messageSpecial(GIL_OBTAINED,GIL_RATE*300); player:completeQuest(BASTOK,STARDUST); end end;
gpl-3.0
pczarn/kollos
components/main/kollos/config.lua
2
2367
--[[ 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. [ MIT license: http://www.opensource.org/licenses/mit-license.php ] --]] -- Kollos top-level config objects -- luacheck: std lua51 -- luacheck: globals bit local function here() return -- luacheck: ignore here debug.getinfo(2,'S').source .. debug.getinfo(2, 'l').currentline end local inspect = require "kollos.inspect" -- luacheck: ignore local grammar = require "kollos.grammar" local development = require "kollos.development" local config_class = { grammar_new = grammar.new } local function config_new(args) local config_object = { _type = "config" } -- 'alpha' means anything is OK -- it is the only acceptable if, at this point if type(args) ~= 'table' then development.error([[argument of config_new() must be a table of named arguments]], true) end local throw = args.throw or true -- config_object.throw = throw if type(args.interface) ~= 'string' then return nil, development.error([["interface" named argument is required and must be string]], throw) end if args.interface ~= 'alpha' then return nil, development.error([["interface = 'alpha'" is required]], throw) end setmetatable(config_object, { __index = config_class, }) return config_object end return { new = config_new } -- vim: expandtab shiftwidth=4:
mit
AdamGagorik/darkstar
scripts/zones/Al_Zahbi/npcs/Chayaya.lua
13
1644
----------------------------------- -- Area: Al Zahbi -- NPC: Chayaya -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CHAYAYA_SHOP_DIALOG); stock = {0x439B,10, --Dart 0x439C,60, --Hawkeye 0x43A1,1204, --Grenade 0x43A8,8, --Iron Arrow 0x1565,68000, --Warrior Die 0x1566,22400, --Monk Die 0x1567,5000, --White Mage Die 0x1568,108000, --Black Mage Die 0x1569,62000, --Red Mage Die 0x156A,50400, --Thief Die 0x156B,90750, --Paladin Die 0x156C,2205, --Dark Knight Die 0x156D,26600, --Beastmaster Die 0x156E,12780, --Bard Die 0x156F,1300, --Ranger Die 0x1577,63375, --Dancer Die 0x1578,68250} --Scholar Die 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/globals/items/red_terrapin.lua
18
1319
----------------------------------------- -- ID: 4402 -- Item: red_terrapin -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 3 -- Mind -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local 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,4402); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -5); end;
gpl-3.0
talldan/lua-reactor
tests/specs/reactor/propTypes/optional.lua
1
2104
local optional = require('reactor.propTypes.optional') local function stringValidator() return function(toValidate) local isValid = type(toValidate) == 'string' local reason = nil if not isValid then reason = 'not a string' end return isValid, reason end end describe('optional', function() describe('error states', function() it('causes an error if the argument to optional is not a function', function() expect(function() optional() end).to.fail() expect(function() optional('test') end).to.fail() expect(function() optional(12) end).to.fail() expect(function() optional(true) end).to.fail() expect(function() optional({}) end).to.fail() end) end) describe('behaviour', function() it('returns a function to use for validation when passed a function to wrap', function() expect(type(optional(stringValidator()))) .to.be('function') end) it('allows nil as an accepted value when wrapping another validator', function() local validateString = stringValidator() local optionalValidateString = optional(stringValidator()) expect(validateString('test')) .to.be(true) expect(validateString(nil)) .to.be(false) expect(validateString(12)) .to.be(false) expect(optionalValidateString('test')) .to.be(true) expect(optionalValidateString(nil)) .to.be(true) expect(optionalValidateString(12)) .to.be(false) end) it('does not return a second return value when validation is successful', function() local validator = optional(stringValidator()) local isValid, reason = validator() expect(reason) .to.be(nil) end) it('returns a second return value of type string that represents the reason validation failed', function() local validator = optional(stringValidator()) local isValid, reason = validator(12) expect(type(reason)) .to.be('string') end) end) end)
mit
mosy210/PERSION-BOT
plugins/media.lua
376
1679
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
Android092921/season
plugins/ingroup.lua
371
44212
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] local user_info = redis:hgetall('user:'..group_owner) if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") if user_info.username then return "Group onwer is @"..user_info.username.." ["..group_owner.."]" else return "Group owner is ["..group_owner..']' end end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Palborough_Mines/npcs/Treasure_Chest.lua
13
3052
----------------------------------- -- Area: Palborough Mines -- NPC: Treasure Chest -- @zone 143 ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Palborough_Mines/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --trade:hasItemQty(1025,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(1025,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); 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); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(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]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1025); 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
JR10/mta-business
scripts/core.client.lua
1
7890
local screen_width, screen_height = GuiElement.getScreenSize(); local is_cursor_over_gui = false; local action; local settings = {}; GuiElement.setInputMode("no_binds_when_editing"); addEvent("business.showCreateBusinessWindow", true); addEventHandler("business.showCreateBusinessWindow", root, function() gui.cb.window.visible = true; showCursor(true); end ); function outputMessage(message, r, g, b) triggerServerEvent("business.outputMessage", localPlayer, message, r, g, b); end addEventHandler("onClientRender", root, function() for index, b_marker in ipairs(Element.getAllByType("marker", resourceRoot)) do local b_data = b_marker:getData("b_data"); local id, name, owner, cost, payout, payout_time, payout_otime, payout_unit, bank, timer = unpack(b_data); local x, y, z = b_marker.position.x, b_marker.position.y, b_marker.position.z; local cam_x, cam_y, cam_z = getCameraMatrix(); if getDistanceBetweenPoints3D(cam_x, cam_y, cam_z, x, y, z) < 15 then local screen_x, screen_y = getScreenFromWorldPosition(x, y, z + 1.6); if screen_x then local scale = 1920 / screen_width; local width = 80 / scale; dxDrawImage(screen_x - width / 2, screen_y - screen_height / 10, width, 80, "files/business.png"); end if settings.show_business_info_on_marker then screen_x, screen_y = getScreenFromWorldPosition(x, y, z + 1.4); if screen_x then if #tostring(id) == 1 then id = "0"..tostring(id) end dxDrawFramedText("ID: #"..id, screen_x, screen_y, screen_x, screen_y, tocolor(255, 255, 255, 255), 1.0, "default-bold", "center", "center", false, false, false); end screen_x, screen_y = getScreenFromWorldPosition(x, y, z + 1.2); if screen_x then dxDrawFramedText("Name: "..name, screen_x, screen_y, screen_x, screen_y, tocolor(255, 255, 255, 255), 1.0, "default-bold", "center", "center", false, false, false); end screen_x, screen_y = getScreenFromWorldPosition(x, y, z + 1.0); if screen_x then dxDrawFramedText("Owner: "..owner, screen_x, screen_y, screen_x, screen_y, tocolor(255, 255, 255, 255), 1.0, "default-bold", "center", "center", false, false, false); end screen_x, screen_y = getScreenFromWorldPosition(x, y, z + 0.8); if screen_x then dxDrawFramedText("Cost: $"..cost, screen_x, screen_y, screen_x, screen_y, tocolor(255, 255, 255, 255), 1.0, "default-bold", "center", "center", false, false, false); end screen_x, screen_y = getScreenFromWorldPosition(x, y, z + 0.6); if screen_x then dxDrawFramedText("Payout: $"..payout, screen_x, screen_y, screen_x, screen_y, tocolor(255, 255, 255, 255), 1.0, "default-bold", "center", "center", false, false, false); end screen_x, screen_y = getScreenFromWorldPosition(x, y, z + 0.4); if screen_x then dxDrawFramedText("Payout Time: "..payout_otime.." "..payout_unit, screen_x, screen_y, screen_x, screen_y, tocolor(255, 255, 255, 255), 1.0, "default-bold", "center", "center", false, false, false); end screen_x, screen_y = getScreenFromWorldPosition(x, y, z + 0.2); if screen_x then dxDrawFramedText("Bank: $"..bank, screen_x, screen_y, screen_x, screen_y, tocolor(255, 255, 255, 255), 1.0, "default-bold", "center", "center", false, false, false); end end end end end ); addEvent("business.showInstructions", true); addEventHandler("business.showInstructions", root, function() addEventHandler("onClientRender", root, showInstructions); end ); function showInstructions() if settings.key then dxDrawText("Press",(screen_width / 1440) * 550,(screen_height / 900) * 450,(screen_width / 1440) * 100,(screen_height / 900) * 100, tocolor(255, 255, 255, 255),(screen_width / 1440) * 2.0); dxDrawText(settings.key:upper(),(screen_width / 1440) * 615,(screen_height / 900) * 450,(screen_width / 1440) * 100,(screen_height / 900) * 100, tocolor(255, 0, 0, 255),(screen_width / 1440) * 2.0); dxDrawText(" To Open The Business",(screen_width / 1440) * 630,(screen_height / 900) * 450,(screen_width / 1440) * 100,(screen_height / 900) * 100, tocolor(255, 255, 255, 255),(screen_width / 1440) * 2.0); end end addEvent("business.hideInstructions", true); addEventHandler("business.hideInstructions", root, function() removeEventHandler("onClientRender", root, showInstructions); end ); addEvent("business.showBusinessWindow", true); addEventHandler("business.showBusinessWindow", root, function(b_marker, is_owner, is_admin) local b_data = b_marker:getData("b_data"); local id, name, owner, cost, payout, payout_time, payout_otime, payout_unit, bank, timer = unpack(b_data); local x, y, z = b_marker.position; if #tostring(id) == 1 then id = "0"..tostring(id) end gui.b.window.text = name; gui.b.label.id.text = "ID: #"..id; gui.b.label.name.text = "Name: "..name; gui.b.label.owner.text = "Owner: "..owner; gui.b.label.cost.text = "Cost: $"..cost; gui.b.label.payout.text = "Payout: $"..payout; gui.b.label.payout_time.text = "Payout Time: "..payout_otime.." "..payout_unit; gui.b.label.location.text = "Location: "..getZoneName(x, y, z, false).."("..getZoneName(x, y, z, true)..")"; gui.b.label.bank.text = "Bank: $"..bank; if is_admin and is_owner then gui.b.tab.action.enabled = true; gui.b.button.sell.enabled = true; gui.b.button.deposit.enabled = true; gui.b.button.withdraw.enabled = true; gui.b.button.set_name.enabled = true; gui.b.button.set_owner.enabled = true; gui.b.button.set_cost.enabled = true; gui.b.button.set_bank.enabled = true; gui.b.button.buy.enabled = false; elseif is_admin and not is_owner and owner ~= "For Sale" then gui.b.tab.action.enabled = true; gui.b.button.set_name.enabled = true; gui.b.button.set_owner.enabled = true; gui.b.button.set_cost.enabled = true; gui.b.button.set_bank.enabled = true; gui.b.button.sell.enabled = true; gui.b.button.buy.enabled = false; gui.b.button.deposit.enabled = false; gui.b.button.withdraw.enabled = false; elseif is_admin and not is_owner and owner == "For Sale" then gui.b.tab.action.enabled = true; gui.b.button.set_name.enabled = true; gui.b.button.set_owner.enabled = true; gui.b.button.set_cost.enabled = true; gui.b.button.set_bank.enabled = true; gui.b.button.sell.enabled = false; gui.b.button.buy.enabled = true; gui.b.button.deposit.enabled = false; gui.b.button.withdraw.enabled = false; elseif not is_admin and is_owner then gui.b.tab.action.enabled = true; gui.b.button.set_name.enabled = false; gui.b.button.set_owner.enabled = false; gui.b.button.set_cost.enabled = false; gui.b.button.set_bank.enabled = false; gui.b.button.sell.enabled = true; gui.b.button.deposit.enabled = true; gui.b.button.withdraw.enabled = true; gui.b.button.buy.enabled = false; elseif not is_admin and not is_owner and owner ~= "For Sale" then gui.b.tab.action.enabled = false; gui.b.tab_panel:setSelectedTab(gui.b.tab.info); elseif not is_admin and not is_owner and owner == "For Sale" then gui.b.tab.action.enabled = true; gui.b.button.set_name.enabled = false; gui.b.button.set_owner.enabled = false; gui.b.button.set_cost.enabled = false; gui.b.button.set_bank.enabled = false; gui.b.button.accept.enabled = false; gui.b.button.sell.enabled = false; gui.b.button.deposit.enabled = false; gui.b.button.withdraw.enabled = false; gui.b.button.buy.enabled = true; end gui.b.window.visible = true; showCursor(true); removeEventHandler("onClientRender", root, showInstructions) end ); addEventHandler("onClientResourceStart", resourceRoot, function() triggerServerEvent("business.getSettings", localPlayer); end ); addEvent("business.getSettings", true); addEventHandler("business.getSettings", root, function(_settings) settings = _settings; end );
mit
AdamGagorik/darkstar
scripts/globals/spells/valor_minuet_ii.lua
27
1565
----------------------------------------- -- Spell: Valor Minuet II -- Grants Attack bonus to all allies. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 10; if (sLvl+iLvl > 85) then power = power + math.floor((sLvl+iLvl-85) / 6); end if (power >= 32) then power = 32; end local iBoost = caster:getMod(MOD_MINUET_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end power = power + caster:getMerit(MERIT_MINUET_EFFECT); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MINUET,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(75); end return EFFECT_MINUET; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Chamber_of_Oracles/bcnms/shattering_stars.lua
27
2049
----------------------------------- -- Area: Qu'Bia Arena -- Name: Shattering stars - Maat Fight -- @pos -221 -24 19 206 ----------------------------------- package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Sacrificial_Chamber/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) -- player:messageSpecial(107); end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if (player:getQuestStatus(JEUNO,SHATTERING_STARS) == QUEST_ACCEPTED and player:getFreeSlotsCount() > 0) then player:addItem(4181); player:messageSpecial(ITEM_OBTAINED,4181); end local pjob = player:getMainJob(); player:setVar("maatDefeated",pjob); local maatsCap = player:getVar("maatsCap") if (bit.band(maatsCap, bit.lshift(1, (pjob -1))) ~= 1) then player:setVar("maatsCap",bit.bor(maatsCap, bit.lshift(1, (pjob -1)))) end player:addTitle(MAAT_MASHER); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Spire_of_Dem/npcs/_0j1.lua
39
1330
----------------------------------- -- Area: Spire_of_Dem -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Dem/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
robertfoss/nodemcu-firmware
lua_modules/yeelink/yeelink_lib.lua
73
3136
-- *************************************************************************** -- Yeelink Updata Libiary Version 0.1.2 r1 -- -- Written by Martin -- but based on a script of zhouxu_o from bbs.nodemcu.com -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** --==========================Module Part====================== local moduleName = ... local M = {} _G[moduleName] = M --=========================Local Args======================= local dns = "0.0.0.0" local device = "" local sensor = "" local apikey = "" --================================ local debug = true --<<<<<<<<<<<<< Don't forget to "false" it before using --================================ local sk=net.createConnection(net.TCP, 0) local datapoint = 0 --====DNS the yeelink ip advance(in order to save RAM)===== if wifi.sta.getip() == nil then print("Please Connect WIFI First") tmr.alarm(1,1000,1,function () if wifi.sta.getip() ~= nil then tmr.stop(1) sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) end end) end sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) --========Set the init function=========== --device->number --sensor->number -- apikey must be -> string <- -- e.g. xxx.init(00000,00000,"123j12b3jkb12k4b23bv54i2b5b3o4") --======================================== function M.init(_device, _sensor, _apikey) device = tostring(_device) sensor = tostring(_sensor) apikey = _apikey if dns == "0.0.0.0" then tmr.alarm(2,5000,1,function () if dns == "0.0.0.0" then print("Waiting for DNS...") end end) return false else return dns end end --========Check the DNS Status=========== --if DNS success, return the address(string) --if DNS fail(or processing), return nil -- -- --======================================== function M.getDNS() if dns == "0.0.0.0" then return nil else return dns end end --=====Update to Yeelink Sever(At least 10s per sencods))===== -- datapoint->number -- --e.g. xxx.update(233.333) --============================================================ function M.update(_datapoint) datapoint = tostring(_datapoint) sk:on("connection", function(conn) print("connect OK...") local a=[[{"value":]] local b=[[}]] local st=a..datapoint..b sk:send("POST /v1.0/device/"..device.."/sensor/"..sensor.."/datapoints HTTP/1.1\r\n" .."Host: www.yeelink.net\r\n" .."Content-Length: "..string.len(st).."\r\n"--the length of json is important .."Content-Type: application/x-www-form-urlencoded\r\n" .."U-ApiKey:"..apikey.."\r\n" .."Cache-Control: no-cache\r\n\r\n" ..st.."\r\n" ) end) sk:on("receive", function(sck, content) if debug then print("\r\n"..content.."\r\n") else print("Date Receive") end end) sk:connect(80,dns) end --================end========================== return M
mit
iotcafe/nodemcu-firmware
lua_modules/yeelink/yeelink_lib.lua
73
3136
-- *************************************************************************** -- Yeelink Updata Libiary Version 0.1.2 r1 -- -- Written by Martin -- but based on a script of zhouxu_o from bbs.nodemcu.com -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** --==========================Module Part====================== local moduleName = ... local M = {} _G[moduleName] = M --=========================Local Args======================= local dns = "0.0.0.0" local device = "" local sensor = "" local apikey = "" --================================ local debug = true --<<<<<<<<<<<<< Don't forget to "false" it before using --================================ local sk=net.createConnection(net.TCP, 0) local datapoint = 0 --====DNS the yeelink ip advance(in order to save RAM)===== if wifi.sta.getip() == nil then print("Please Connect WIFI First") tmr.alarm(1,1000,1,function () if wifi.sta.getip() ~= nil then tmr.stop(1) sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) end end) end sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) --========Set the init function=========== --device->number --sensor->number -- apikey must be -> string <- -- e.g. xxx.init(00000,00000,"123j12b3jkb12k4b23bv54i2b5b3o4") --======================================== function M.init(_device, _sensor, _apikey) device = tostring(_device) sensor = tostring(_sensor) apikey = _apikey if dns == "0.0.0.0" then tmr.alarm(2,5000,1,function () if dns == "0.0.0.0" then print("Waiting for DNS...") end end) return false else return dns end end --========Check the DNS Status=========== --if DNS success, return the address(string) --if DNS fail(or processing), return nil -- -- --======================================== function M.getDNS() if dns == "0.0.0.0" then return nil else return dns end end --=====Update to Yeelink Sever(At least 10s per sencods))===== -- datapoint->number -- --e.g. xxx.update(233.333) --============================================================ function M.update(_datapoint) datapoint = tostring(_datapoint) sk:on("connection", function(conn) print("connect OK...") local a=[[{"value":]] local b=[[}]] local st=a..datapoint..b sk:send("POST /v1.0/device/"..device.."/sensor/"..sensor.."/datapoints HTTP/1.1\r\n" .."Host: www.yeelink.net\r\n" .."Content-Length: "..string.len(st).."\r\n"--the length of json is important .."Content-Type: application/x-www-form-urlencoded\r\n" .."U-ApiKey:"..apikey.."\r\n" .."Cache-Control: no-cache\r\n\r\n" ..st.."\r\n" ) end) sk:on("receive", function(sck, content) if debug then print("\r\n"..content.."\r\n") else print("Date Receive") end end) sk:connect(80,dns) end --================end========================== return M
mit
Hostle/luci
applications/luci-app-pbx/luasrc/model/cbi/pbx.lua
146
4360
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- modulename = "pbx" if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end -- Returns formatted output of string containing only the words at the indices -- specified in the table "indices". function format_indices(string, indices) if indices == nil then return "Error: No indices to format specified.\n" end -- Split input into separate lines. lines = luci.util.split(luci.util.trim(string), "\n") -- Split lines into separate words. splitlines = {} for lpos,line in ipairs(lines) do splitlines[lpos] = luci.util.split(luci.util.trim(line), "%s+", nil, true) end -- For each split line, if the word at all indices specified -- to be formatted are not null, add the formatted line to the -- gathered output. output = "" for lpos,splitline in ipairs(splitlines) do loutput = "" for ipos,index in ipairs(indices) do if splitline[index] ~= nil then loutput = loutput .. string.format("%-40s", splitline[index]) else loutput = nil break end end if loutput ~= nil then output = output .. loutput .. "\n" end end return output end m = Map (modulename, translate("PBX Main Page"), translate("This configuration page allows you to configure a phone system (PBX) service which \ permits making phone calls through multiple Google and SIP (like Sipgate, \ SipSorcery, and Betamax) accounts and sharing them among many SIP devices. \ Note that Google accounts, SIP accounts, and local user accounts are configured in the \ \"Google Accounts\", \"SIP Accounts\", and \"User Accounts\" sub-sections. \ You must add at least one User Account to this PBX, and then configure a SIP device or \ softphone to use the account, in order to make and receive calls with your Google/SIP \ accounts. Configuring multiple users will allow you to make free calls between all users, \ and share the configured Google and SIP accounts. If you have more than one Google and SIP \ accounts set up, you should probably configure how calls to and from them are routed in \ the \"Call Routing\" page. If you're interested in using your own PBX from anywhere in the \ world, then visit the \"Remote Usage\" section in the \"Advanced Settings\" page.")) ----------------------------------------------------------------------------------------- s = m:section(NamedSection, "connection_status", "main", translate("PBX Service Status")) s.anonymous = true s:option (DummyValue, "status", translate("Service Status")) sts = s:option(DummyValue, "_sts") sts.template = "cbi/tvalue" sts.rows = 20 function sts.cfgvalue(self, section) if server == "asterisk" then regs = luci.sys.exec("asterisk -rx 'sip show registry' | sed 's/peer-//'") jabs = luci.sys.exec("asterisk -rx 'jabber show connections' | grep onnected") usrs = luci.sys.exec("asterisk -rx 'sip show users'") chan = luci.sys.exec("asterisk -rx 'core show channels'") return format_indices(regs, {1, 5}) .. format_indices(jabs, {2, 4}) .. "\n" .. format_indices(usrs, {1} ) .. "\n" .. chan elseif server == "freeswitch" then return "Freeswitch is not supported yet.\n" else return "Neither Asterisk nor FreeSwitch discovered, please install Asterisk, as Freeswitch is not supported yet.\n" end end return m
apache-2.0
teamactivebot/team-active
plugins/me.lua
4
2591
do local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stat(chat_id, typee) -- Users on chat local hash = '' if typee == 'channel' then hash = 'channel:'..chat_id..':users' else hash = 'chat:'..chat_id..':users' end local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local arian = '0' local text = 'users in this chat \n' for k,user in pairs(users_info) do --text = text..user.name..' = '..user.msgs..'\n' arian = arian + user.msgs end return arian end local function rsusername_cb(extra, success, result) if success == 1 then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local chatid = get_receiver(extra.msg) local username = result.username function round2(num, idp) return tonumber(string.format("%." .. (idp or 0) .. "f", num)) end local r = tonumber(chat_stat(extra.msg.to.id, extra.msg.to.type) or 0) local hashs = 'msgs:'..result.peer_id..':'..extra.msg.to.id local msgss = redis:get(hashs) local percent = msgss / r * 100 local text = "نام شما : "..name.."\nتعداد پیام ها ارسالی توسط شما : "..msgss.." ("..round2(percent).."%)\n تمام پیام های ارسال شده در گروه: "..r.."" text = string.gsub(text, '0', '۰') text = string.gsub(text, '1', '۱') text = string.gsub(text, '2', '۲') text = string.gsub(text, '3', '۳') text = string.gsub(text, '4', '۴') text = string.gsub(text, '5', '۵') text = string.gsub(text, '6', '۶') text = string.gsub(text, '7', '۷') text = string.gsub(text, '8', '۸') text = string.gsub(text, '9', '۹') return send_large_msg(chatid,text ) end end local function run(msg, matches) local chat_id = msg.to.id --return chat_stat(chat_id) resolve_username(msg.from.username, rsusername_cb, {msg=msg}) end return { patterns = { "^[!/](me)$", }, run = run } end
gpl-2.0
AdamGagorik/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/_iz2.lua
13
1986
----------------------------------- -- Area: The Garden of RuHmet -- NPC: _iz2 (Ebon_Panel) -- @pos 422.351 -5.180 -100.000 35 | Hume Tower ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Race = player:getRace(); if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x00CA); elseif (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") == 2) then if ( Race==2 or Race==1) then player:startEvent(0x0078); else player:messageSpecial(NO_NEED_INVESTIGATE); end else player:messageSpecial(NO_NEED_INVESTIGATE); 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 == 0x00CA) then player:setVar("PromathiaStatus",2); elseif (0x0078 and option ~=0) then -- Hume player:addTitle(WARRIOR_OF_THE_CRYSTAL); player:setVar("PromathiaStatus",3); player:addKeyItem(LIGHT_OF_VAHZL); player:messageSpecial(KEYITEM_OBTAINED,LIGHT_OF_VAHZL); end end;
gpl-3.0
sjznxd/lc-20130204
applications/luci-coovachilli/luasrc/model/cbi/coovachilli_network.lua
79
1639
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.ip") m = Map("coovachilli") -- tun s1 = m:section(TypedSection, "tun") s1.anonymous = true s1:option( Flag, "usetap" ) s1:option( Value, "tundev" ).optional = true s1:option( Value, "txqlen" ).optional = true net = s1:option( Value, "net" ) for _, route in ipairs(luci.sys.net.routes()) do if route.device ~= "lo" and route.dest:prefix() < 32 then net:value( route.dest:string() ) end end s1:option( Value, "dynip" ).optional = true s1:option( Value, "statip" ).optional = true s1:option( Value, "dns1" ).optional = true s1:option( Value, "dns2" ).optional = true s1:option( Value, "domain" ).optional = true s1:option( Value, "ipup" ).optional = true s1:option( Value, "ipdown" ).optional = true s1:option( Value, "conup" ).optional = true s1:option( Value, "condown" ).optional = true -- dhcp config s2 = m:section(TypedSection, "dhcp") s2.anonymous = true dif = s2:option( Value, "dhcpif" ) for _, nif in ipairs(luci.sys.net.devices()) do if nif ~= "lo" then dif:value(nif) end end s2:option( Value, "dhcpmac" ).optional = true s2:option( Value, "lease" ).optional = true s2:option( Value, "dhcpstart" ).optional = true s2:option( Value, "dhcpend" ).optional = true s2:option( Flag, "eapolenable" ) return m
apache-2.0
sjznxd/lc-20130204
applications/luci-commands/luasrc/controller/commands.lua
76
5959
--[[ LuCI - Lua Configuration Interface Copyright 2012 Jo-Philipp Wich <jow@openwrt.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 ]]-- module("luci.controller.commands", package.seeall) function index() entry({"admin", "system", "commands"}, firstchild(), _("Custom Commands"), 80) entry({"admin", "system", "commands", "dashboard"}, template("commands"), _("Dashboard"), 1) entry({"admin", "system", "commands", "config"}, cbi("commands"), _("Configure"), 2) entry({"admin", "system", "commands", "run"}, call("action_run"), nil, 3).leaf = true entry({"admin", "system", "commands", "download"}, call("action_download"), nil, 3).leaf = true entry({"command"}, call("action_public"), nil, 1).leaf = true end --- Decode a given string into arguments following shell quoting rules --- [[abc \def "foo\"bar" abc'def']] -> [[abc def]] [[foo"bar]] [[abcdef]] local function parse_args(str) local args = { } local function isspace(c) if c == 9 or c == 10 or c == 11 or c == 12 or c == 13 or c == 32 then return c end end local function isquote(c) if c == 34 or c == 39 or c == 96 then return c end end local function isescape(c) if c == 92 then return c end end local function ismeta(c) if c == 36 or c == 92 or c == 96 then return c end end --- Convert given table of byte values into a Lua string and append it to --- the "args" table. Segment byte value sequence into chunks of 256 values --- to not trip over the parameter limit for string.char() local function putstr(bytes) local chunks = { } local csz = 256 local upk = unpack local chr = string.char local min = math.min local len = #bytes local off for off = 1, len, csz do chunks[#chunks+1] = chr(upk(bytes, off, min(off + csz - 1, len))) end args[#args+1] = table.concat(chunks) end --- Scan substring defined by the indexes [s, e] of the string "str", --- perform unquoting and de-escaping on the fly and store the result in --- a table of byte values which is passed to putstr() local function unquote(s, e) local off, esc, quote local res = { } for off = s, e do local byte = str:byte(off) local q = isquote(byte) local e = isescape(byte) local m = ismeta(byte) if e then esc = true elseif esc then if m then res[#res+1] = 92 end res[#res+1] = byte esc = false elseif q and quote and q == quote then quote = nil elseif q and not quote then quote = q else if m then res[#res+1] = 92 end res[#res+1] = byte end end putstr(res) end --- Find substring boundaries in "str". Ignore escaped or quoted --- whitespace, pass found start- and end-index for each substring --- to unquote() local off, esc, start, quote for off = 1, #str + 1 do local byte = str:byte(off) local q = isquote(byte) local s = isspace(byte) or (off > #str) local e = isescape(byte) if esc then esc = false elseif e then esc = true elseif q and quote and q == quote then quote = nil elseif q and not quote then start = start or off quote = q elseif s and not quote then if start then unquote(start, off - 1) start = nil end else start = start or off end end --- If the "quote" is still set we encountered an unfinished string if quote then unquote(start, #str) end return args end local function parse_cmdline(cmdid, args) local uci = require "luci.model.uci".cursor() if uci:get("luci", cmdid) == "command" then local cmd = uci:get_all("luci", cmdid) local argv = parse_args(cmd.command) local i, v if cmd.param == "1" and args then for i, v in ipairs(parse_args(luci.http.urldecode(args))) do argv[#argv+1] = v end end for i, v in ipairs(argv) do if v:match("[^%w%.%-i/]") then argv[i] = '"%s"' % v:gsub('"', '\\"') end end return argv end end function action_run(...) local fs = require "nixio.fs" local argv = parse_cmdline(...) if argv then local outfile = os.tmpname() local errfile = os.tmpname() local rv = os.execute(table.concat(argv, " ") .. " >%s 2>%s" %{ outfile, errfile }) local stdout = fs.readfile(outfile, 1024 * 512) or "" local stderr = fs.readfile(errfile, 1024 * 512) or "" fs.unlink(outfile) fs.unlink(errfile) local binary = not not (stdout:match("[%z\1-\8\14-\31]")) luci.http.prepare_content("application/json") luci.http.write_json({ command = table.concat(argv, " "), stdout = not binary and stdout, stderr = stderr, exitcode = rv, binary = binary }) else luci.http.status(404, "No such command") end end function action_download(...) local fs = require "nixio.fs" local argv = parse_cmdline(...) if argv then local fd = io.popen(table.concat(argv, " ") .. " 2>/dev/null") if fd then local chunk = fd:read(4096) or "" local name if chunk:match("[%z\1-\8\14-\31]") then luci.http.header("Content-Disposition", "attachment; filename=%s" % fs.basename(argv[1]):gsub("%W+", ".") .. ".bin") luci.http.prepare_content("application/octet-stream") else luci.http.header("Content-Disposition", "attachment; filename=%s" % fs.basename(argv[1]):gsub("%W+", ".") .. ".txt") luci.http.prepare_content("text/plain") end while chunk do luci.http.write(chunk) chunk = fd:read(4096) end fd:close() else luci.http.status(500, "Failed to execute command") end else luci.http.status(404, "No such command") end end function action_public(cmdid, args) local uci = require "luci.model.uci".cursor() if cmdid and uci:get("luci", cmdid) == "command" and uci:get("luci", cmdid, "public") == "1" then action_download(cmdid, args) else luci.http.status(403, "Access to command denied") end end
apache-2.0
Snazz2001/fbcunn
examples/imagenet/models/vgg_cudnn.lua
8
2154
function createModel(nGPU) require 'cudnn' local modelType = 'A' -- on a titan black, B/D/E run out of memory even for batch-size 32 -- Create tables describing VGG configurations A, B, D, E local cfg = {} if modelType == 'A' then cfg = {64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'} elseif modelType == 'B' then cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'} elseif modelType == 'D' then cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'} elseif modelType == 'E' then cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'} else error('Unknown model type: ' .. modelType .. ' | Please specify a modelType A or B or D or E') end local features = nn.Sequential() do local iChannels = 3; for k,v in ipairs(cfg) do if v == 'M' then features:add(cudnn.SpatialMaxPooling(2,2,2,2)) else local oChannels = v; local conv3 = cudnn.SpatialConvolution(iChannels,oChannels,3,3,1,1,1,1); features:add(conv3) features:add(cudnn.ReLU(true)) iChannels = oChannels; end end end local classifier = nn.Sequential() classifier:add(nn.View(512*7*7)) classifier:add(nn.Linear(512*7*7, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(4096, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(4096, 1000)) classifier:add(nn.LogSoftMax()) if nGPU > 1 then assert(nGPU <= cutorch.getDeviceCount(), 'number of GPUs less than nGPU specified') local features_single = features require 'fbcunn' features = nn.DataParallel(1) for i=1,nGPU do cutorch.withDevice(i, function() features:add(features_single:clone()) end) end end local model = nn.Sequential() model:add(features):add(classifier) return model end
bsd-3-clause
robertfoss/nodemcu-firmware
lua_modules/bmp085/bmp085.lua
69
5037
-------------------------------------------------------------------------------- -- BMP085 I2C module for NODEMCU -- NODEMCU TEAM -- LICENCE: http://opensource.org/licenses/MIT -- Christee <Christee@nodemcu.com> -------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M --default value for i2c communication local id=0 --default oversampling setting local oss = 0 --CO: calibration coefficients table. local CO = {} -- read reg for 1 byte local function read_reg(dev_addr, reg_addr) i2c.start(id) i2c.address(id, dev_addr ,i2c.TRANSMITTER) i2c.write(id,reg_addr) i2c.stop(id) i2c.start(id) i2c.address(id, dev_addr,i2c.RECEIVER) local c=i2c.read(id,1) i2c.stop(id) return c end --write reg for 1 byte local function write_reg(dev_addr, reg_addr, reg_val) i2c.start(id) i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.write(id, reg_addr) i2c.write(id, reg_val) i2c.stop(id) end --get signed or unsigned 16 --parameters: --reg_addr: start address of short --signed: if true, return signed16 local function getShort(reg_addr, signed) local tH = string.byte(read_reg(0x77, reg_addr)) local tL = string.byte(read_reg(0x77, (reg_addr + 1))) local temp = tH*256 + tL if (temp > 32767) and (signed == true) then temp = temp - 65536 end return temp end -- initialize i2c --parameters: --d: sda --l: scl function M.init(d, l) if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then sda = d scl = l else print("iic config failed!") return nil end print("init done") i2c.setup(id, sda, scl, i2c.SLOW) --get calibration coefficients. CO.AC1 = getShort(0xAA, true) CO.AC2 = getShort(0xAC, true) CO.AC3 = getShort(0xAE, true) CO.AC4 = getShort(0xB0) CO.AC5 = getShort(0xB2) CO.AC6 = getShort(0xB4) CO.B1 = getShort(0xB6, true) CO.B2 = getShort(0xB8, true) CO.MB = getShort(0xBA, true) CO.MC = getShort(0xBC, true) CO.MD = getShort(0xBE, true) end --get temperature from bmp085 --parameters: --num_10x: bool value, if true, return number of 0.1 centi-degree -- default value is false, which return a string , eg: 16.7 function M.getUT(num_10x) write_reg(0x77, 0xF4, 0x2E); tmr.delay(10000); local temp = getShort(0xF6) local X1 = (temp - CO.AC6) * CO.AC5 / 32768 local X2 = CO.MC * 2048/(X1 + CO.MD) local r = (X2 + X1 + 8)/16 if(num_10x == true) then return r else return ((r/10).."."..(r%10)) end end --get raw data of pressure from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getUP_raw(oss) local os = 0 if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then os = oss end local ov = os * 64 write_reg(0x77, 0xF4, (0x34 + ov)); tmr.delay(30000); --delay 30ms, according to bmp085 document, wait time are: -- 4.5ms 7.5ms 13.5ms 25.5ms respectively according to oss 0,1,2,3 local MSB = string.byte(read_reg(0x77, 0xF6)) local LSB = string.byte(read_reg(0x77, 0xF7)) local XLSB = string.byte(read_reg(0x77, 0xF8)) local up_raw = (MSB*65536 + LSB *256 + XLSB)/2^(8 - os) return up_raw end --get calibrated data of pressure from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getUP(oss) local os = 0 if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then os = oss end local raw = M.getUP_raw(os) local B5 = M.getUT(true) * 16 - 8; local B6 = B5 - 4000 local X1 = CO.B2 * (B6 * B6 /4096)/2048 local X2 = CO.AC2 * B6 / 2048 local X3 = X1 + X2 local B3 = ((CO.AC1*4 + X3)*2^os + 2)/4 X1 = CO.AC3 * B6 /8192 X2 = (CO.B1 * (B6 * B6 / 4096))/65536 X3 = (X1 + X2 + 2)/4 local B4 = CO.AC4 * (X3 + 32768) / 32768 local B7 = (raw -B3) * (50000/2^os) local p = B7/B4 * 2 X1 = (p/256)^2 X1 = (X1 *3038)/65536 X2 = (-7357 *p)/65536 p = p +(X1 + X2 + 3791)/16 return p end --get estimated data of altitude from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getAL(oss) --Altitudi can be calculated by pressure refer to sea level pressure, which is 101325 --pressure changes 100pa corresponds to 8.43m at sea level return (M.getUP(oss) - 101325)*843/10000 end return M
mit
AdamGagorik/darkstar
scripts/zones/Spire_of_Mea/npcs/_0l3.lua
39
1330
----------------------------------- -- Area: Spire_of_Mea -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Mea/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Mea/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/dark_bass.lua
18
1328
----------------------------------------- -- ID: 4428 -- Item: dark_bass -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local 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,4428); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/weaponskills/flash_nova.lua
9
1395
----------------------------------- -- Skill level: 290 -- Delivers light elemental damage. Additional effect: Flash. Chance of effect varies with TP. -- Generates a significant amount of Enmity. -- Does not stack with Sneak Attack -- Aligned with Aqua Gorget. -- Aligned with Aqua Belt. -- Properties: -- Element: Light -- Skillchain Properties:Induration Reverberation -- Modifiers: STR:30% MND:30% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_CLB; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.5; params.mnd_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Windurst_Woods/npcs/Mushuhi-Metahi.lua
59
1052
----------------------------------- -- Area: Windurst Woods -- NPC: Mushuhi-Metahi -- Type: Weather Reporter ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x82718,0,0,0,0,0,0,0,VanadielTime()); 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/Wata_Khamazom.lua
13
1476
----------------------------------- -- Area: Nashmau -- NPC: Wata Khamazom -- 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,WATAKHAMAZOM_SHOP_DIALOG); stock = {0x4300,44, -- Shortbow 0x4301,536, -- Self Bow 0x4302,7920, -- Wrapped Bow 0x4308,492, -- Longbow 0x430A,21812, -- Great Bow 0x43A6,4, -- Wooden Arrow 0x43A8,8, -- Iron Arrow 0x43A9,18, -- Silver Arrow 0x43AA,140, -- Fire Arrow 0x43B8,6, -- Crossbow Bolt 0x4752,248} -- Throwing Tomahawk 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
sbuettner/kong
kong/plugins/oauth2/access.lua
2
13741
local stringy = require "stringy" local utils = require "kong.tools.utils" local cache = require "kong.tools.database_cache" local responses = require "kong.tools.responses" local constants = require "kong.constants" local timestamp = require "kong.tools.timestamp" local _M = {} local CONTENT_LENGTH = "content-length" local RESPONSE_TYPE = "response_type" local STATE = "state" local CODE = "code" local TOKEN = "token" local REFRESH_TOKEN = "refresh_token" local SCOPE = "scope" local CLIENT_ID = "client_id" local CLIENT_SECRET = "client_secret" local REDIRECT_URI = "redirect_uri" local ACCESS_TOKEN = "access_token" local GRANT_TYPE = "grant_type" local GRANT_AUTHORIZATION_CODE = "authorization_code" local GRANT_CLIENT_CREDENTIALS = "client_credentials" local GRANT_REFRESH_TOKEN = "refresh_token" local ERROR = "error" local AUTHENTICATED_USERID = "authenticated_userid" local AUTHORIZE_URL = "^%s/oauth2/authorize/?$" local TOKEN_URL = "^%s/oauth2/token/?$" -- TODO: Expire token (using TTL ?) local function generate_token(conf, credential, authenticated_userid, scope, state, expiration) local token_expiration = expiration or conf.token_expiration local token, err = dao.oauth2_tokens:insert({ credential_id = credential.id, authenticated_userid = authenticated_userid, expires_in = token_expiration, scope = scope }) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end return { access_token = token.access_token, token_type = "bearer", expires_in = token_expiration > 0 and token.expires_in or nil, refresh_token = token_expiration > 0 and token.refresh_token or nil, state = state -- If state is nil, this value won't be added } end local function get_redirect_uri(client_id) local client if client_id then client = cache.get_or_set(cache.oauth2_credential_key(client_id), function() local credentials, err = dao.oauth2_credentials:find_by_keys { client_id = client_id } local result if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) elseif #credentials > 0 then result = credentials[1] end return result end) end return client and client.redirect_uri or nil, client end local function retrieve_parameters() ngx.req.read_body() -- OAuth2 parameters could be in both the querystring or body return utils.table_merge(ngx.req.get_uri_args(), ngx.req.get_post_args()) end local function retrieve_scopes(parameters, conf) local scope = parameters[SCOPE] local scopes = {} if conf.scopes and scope then for v in scope:gmatch("%w+") do if not utils.table_contains(conf.scopes, v) then return false, {[ERROR] = "invalid_scope", error_description = "\""..v.."\" is an invalid "..SCOPE} else table.insert(scopes, v) end end elseif not scope and conf.mandatory_scope then return false, {[ERROR] = "invalid_scope", error_description = "You must specify a "..SCOPE} end return true, scopes end local function authorize(conf) local response_params = {} local parameters = retrieve_parameters() local redirect_uri, client local state = parameters[STATE] if conf.provision_key ~= parameters.provision_key then response_params = {[ERROR] = "invalid_provision_key", error_description = "Invalid Kong provision_key"} elseif not parameters.authenticated_userid or stringy.strip(parameters.authenticated_userid) == "" then response_params = {[ERROR] = "invalid_authenticated_userid", error_description = "Missing authenticated_userid parameter"} else local response_type = parameters[RESPONSE_TYPE] -- Check response_type if not ((response_type == CODE and conf.enable_authorization_code) or (conf.enable_implicit_grant and response_type == TOKEN)) then -- Authorization Code Grant (http://tools.ietf.org/html/rfc6749#section-4.1.1) response_params = {[ERROR] = "unsupported_response_type", error_description = "Invalid "..RESPONSE_TYPE} end -- Check scopes local ok, scopes = retrieve_scopes(parameters, conf) if not ok then response_params = scopes -- If it's not ok, then this is the error message end -- Check client_id and redirect_uri redirect_uri, client = get_redirect_uri(parameters[CLIENT_ID]) if not redirect_uri then response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..CLIENT_ID} elseif parameters[REDIRECT_URI] and parameters[REDIRECT_URI] ~= redirect_uri then response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..REDIRECT_URI.." that does not match with the one created with the application"} end -- If there are no errors, keep processing the request if not response_params[ERROR] then if response_type == CODE then local authorization_code, err = dao.oauth2_authorization_codes:insert({ authenticated_userid = parameters[AUTHENTICATED_USERID], scope = table.concat(scopes, " ") }) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end response_params = { code = authorization_code.code, } else -- Implicit grant, override expiration to zero response_params = generate_token(conf, client, parameters[AUTHENTICATED_USERID], table.concat(scopes, " "), state, 0) end end end -- Adding the state if it exists. If the state == nil then it won't be added response_params.state = state -- Stopping other phases ngx.ctx.stop_phases = true -- Sending response in JSON format responses.send(response_params[ERROR] and 400 or 200, redirect_uri and { redirect_uri = redirect_uri.."?"..ngx.encode_args(response_params) } or response_params, false, { ["cache-control"] = "no-store", ["pragma"] = "no-cache" }) end local function retrieve_client_credentials(parameters) local client_id, client_secret local authorization_header = ngx.req.get_headers()["authorization"] if parameters[CLIENT_ID] then client_id = parameters[CLIENT_ID] client_secret = parameters[CLIENT_SECRET] elseif authorization_header then local iterator, iter_err = ngx.re.gmatch(authorization_header, "\\s*[Bb]asic\\s*(.+)") if not iterator then ngx.log(ngx.ERR, iter_err) return end local m, err = iterator() if err then ngx.log(ngx.ERR, err) return end if m and table.getn(m) > 0 then local decoded_basic = ngx.decode_base64(m[1]) if decoded_basic then local basic_parts = stringy.split(decoded_basic, ":") client_id = basic_parts[1] client_secret = basic_parts[2] print(client_id) print(client_secret) end end end return client_id, client_secret end local function issue_token(conf) local response_params = {} local parameters = retrieve_parameters() --TODO: Also from authorization header local state = parameters[STATE] local grant_type = parameters[GRANT_TYPE] if not (grant_type == GRANT_AUTHORIZATION_CODE or grant_type == GRANT_REFRESH_TOKEN or (conf.enable_client_credentials and grant_type == GRANT_CLIENT_CREDENTIALS)) then response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..GRANT_TYPE} end local client_id, client_secret = retrieve_client_credentials(parameters) -- Check client_id and redirect_uri local redirect_uri, client = get_redirect_uri(client_id) if not redirect_uri then response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..CLIENT_ID} elseif parameters[REDIRECT_URI] and parameters[REDIRECT_URI] ~= redirect_uri then response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..REDIRECT_URI.." that does not match with the one created with the application"} end if client and client.client_secret ~= client_secret then response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..CLIENT_SECRET} end if not response_params[ERROR] then if grant_type == GRANT_AUTHORIZATION_CODE then local code = parameters[CODE] local authorization_code = code and dao.oauth2_authorization_codes:find_by_keys({code = code})[1] or nil if not authorization_code then response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..CODE} else response_params = generate_token(conf, client, authorization_code.authenticated_userid, authorization_code.scope, state) end elseif grant_type == GRANT_CLIENT_CREDENTIALS then -- Check scopes local ok, scopes = retrieve_scopes(parameters, conf) if not ok then response_params = scopes -- If it's not ok, then this is the error message else response_params = generate_token(conf, client, nil, table.concat(scopes, " "), state) end elseif grant_type == GRANT_REFRESH_TOKEN then local refresh_token = parameters[REFRESH_TOKEN] local token = refresh_token and dao.oauth2_tokens:find_by_keys({refresh_token = refresh_token})[1] or nil if not token then response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..REFRESH_TOKEN} else response_params = generate_token(conf, client, token.authenticated_userid, token.scope, state) dao.oauth2_tokens:delete({id=token.id}) -- Delete old token end end end -- Adding the state if it exists. If the state == nil then it won't be added response_params.state = state -- Stopping other phases ngx.ctx.stop_phases = true -- Sending response in JSON format responses.send(response_params[ERROR] and 400 or 200, response_params, false, { ["cache-control"] = "no-store", ["pragma"] = "no-cache" }) end local function retrieve_token(access_token) local token if access_token then token = cache.get_or_set(cache.oauth2_token_key(access_token), function() local credentials, err = dao.oauth2_tokens:find_by_keys { access_token = access_token } local result if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) elseif #credentials > 0 then result = credentials[1] end return result end) end return token end local function parse_access_token(conf) local found_in = {} local result = retrieve_parameters()["access_token"] if not result then local authorization = ngx.req.get_headers()["authorization"] if authorization then local parts = {} for v in authorization:gmatch("%w+") do -- Split by space table.insert(parts, v) end if #parts == 2 and (parts[1]:lower() == "token" or parts[1]:lower() == "bearer") then result = parts[2] found_in.authorization_header = true end end end if conf.hide_credentials then if found_in.authorization_header then ngx.req.clear_header("authorization") else -- Remove from querystring local parameters = ngx.req.get_uri_args() parameters[ACCESS_TOKEN] = nil ngx.req.set_uri_args(parameters) if ngx.req.get_method() ~= "GET" then -- Remove from body ngx.req.read_body() parameters = ngx.req.get_post_args() parameters[ACCESS_TOKEN] = nil local encoded_args = ngx.encode_args(parameters) ngx.req.set_header(CONTENT_LENGTH, string.len(encoded_args)) ngx.req.set_body_data(encoded_args) end end end return result end function _M.execute(conf) local path_prefix = ngx.ctx.api.path or "" if stringy.endswith(path_prefix, "/") then path_prefix = path_prefix:sub(1, path_prefix:len() - 1) end if ngx.req.get_method() == "POST" then if ngx.re.match(ngx.var.request_uri, string.format(AUTHORIZE_URL, path_prefix)) then authorize(conf) elseif ngx.re.match(ngx.var.request_uri, string.format(TOKEN_URL, path_prefix)) then issue_token(conf) end end local token = retrieve_token(parse_access_token(conf)) if not token then ngx.ctx.stop_phases = true -- interrupt other phases of this request return responses.send_HTTP_FORBIDDEN("Invalid authentication credentials") end -- Check expiration date if token.expires_in > 0 then -- zero means the token never expires local now = timestamp.get_utc() if now - token.created_at > (token.expires_in * 1000) then ngx.ctx.stop_phases = true -- interrupt other phases of this request return responses.send_HTTP_BAD_REQUEST({[ERROR] = "invalid_request", error_description = "access_token expired"}) end end -- Retrive the credential from the token local credential = cache.get_or_set(cache.oauth2_credential_key(token.credential_id), function() local result, err = dao.oauth2_credentials:find_by_primary_key({id = token.credential_id}) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end return result end) -- Retrive the consumer from the credential local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), function() local result, err = dao.consumers:find_by_primary_key({id = credential.consumer_id}) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end return result end) ngx.req.set_header(constants.HEADERS.CONSUMER_ID, consumer.id) ngx.req.set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id) ngx.req.set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username) ngx.req.set_header("x-authenticated-scope", token.scope) ngx.req.set_header("x-authenticated-userid", token.authenticated_userid) ngx.ctx.authenticated_entity = credential end return _M
mit
AdamGagorik/darkstar
scripts/zones/Northern_San_dOria/npcs/Mevreauche.lua
44
2103
----------------------------------- -- Area: Northern San d'Oria -- NPC: Mevreauche -- Type: Smithing Guild Master -- @pos -193.584 10 148.655 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILL_SMITHING); if (newRank ~= 0) then player:setSkillRank(SKILL_SMITHING,newRank); player:startEvent(0x0273,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILL_SMITHING); local testItem = getTestItem(player,npc,SKILL_SMITHING); local guildMember = isGuildMember(player,8); if (guildMember == 1) then guildMember = 150995375; end if (canGetNewRank(player,craftSkill,SKILL_SMITHING) == 1) then getNewRank = 100; end player:startEvent(0x0272,testItem,getNewRank,30,guildMember,44,0,0,0); end; -- 0x0272 0x0273 0x0010 0x0000 0x0049 0x004a ----------------------------------- -- 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 == 0x0272 and option == 1) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4096); else player:addItem(4096); player:messageSpecial(ITEM_OBTAINED,4096); -- Fire Crystal signupGuild(player,256); end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Port_Bastok/npcs/Tete.lua
13
1283
----------------------------------- -- Area: Port Bastok -- NPC: Tete -- Continues Quest: The Wisdom Of Elders ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ------------------------------------ require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,THE_WISDOM_OF_ELDERS) == QUEST_ACCEPTED) then player:startEvent(0x00af); else player:startEvent(0x0023); 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 == 0x00af) then player:setVar("TheWisdomVar",2); end end;
gpl-3.0
talldan/lua-reactor
tests/specs/reactor/propTypes/tableShape.lua
1
3906
local tableShape = require('reactor.propTypes.tableShape') local function trueValidator() return true end local function falseValidator() return false, 'this validation failed' end describe('tableShape', function() describe('error states', function() it('causes an error is the table shape description is not expressed as a table', function() expect(function() tableShape() end).to.fail() expect(function() tableShape('test') end).to.fail() expect(function() tableShape(12) end).to.fail() expect(function() tableShape(true) end).to.fail() expect(function() tableShape(function() end) end).to.fail() end) end) describe('behaviour', function() it('returns a function to use for validation when passed a valid description', function() expect(type(tableShape({}))) .to.be('function') end) it('returns false if a table is not specified to the validator', function() local validateEmptyTable = tableShape({}) expect(validateEmptyTable()) .to.be(false) expect(validateEmptyTable('test')) .to.be(false) expect(validateEmptyTable(12)) .to.be(false) expect(validateEmptyTable(false)) .to.be(false) expect(validateEmptyTable(function() end)) .to.be(false) end) it('returns false if a table has a different number of keys to the validation description', function() local validateTable = tableShape({ test = trueValidator }) expect(validateTable({})) .to.be(false) expect(validateTable({1, 2})) .to.be(false) end) it('returns false if the specified keys in the able are named differently to the description', function() local validateTable = tableShape({ test = trueValidator, anotherTest = trueValidator }) expect(validateTable({ test = 'hi', notAnotherTest = 2 })).to.be(false) expect(validateTable({ notTest = 'hi', anotherTest = 2 })).to.be(false) end) it('returns false if any of the properties do not pass validation', function() local validateTable = tableShape({ test = trueValidator, anotherTest = falseValidator }) expect(validateTable({ test = 'hi', anotherTest = 2 })).to.be(false) end) it('returns true when all properties pass validation', function() local validateTable = tableShape({ test = trueValidator, anotherTest = trueValidator }) expect(validateTable({ test = 'hi', anotherTest = 2 })).to.be(true) end) it('matches an empty table correctly', function() local validateEmptyTable = tableShape({}) expect(validateEmptyTable({})) .to.be(true) end) it('passes the property value to the property validator', function() local passedValue = nil local testValue = 'aloha' local validateTable = tableShape({ test = function(value) passedValue = value return testValue == passedValue end }) validateTable({ test = testValue }) expect(passedValue) .to.be(testValue) end) it('does not return a second return value when validation is successful', function() local validator = tableShape({ test = trueValidator }) local isValid, reason = validator({ test = 'test' }) expect(reason) .to.be(nil) end) it('returns a second return value of type string that represents the reason validation failed', function() local validator = tableShape({ test = falseValidator }) local isValid, reason = validator({ test = 'test' }) expect(type(reason)) .to.be('string') end) end) end)
mit
AdamGagorik/darkstar
scripts/zones/Mount_Zhayolm/mobs/Claret.lua
7
1448
----------------------------------- -- Area: Mount Zhayolm -- MOB: Claret -- @pos 501 -9 53 -- Spawned with Pectin: @additem 2591 -- Wiki: http://ffxiclopedia.wikia.com/wiki/Claret ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:addMod(MOD_REGEN, math.floor(mob:getMaxHP()*.004)); mob:addMod(MOD_BINDRES, 40); mob:SetAutoAttackEnabled(false); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) if (mob:checkDistance(target) < 3) then if (target:hasStatusEffect(EFFECT_POISON) == false) then target:addStatusEffect(EFFECT_POISON, 100, 3, math.random(3,6) * 3); -- Poison for 3-6 ticks. else if (target:getStatusEffect(EFFECT_POISON):getPower() < 100) then target:delStatusEffect(EFFECT_POISON); target:addStatusEffect(EFFECT_POISON, 100, 3, math.random(3,6) * 3); -- Poison for 3-6 ticks. end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/bunny_ball.lua
18
1736
----------------------------------------- -- ID: 4349 -- Item: Bunny Ball -- Food Effect: 240Min, All Races ----------------------------------------- -- Health 10 -- Strength 2 -- Vitality 2 -- Intelligence -1 -- Attack % 30 -- Attack Cap 25 -- Ranged ATT % 30 -- Ranged ATT Cap 25 ----------------------------------------- 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,14400,4349); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_STR, 2); target:addMod(MOD_VIT, 2); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 30); target:addMod(MOD_FOOD_ATT_CAP, 25); target:addMod(MOD_FOOD_RATTP, 30); target:addMod(MOD_FOOD_RATT_CAP, 25); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_STR, 2); target:delMod(MOD_VIT, 2); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 30); target:delMod(MOD_FOOD_ATT_CAP, 25); target:delMod(MOD_FOOD_RATTP, 30); target:delMod(MOD_FOOD_RATT_CAP, 25); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/VeLugannon_Palace/mobs/Brigandish_Blade.lua
7
1272
----------------------------------- -- Area: VeLugannon Palace -- NM: Brigandish Blade ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) local rand = math.random(1,10); if ((rand >= 4) or (target:hasStatusEffect(EFFECT_TERROR) == true)) then -- 30% chance to terror return 0,0,0; else local duration = math.random(3,5); target:addStatusEffect(EFFECT_TERROR,1,0,duration); return SUBEFFECT_NONE,0,EFFECT_TERROR; end end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) GetNPCByID(17502582):updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME); end;
gpl-3.0
Mastersey/waifu2x
cleanup_model.lua
34
1775
require './lib/portable' require './lib/LeakyReLU' torch.setdefaulttensortype("torch.FloatTensor") -- ref: https://github.com/torch/nn/issues/112#issuecomment-64427049 local function zeroDataSize(data) if type(data) == 'table' then for i = 1, #data do data[i] = zeroDataSize(data[i]) end elseif type(data) == 'userdata' then data = torch.Tensor():typeAs(data) end return data end -- Resize the output, gradInput, etc temporary tensors to zero (so that the -- on disk size is smaller) local function cleanupModel(node) if node.output ~= nil then node.output = zeroDataSize(node.output) end if node.gradInput ~= nil then node.gradInput = zeroDataSize(node.gradInput) end if node.finput ~= nil then node.finput = zeroDataSize(node.finput) end if tostring(node) == "nn.LeakyReLU" then if node.negative ~= nil then node.negative = zeroDataSize(node.negative) end end if tostring(node) == "nn.Dropout" then if node.noise ~= nil then node.noise = zeroDataSize(node.noise) end end -- Recurse on nodes with 'modules' if (node.modules ~= nil) then if (type(node.modules) == 'table') then for i = 1, #node.modules do local child = node.modules[i] cleanupModel(child) end end end collectgarbage() end local cmd = torch.CmdLine() cmd:text() cmd:text("cleanup model") cmd:text("Options:") cmd:option("-model", "./model.t7", 'path of model file') cmd:option("-iformat", "binary", 'input format') cmd:option("-oformat", "binary", 'output format') local opt = cmd:parse(arg) local model = torch.load(opt.model, opt.iformat) if model then cleanupModel(model) torch.save(opt.model, model, opt.oformat) else error("model not found") end
mit
AdamGagorik/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Kopol-Rapol.lua
13
1066
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Kopol-Rapol -- Type: Standard NPC -- @zone: 94 -- @pos 131.179 -6.75 172.758 -- -- 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(0x01a6); 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/fish_chiefkabob.lua
18
1530
----------------------------------------- -- ID: 4575 -- Item: fish_chiefkabob -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 1 -- Vitality 2 -- Mind 1 -- Charisma 1 -- defense % 26 -- defense Cap 95 ----------------------------------------- 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,4575); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_VIT, 2); target:addMod(MOD_MND, 1); target:addMod(MOD_CHR, 1); target:addMod(MOD_FOOD_DEFP, 26); target:addMod(MOD_FOOD_DEF_CAP, 95); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_VIT, 2); target:delMod(MOD_MND, 1); target:delMod(MOD_CHR, 1); target:delMod(MOD_FOOD_DEFP, 26); target:delMod(MOD_FOOD_DEF_CAP, 95); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Zabahf.lua
13
1714
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Zabahf -- Type: Standard NPC -- @pos -90.070 -1 10.140 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local gotItAllProg = player:getVar("gotitallCS"); if (gotItAllProg == 1 or gotItAllProg == 3) then player:startEvent(0x0215); elseif (gotItAllProg == 2) then player:startEvent(0x020b); elseif (gotItAllProg == 5) then player:startEvent(0x021a); elseif (gotItAllProg == 6) then player:startEvent(0x021c); elseif (gotItAllProg == 7) then player:startEvent(0x0217); elseif (player:getQuestStatus(AHT_URHGAN,GOT_IT_ALL) == QUEST_COMPLETED) then player:startEvent(0x0212); 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 == 0x020b) then player:setVar("gotitallCS",3); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Porter_Moogle.lua
41
1553
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 50 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 957, STORE_EVENT_ID = 958, RETRIEVE_EVENT_ID = 959, ALREADY_STORED_ID = 960, MAGIAN_TRIAL_ID = 963 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Temple_of_Uggalepih/npcs/Treasure_Coffer.lua
13
4655
----------------------------------- -- Area: Temple of Uggalepih -- NPC: Treasure Coffer -- @zone 159 -- @pos -219 0 32 ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Temple_of_Uggalepih/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1049,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(1049,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(); local listAF = getAFbyZone(zone); if (player:hasKeyItem(MAP_OF_THE_TEMPLE_OF_UGGALEPIH) == false) then questItemNeeded = 3; end 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_TEMPLE_OF_UGGALEPIH); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_TEMPLE_OF_UGGALEPIH); -- Map of the Temple of Uggalepih (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 = chestLoot(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]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); 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,1049); 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_San_dOria/npcs/Perdiouvilet.lua
13
1735
----------------------------------- -- Area: Port San d'Oria -- NPC: Perdiouvilet -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -59 -5 -29 232 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,10) == false) then player:startEvent(0x02ee); else player:startEvent(0x02fa); 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 == 0x02ee) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",10,true); end end;
gpl-3.0
aqasaeed/hesam
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
ashkanpj/firebot
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
shakib01/anonymous01
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
punisherbot/helper
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
srodrigo/lge
etc/premake4.lua
1
1658
-- -- Copyright (C) 2013 Sergio Rodrigo -- -- This software may be modified and distributed under the terms -- of the MIT license. See the LICENSE file for details. -- -- projects lge = "lge" test = "test" -- main dirs base_dir = ".." -- src dirs src_dir = base_dir .. "/src/" lge_src_dir = src_dir .. "/lge/" test_src_dir = src_dir .. "/test/" -- generated dirs lib_dir = base_dir .. "/lib/" build_dir = base_dir .. "/build/" bin_dir = base_dir .. "/bin/" -- libs liblge = "liblge.so" all_sfml_libs = { "sfml-audio", "sfml-network", "sfml-graphics", "sfml-window", "sfml-system" } libunittest = "UnitTest++" solution ("lgeall") location (build_dir) includedirs { src_dir } buildoptions { "-DCONFIGFILE='\"../../etc/logger.config\"'" } configurations { "Debug", "Release" } configuration { "Debug" } targetdir (bin_dir .. "Debug") flags { "Symbols", "ExtraWarnings", "FatalWarnings" } configuration { "Release" } targetdir (bin_dir .. "Release") flags { "Optimize", "ExtraWarnings" } if _ACTION == "clean" then os.rmdir(lib_dir .. liblge) os.rmdir(build_dir) os.rmdir(bin_dir) end project (lge) kind "SharedLib" language "C++" files { lge_src_dir .. "**.h", lge_src_dir .. "**.cpp" } targetdir (lib_dir) for _,sfmllib in pairs(all_sfml_libs) do libdirs { os.findlib(sfmllib) } end links(all_sfml_libs) project (test) kind "ConsoleApp" language "C++" files { test_src_dir .. "**.h", test_src_dir .. "**.cpp" } libdirs { os.findlib(libunittest) } links {lge} links {libunittest} for _,sfmllib in pairs(all_sfml_libs) do libdirs { os.findlib(sfmllib) } end links(all_sfml_libs)
mit
pczarn/kollos
components/test/luif/seq4.lua
1
2395
--[[ Copyright 2015 Jeffrey Kegler 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. --]] -- Prototype the LUIF parser local inspect = require 'kollos.inspect' require 'Test.More' -- luacheck: globals ok plan plan(1) -- luacheck: globals __LINE__ __FILE__ local K = require 'kollos' local kollos = K.config_new{interface = 'alpha'} ok(kollos, 'config_new() returned') local l0 = kollos:grammar_new{ line = __LINE__, file = __FILE__, name = 'l0' } l0:line_set(__LINE__) l0:rule_new{'top'} l0:alternative_new{'one_open'} l0:alternative_new{'one_closed'} l0:alternative_new{'seven_fixed'} l0:alternative_new{'seven_open'} l0:alternative_new{'seven_closed'} l0:line_set(__LINE__) l0:rule_new{'one_open'} l0:alternative_new{'b', 'c', max=-1, separator = 'comma' } l0:line_set(__LINE__) l0:rule_new{'one_closed'} l0:alternative_new{'b', 'c', max=7, separator = 'comma' } l0:line_set(__LINE__) l0:rule_new{'seven_fixed'} l0:alternative_new{'b', 'c', min=7, max=7, separator = 'comma' } l0:rule_new{'seven_open'} l0:alternative_new{'b', 'c', min=7, separator = 'comma' } l0:rule_new{'seven_closed'} l0:alternative_new{'b', 'c', min=7, max=11, separator = 'comma' } l0:rule_new{'b'} l0:alternative_new{l0:string'b'} l0:rule_new{'c'} l0:alternative_new{l0:string'c'} l0:rule_new{'comma'} l0:alternative_new{l0:string','} l0:compile{ seamless = 'top', line = __LINE__} -- print(inspect(l0)) -- vim: expandtab shiftwidth=4:
mit
AdamGagorik/darkstar
scripts/zones/Port_Bastok/npcs/Styi_Palneh.lua
27
4322
----------------------------------- -- Area: Port Bastok -- NPC: Styi Palneh -- Title Change NPC -- @pos 28 4 -15 236 ----------------------------------- require("scripts/globals/titles"); local title2 = { NEW_ADVENTURER , BASTOK_WELCOMING_COMMITTEE , BUCKET_FISHER , PURSUER_OF_THE_PAST , MOMMYS_HELPER , HOT_DOG , STAMPEDER , RINGBEARER , ZERUHN_SWEEPER , TEARJERKER , CRAB_CRUSHER , BRYGIDAPPROVED , GUSTABERG_TOURIST , MOGS_MASTER , CERULEAN_SOLDIER , DISCERNING_INDIVIDUAL , VERY_DISCERNING_INDIVIDUAL , EXTREMELY_DISCERNING_INDIVIDUAL , APOSTATE_FOR_HIRE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { SHELL_OUTER , PURSUER_OF_THE_TRUTH , QIJIS_FRIEND , TREASURE_SCAVENGER , SAND_BLASTER , DRACHENFALL_ASCETIC , ASSASSIN_REJECT , CERTIFIED_ADVENTURER , QIJIS_RIVAL , CONTEST_RIGGER , KULATZ_BRIDGE_COMPANION , AVENGER , AIRSHIP_DENOUNCER , STAR_OF_IFRIT , PURPLE_BELT , MOGS_KIND_MASTER , TRASH_COLLECTOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { BEADEAUX_SURVEYOR , PILGRIM_TO_DEM , BLACK_DEATH , DARK_SIDER , SHADOW_WALKER , SORROW_DROWNER , STEAMING_SHEEP_REGULAR , SHADOW_BANISHER , MOGS_EXCEPTIONALLY_KIND_MASTER , HYPER_ULTRA_SONIC_ADVENTURER , GOBLIN_IN_DISGUISE , BASTOKS_SECOND_BEST_DRESSED , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { PARAGON_OF_WARRIOR_EXCELLENCE , PARAGON_OF_MONK_EXCELLENCE , PARAGON_OF_DARK_KNIGHT_EXCELLENCE , HEIR_OF_THE_GREAT_EARTH , MOGS_LOVING_MASTER , HERO_AMONG_HEROES , DYNAMISBASTOK_INTERLOPER , MASTER_OF_MANIPULATION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { LEGIONNAIRE , DECURION , CENTURION , JUNIOR_MUSKETEER , SENIOR_MUSKETEER , MUSKETEER_COMMANDER , GOLD_MUSKETEER , PRAEFECTUS , SENIOR_GOLD_MUSKETEER , PRAEFECTUS_CASTRORUM , ANVIL_ADVOCATE , FORGE_FANATIC , ACCOMPLISHED_BLACKSMITH , ARMORY_OWNER , TRINKET_TURNER , SILVER_SMELTER , ACCOMPLISHED_GOLDSMITH , JEWELRY_STORE_OWNER , FORMULA_FIDDLER , POTION_POTENTATE , ACCOMPLISHED_ALCHEMIST , APOTHECARY_OWNER , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { MOG_HOUSE_HANDYPERSON , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C8,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); 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==0x00C8) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title5[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end elseif (option > 1280 and option < 1309) then if (player:delGil(700)) then player:setTitle( title7[option - 1280]) end end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Windurst_Waters/npcs/Maysoon.lua
25
2162
----------------------------------- -- Area: Windurst Waters -- NPC: Maysoon -- Starts and Finishes Quest: Hoist the Jelly, Roger -- Involved in Quests: Cook's Pride -- @zone 238 -- @pos -105 -2 69 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,HOIST_THE_JELLY_ROGER) == QUEST_ACCEPTED) then if (trade:hasItemQty(4508,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x2711); -- Finish quest "Hoist the Jelly, Roger" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CooksPride = player:getQuestStatus(JEUNO,COOK_S_PRIDE); HoistTheJelly = player:getQuestStatus(WINDURST,HOIST_THE_JELLY_ROGER); if (CooksPride == QUEST_ACCEPTED and HoistTheJelly == QUEST_AVAILABLE) then player:startEvent(0x2710); -- Start quest "Hoist the Jelly, Roger" else player:startEvent(0x010a); -- 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 == 0x2710) then player:addQuest(WINDURST,HOIST_THE_JELLY_ROGER); elseif (csid == 0x2711) then player:completeQuest(WINDURST,HOIST_THE_JELLY_ROGER); player:addKeyItem(SUPER_SOUP_POT); player:messageSpecial(KEYITEM_OBTAINED,SUPER_SOUP_POT); player:addFame(WINDURST,30); player:tradeComplete(); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/PsoXja/npcs/_099.lua
13
2892
----------------------------------- -- Area: Pso'Xja -- NPC: _099 (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos 250.000 -1.925 -58.399 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == 6) then local Z=player:getZPos(); if (npc:getAnimation() == 9) then if (Z <= -59) then if (GetMobAction(16814090) == 0) then local Rand = math.random(1,2); -- estimated 50% success as per the wiki if (Rand == 1) then -- Spawn Gargoyle player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814090,120):updateClaim(player); -- Gargoyle else player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end player:tradeComplete(); else player:messageSpecial(DOOR_LOCKED); end end end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Z=player:getZPos(); if (npc:getAnimation() == 9) then if (Z <= -59) then if (GetMobAction(16814090) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814090,120):updateClaim(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true); -- 10% Chance the door will simply open without Gargoyle pop npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif (Z >= -58) then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/West_Ronfaure/npcs/Yoshihiro_IM.lua
13
3319
----------------------------------- -- Area: West Ronfaure -- NPC: Yoshihiro, I.M. -- Outpost Conquest Guards -- @pos -450.571 -20.807 -219.970 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Ronfaure/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = RONFAURE; local csid = 0x7ff9; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Lower_Jeuno/npcs/_l01.lua
13
1557
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- @zone 245 -- @pos -101.010 0 -144.080 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); if (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then if (player:getVar("cService") == 10) then player:setVar("cService",11); end elseif (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (player:getVar("cService") == 23) then player:setVar("cService",24); end end 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
ohmbase/OpenRA
mods/ra/maps/soviet-04a/main.lua
15
4321
RunInitialActivities = function() Harvester.FindResources() IdlingUnits() Trigger.AfterDelay(10, function() BringPatrol1() BringPatrol2() BuildBase() end) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == Greece and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == Greece and building.Health < 3/4 * building.MaxHealth then building.StartBuildingRepairs() end end) end end) Reinforcements.Reinforce(player, SovietMCV, SovietStartToBasePath, 0, function(mcv) mcv.Move(StartCamPoint.Location) end) Media.PlaySpeechNotification(player, "ReinforcementsArrived") Trigger.OnKilled(Barr, function(building) BaseBuildings[2][4] = false end) Trigger.OnKilled(Proc, function(building) BaseBuildings[3][4] = false end) Trigger.OnKilled(Weap, function(building) BaseBuildings[4][4] = false end) Trigger.OnEnteredFootprint(VillageCamArea, function(actor, id) if actor.Owner == player then local camera = Actor.Create("camera", true, { Owner = player, Location = VillagePoint.Location }) Trigger.RemoveFootprintTrigger(id) Trigger.OnAllKilled(Village, function() camera.Destroy() end) end end) Trigger.OnAnyKilled(Civs, function() Trigger.ClearAll(civ1) Trigger.ClearAll(civ2) Trigger.ClearAll(civ3) local units = Reinforcements.Reinforce(Greece, Avengers, { SWRoadPoint.Location }, 0) Utils.Do(units, function(unit) unit.Hunt() end) end) Runner1.Move(CrossroadsEastPoint.Location) Runner2.Move(InVillagePoint.Location) Tank5.Move(V2MovePoint.Location) Trigger.AfterDelay(DateTime.Seconds(2), function() Tank1.Stop() Tank2.Stop() Tank3.Stop() Tank4.Stop() Tank5.Stop() Trigger.AfterDelay(1, function() Tank1.Move(SovietBaseEntryPointNE.Location) Tank2.Move(SovietBaseEntryPointW.Location) Tank3.Move(SovietBaseEntryPointNE.Location) Tank4.Move(SovietBaseEntryPointW.Location) Tank5.Move(V2MovePoint.Location) end) end) Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry) Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor) if Map.Difficulty == "Hard" or Map.Difficulty == "Medium" then Trigger.AfterDelay(DateTime.Seconds(15), ReinfInf) end Trigger.AfterDelay(DateTime.Minutes(1), ReinfInf) Trigger.AfterDelay(DateTime.Minutes(3), ReinfInf) Trigger.AfterDelay(DateTime.Minutes(2), ReinfArmor) end Tick = function() if Greece.HasNoRequiredUnits() then player.MarkCompletedObjective(KillAll) player.MarkCompletedObjective(KillRadar) end if player.HasNoRequiredUnits() then Greece.MarkCompletedObjective(BeatUSSR) end if Greece.Resources >= Greece.ResourceCapacity * 0.75 then Greece.Cash = Greece.Cash + Greece.Resources - Greece.ResourceCapacity * 0.25 Greece.Resources = Greece.ResourceCapacity * 0.25 end if RCheck then RCheck = false if Map.Difficulty == "Hard" then Trigger.AfterDelay(DateTime.Seconds(150), ReinfArmor) elseif Map.Difficulty == "Medium" then Trigger.AfterDelay(DateTime.Minutes(5), ReinfArmor) else Trigger.AfterDelay(DateTime.Minutes(8), ReinfArmor) end end end WorldLoaded = function() player = Player.GetPlayer("USSR") Greece = Player.GetPlayer("Greece") RunInitialActivities() 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) KillAll = player.AddPrimaryObjective("Defeat the Allied forces.") BeatUSSR = Greece.AddPrimaryObjective("Defeat the Soviet forces.") KillRadar = player.AddSecondaryObjective("Destroy Allied Radar Dome to stop enemy\nreinforcements.") Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnKilled(Radar, function() player.MarkCompletedObjective(KillRadar) Media.PlaySpeechNotification(player, "ObjectiveMet") end) Camera.Position = StartCamPoint.CenterPosition end
gpl-3.0
cresd/CressD
plugins/anti_chat.lua
62
1069
antichat = {}-- An empty table for solving multiple kicking problem do local function run(msg, matches) if is_momod(msg) then -- Ignore mods,owner,admins return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_chat'] then if data[tostring(msg.to.id)]['settings']['lock_chat'] == 'yes' then if antichat[msg.from.id] == true then return end send_large_msg("chat#id".. msg.to.id , "chat is not allowed here") local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (chat was locked) ") chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false) antichat[msg.from.id] = true return end end return end local function cron() antichat = {} -- Clear antichat table end return { patterns = { "([\216-\219][\128-\191])" }, run = run, cron = cron } end --Copyright; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Southern_San_dOria/npcs/Pourette.lua
12
2175
----------------------------------- -- Area: Southern San d'Oria -- NPC: Pourette -- Only sells when San d'Oria controlls Derfland Region ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/globals/conquest"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end else onHalloweenTrade(player,trade,npc); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(DERFLAND); if (RegionOwner ~= SANDORIA) then player:showText(npc,POURETTE_CLOSED_DIALOG); else player:showText(npc,POURETTE_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,SANDORIA,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/Kazham/npcs/Pofhu_Tendelicon.lua
15
1056
----------------------------------- -- Area: Kazham -- NPC: Pofhu Tendelicon -- Standard Info NPC ----------------------------------- 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) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00A9); -- scent from Blue Rafflesias else player:startEvent(0x0040); 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/Temple_of_Uggalepih/npcs/Tome_of_Magic.lua
13
1134
----------------------------------- -- Area: Temple of Uggalepih -- NPC: Tome of Magic -- Involved In Windurst Mission 7-2 (Optional Dialogue) -- @pos 346 0 343 159 <many> ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Temple_of_Uggalepih/TextIDs"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local cs = math.random(0x014,0x016) player:startEvent(cs); 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/globals/items/bunch_of_san_dorian_grapes.lua
18
1192
----------------------------------------- -- ID: 4431 -- Item: Bunch of San Dorian Grapes -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -5 -- Intelligence 3 ----------------------------------------- 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,300,4431); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -5); target:addMod(MOD_INT, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -5); target:delMod(MOD_INT, 3); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Windurst_Walls/npcs/Hiwon-Biwon.lua
13
3915
----------------------------------- -- Area: Windurst Walls -- NPC: Hiwon-Biwon -- Involved In Quest: Making Headlines, Curses, Foiled...Again!? -- Working 100% ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); local CFA2 = player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_2); -- Curses,Foiled ... Again!? if (CFA2 == QUEST_ACCEPTED and player:hasItem(552) == false) then player:startEvent(0x00B6); -- get Hiwon's hair elseif (CFA2 == QUEST_COMPLETED and MakingHeadlines ~= QUEST_ACCEPTED) then player:startEvent(0x00B9); -- New Dialog after CFA2 -- Making Headlines elseif (MakingHeadlines == 1) then prog = player:getVar("QuestMakingHeadlines_var"); -- Variable to track if player has talked to 4 NPCs and a door -- 1 = Kyume -- 2 = Yujuju -- 4 = Hiwom -- 8 = Umumu -- 16 = Mahogany Door if (testflag(tonumber(prog),4) == false) then if (player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_1) == 1) then if (math.random(1,2) == 1) then player:startEvent(0x011b); -- Give scoop while sick else player:startEvent(0x011c); -- Give scoop while sick end else player:startEvent(0x0119); -- Give scoop end else player:startEvent(0x011a); -- "Getting back to the maater at hand-wand..." end else local rand = math.random(1,5); if (rand == 1) then print (rand); player:startEvent(0x0131); -- Standard Conversation elseif (rand == 2) then print (rand); player:startEvent(0x0132); -- Standard Conversation elseif (rand == 3) then print (rand); player:startEvent(0x00a8); -- Standard Conversation elseif (rand == 4) then print (rand); player:startEvent(0x00aa); -- Standard Conversation elseif (rand == 5) then print (rand); player:startEvent(0x00a9); -- Standard Conversation 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); -- Making Headlines if (csid == 0x0119 or csid == 0x011b or csid == 0x011c) then prog = player:getVar("QuestMakingHeadlines_var"); player:addKeyItem(WINDURST_WALLS_SCOOP); player:messageSpecial(KEYITEM_OBTAINED,WINDURST_WALLS_SCOOP); player:setVar("QuestMakingHeadlines_var",prog+4); -- Curses,Foiled...Again!? elseif (csid == 0x00B6) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,552); -- Hiwon's hair else player:addItem(552); player:messageSpecial(ITEM_OBTAINED,552); -- Hiwon's hair end end end;
gpl-3.0
Hostle/luci
applications/luci-app-pbx/luasrc/model/cbi/pbx-voip.lua
18
4549
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end modulename = "pbx-voip" m = Map (modulename, translate("SIP Accounts"), translate("This is where you set up your SIP (VoIP) accounts ts like Sipgate, SipSorcery, \ the popular Betamax providers, and any other providers with SIP settings in order to start \ using them for dialing and receiving calls (SIP uri and real phone calls). Click \"Add\" to \ add as many accounts as you wish.")) -- Recreate the config, and restart services after changes are commited to the configuration. function m.on_after_commit(self) commit = false -- Create a field "name" for each account that identifies the account in the backend. m.uci:foreach(modulename, "voip_provider", function(s1) if s1.defaultuser ~= nil and s1.host ~= nil then name=string.gsub(s1.defaultuser.."_"..s1.host, "%W", "_") if s1.name ~= name then m.uci:set(modulename, s1['.name'], "name", name) commit = true end end end) if commit == true then m.uci:commit(modulename) end luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(TypedSection, "voip_provider", translate("SIP Provider Accounts")) s.anonymous = true s.addremove = true s:option(Value, "defaultuser", translate("User Name")) pwd = s:option(Value, "secret", translate("Password"), translate("When your password is saved, it disappears from this field and is not displayed \ for your protection. The previously saved password will be changed only when you \ enter a value different from the saved one.")) pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end h = s:option(Value, "host", translate("SIP Server/Registrar")) h.datatype = "host(0)" p = s:option(ListValue, "register", translate("Enable Incoming Calls (Register via SIP)"), translate("This option should be set to \"Yes\" if you have a DID \(real telephone number\) \ associated with this SIP account or want to receive SIP uri calls through this \ provider.")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" p = s:option(ListValue, "make_outgoing_calls", translate("Enable Outgoing Calls"), translate("Use this account to make outgoing calls.")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" from = s:option(Value, "fromdomain", translate("SIP Realm (needed by some providers)")) from.optional = true from.datatype = "host(0)" port = s:option(Value, "port", translate("SIP Server/Registrar Port")) port.optional = true port.datatype = "port" op = s:option(Value, "outboundproxy", translate("Outbound Proxy")) op.optional = true op.datatype = "host(0)" return m
apache-2.0
luveti/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/module.lua
44
1479
-- tolua: module class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Module class -- Represents module. -- The following fields are stored: -- {i} = list of objects in the module. classModule = { classtype = 'module' } classModule.__index = classModule setmetatable(classModule,classContainer) -- register module function classModule:register (pre) pre = pre or '' push(self) output(pre..'tolua_module(tolua_S,"'..self.name..'",',self:hasvar(),');') output(pre..'tolua_beginmodule(tolua_S,"'..self.name..'");') local i=1 while self[i] do self[i]:register(pre..' ') i = i+1 end output(pre..'tolua_endmodule(tolua_S);') pop() end -- Print method function classModule:print (ident,close) print(ident.."Module{") print(ident.." name = '"..self.name.."';") local i=1 while self[i] do self[i]:print(ident.." ",",") i = i+1 end print(ident.."}"..close) end -- Internal constructor function _Module (t) setmetatable(t,classModule) append(t) return t end -- Constructor -- Expects two string representing the module name and body. function Module (n,b) local t = _Module(_Container{name=n}) push(t) t:parse(strsub(b,2,strlen(b)-1)) -- eliminate braces pop() return t end
mit
mwharris333/serval
lib/pnNetwork.lua
2
5652
local thisFile = g.dir.library..'pnNetwork' if (dbg) then dbg.file(thisFile) end -------------------------------------------------------------------------------------------------- math.randomseed(os.time()) -- init random function math.random() -- bug in first use --local uuid = pnObj:UUID() -------------------------------------------------------------------------------------------------- require 'pubnub' -- send message in format below via the PubNub Dev Console to troubleshoot app -- {'msg':'id,opcode,data'} -------------------------------------------------------------------------------------------------- -- Pubnub class Pubnub = {} --************************************************************************************************ -- constructor function Pubnub:new(parm) -------------------------------------------------------------------------------------------------- local self = {} ---------------------------------------------------------------- self.name = 'PubnubNetwork' self.mainChannel = 'serval' --self.myChannel = self.id self.curChannel = self.mainChannel self.isRoomCreator = false ---------------------------------------------------------------- -- Initiate Multiplayer PubNub Object -- This initializes the pubnub networking layer. self.pnObj = pubnub.new({ subscribe_key = 'sub-c-d80638dc-6ac7-11e2-ae8f-12313f022c90', publish_key = 'pub-c-ee663362-0c59-4e8e-9071-29d178553ae5', secret_key = nil, ssl = nil, origin = 'pubsub.pubnub.com', }) --**************************************************** -- open network connection to pubnub self.connect = function () local thisFunc = 'connect' if (dbg) then dbg.func(thisFile, thisFunc) end if (dbg) then dbg.func(thisFile, thisFunc, 'Connecting... '..self.pnObj.uuid) end self.pnObj:subscribe({ channel = self.curChannel, connect = function() dbg.out(thisFile, thisFunc, 'Connected: '..self.curChannel..' '..self.pnObj.uuid) end, callback = function(message) self.receive(message.msg) end, errorback = function() dbg.out(thisFile, thisFunc, 'Oh no!!! Dropped 3G Conection!') end }) end --**************************************************** -- close connection to pubnub self.disconnect = function () local thisFunc = 'disconnect' if (dbg) then dbg.func(thisFile, thisFunc) end self.pnObj:unsubscribe({channel = self.curChannel}) if (dbg) then dbg.out(thisFile, thisFunc, 'disconnected') end end --**************************************************** -- send message self.send = function (fCode, fData) local thisFunc = 'send' if (dbg) then dbg.func(thisFile, thisFunc) end local text = self.pnObj.uuid..','..fCode..','..fData self.pnObj:publish({ channel = self.curChannel, --message = { msgtext = text }, message = { msg = text }, callback = function(info) end }) if (dbg) then dbg.out(thisFile, thisFunc, self.curChannel..' '..fCode..' '..fData) end end --**************************************************** -- filter and execute incoming ops if from opponent self.receive = function (fCode) local thisFunc = 'receive' if (dbg) then dbg.func(thisFile, thisFunc) end local op = {} op = util.split(fCode,',') if (op[1] == pn.pnObj.uuid) then -- opcode from me if (dbg) then dbg.out(thisFile, thisFunc, 'MyID '..op[1]..' '..op[2]..' '..op[3]) end if(op[2] == 'saveRoom') then db.updateConfig('roomName',op[1]) db.updateConfig('roomID',op[3]) db.showConfig() sb.gotoScene('startMenu') else if (dbg) then dbg.out(thisFile, thisFunc, 'ERROR: Unknown opcode in decodeOp()') end end else -- opcode not from me if (dbg) then dbg.out(thisFile, thisFunc, 'NotMyID '..op[1]..' '..op[2]..' '..op[3]) end if(op[2] == 'joinRoom' and self.isRoomCreator) then if (dbg) then dbg.out(thisFile, thisFunc, 'Executing GuestOp: '..op[1]..' '..op[2]..' '..op[3]) end self.isRoomCreator = false self.send( 'saveRoom', self.createChannelID() ) elseif(op[2] == 'saveRoom') then db.updateConfig('roomName',op[1]) db.updateConfig('roomID',op[3]) db.showConfig() sb.gotoScene('startMenu') else if (dbg) then dbg.out(thisFile, thisFunc, 'ERROR: Unknown opcode in decodeOp()') end end end end --**************************************************** self.createChannelID = function() ------------------ local thisFunc = 'createChannelID' if (dbg) then dbg.func(thisFile, thisFunc) end ------------------ local chars = {'-','_','0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'} local temp = {} for i=1,128 do temp[i] = chars[math.random (64)] end local ret = table.concat(temp) return ret end --**************************************************** self.createRoomID = function() ------------------ local thisFunc = 'createRoomID' if (dbg) then dbg.func(thisFile, thisFunc) end ------------------ local chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','m','n','o','p','q','r','s','t','u','v','w','x','y','z'} -- l removed local temp = {} for i=1,6 do temp[i] = chars[math.random (35)] end local ret = table.concat(temp) return ret end --**************************************************** return self end local obj = Pubnub:new() obj.uuid = obj.pnObj.UUID() obj.pnObj.uuid = db.getConfigColumn('userName')..'_'..db.getConfigColumn('uuid') return obj
apache-2.0
zlua/zLua
luasocket3.0/test/mimetest.lua
44
8413
local socket = require("socket") local ltn12 = require("ltn12") local mime = require("mime") local unpack = unpack or table.unpack dofile("testsupport.lua") local qptest = "qptest.bin" local eqptest = "qptest.bin2" local dqptest = "qptest.bin3" local b64test = "b64test.bin" local eb64test = "b64test.bin2" local db64test = "b64test.bin3" -- from Machado de Assis, "A Mão e a Rosa" local mao = [[ Cursavam estes dois moços a academia de S. Paulo, estando Luís Alves no quarto ano e Estêvão no terceiro. Conheceram-se na academia, e ficaram amigos íntimos, tanto quanto podiam sê-lo dois espíritos diferentes, ou talvez por isso mesmo que o eram. Estêvão, dotado de extrema sensibilidade, e não menor fraqueza de ânimo, afetuoso e bom, não daquela bondade varonil, que é apanágio de uma alma forte, mas dessa outra bondade mole e de cera, que vai à mercê de todas as circunstâncias, tinha, além de tudo isso, o infortúnio de trazer ainda sobre o nariz os óculos cor-de-rosa de suas virginais ilusões. Luís Alves via bem com os olhos da cara. Não era mau rapaz, mas tinha o seu grão de egoísmo, e se não era incapaz de afeições, sabia regê-las, moderá-las, e sobretudo guiá-las ao seu próprio interesse. Entre estes dois homens travara-se amizade íntima, nascida para um na simpatia, para outro no costume. Eram eles os naturais confidentes um do outro, com a diferença que Luís Alves dava menos do que recebia, e, ainda assim, nem tudo o que dava exprimia grande confiança. ]] local function random(handle, io_err) if handle then return function() if not handle then error("source is empty!", 2) end local len = math.random(0, 1024) local chunk = handle:read(len) if not chunk then handle:close() handle = nil end return chunk end else return ltn12.source.empty(io_err or "unable to open file") end end local function named(f) return f end local what = nil local function transform(input, output, filter) local source = random(io.open(input, "rb")) local sink = ltn12.sink.file(io.open(output, "wb")) if what then sink = ltn12.sink.chain(filter, sink) else source = ltn12.source.chain(source, filter) end --what = not what ltn12.pump.all(source, sink) end local function encode_qptest(mode) local encode = mime.encode("quoted-printable", mode) local split = mime.wrap("quoted-printable") local chain = ltn12.filter.chain(encode, split) transform(qptest, eqptest, chain) end local function compare_qptest() io.write("testing qp encoding and wrap: ") compare(qptest, dqptest) end local function decode_qptest() local decode = mime.decode("quoted-printable") transform(eqptest, dqptest, decode) end local function create_qptest() local f, err = io.open(qptest, "wb") if not f then fail(err) end -- try all characters for i = 0, 255 do f:write(string.char(i)) end -- try all characters and different line sizes for i = 0, 255 do for j = 0, i do f:write(string.char(i)) end f:write("\r\n") end -- test latin text f:write(mao) -- force soft line breaks and treatment of space/tab in end of line local tab f:write(string.gsub(mao, "(%s)", function(c) if tab then tab = nil return "\t" else tab = 1 return " " end end)) -- test crazy end of line conventions local eol = { "\r\n", "\r", "\n", "\n\r" } local which = 0 f:write(string.gsub(mao, "(\n)", function(c) which = which + 1 if which > 4 then which = 1 end return eol[which] end)) for i = 1, 4 do for j = 1, 4 do f:write(eol[i]) f:write(eol[j]) end end -- try long spaced and tabbed lines f:write("\r\n") for i = 0, 255 do f:write(string.char(9)) end f:write("\r\n") for i = 0, 255 do f:write(' ') end f:write("\r\n") for i = 0, 255 do f:write(string.char(9),' ') end f:write("\r\n") for i = 0, 255 do f:write(' ',string.char(32)) end f:write("\r\n") f:close() end local function cleanup_qptest() os.remove(qptest) os.remove(eqptest) os.remove(dqptest) end -- create test file local function create_b64test() local f = assert(io.open(b64test, "wb")) local t = {} for j = 1, 100 do for i = 1, 100 do t[i] = math.random(0, 255) end f:write(string.char(unpack(t))) end f:close() end local function encode_b64test() local e1 = mime.encode("base64") local e2 = mime.encode("base64") local e3 = mime.encode("base64") local e4 = mime.encode("base64") local sp4 = mime.wrap() local sp3 = mime.wrap(59) local sp2 = mime.wrap("base64", 30) local sp1 = mime.wrap(27) local chain = ltn12.filter.chain(e1, sp1, e2, sp2, e3, sp3, e4, sp4) transform(b64test, eb64test, chain) end local function decode_b64test() local d1 = named(mime.decode("base64"), "d1") local d2 = named(mime.decode("base64"), "d2") local d3 = named(mime.decode("base64"), "d3") local d4 = named(mime.decode("base64"), "d4") local chain = named(ltn12.filter.chain(d1, d2, d3, d4), "chain") transform(eb64test, db64test, chain) end local function cleanup_b64test() os.remove(b64test) os.remove(eb64test) os.remove(db64test) end local function compare_b64test() io.write("testing b64 chained encode: ") compare(b64test, db64test) end local function identity_test() io.write("testing identity: ") local chain = named(ltn12.filter.chain( named(mime.encode("quoted-printable"), "1 eq"), named(mime.encode("base64"), "2 eb"), named(mime.decode("base64"), "3 db"), named(mime.decode("quoted-printable"), "4 dq") ), "chain") transform(b64test, eb64test, chain) compare(b64test, eb64test) os.remove(eb64test) end local function padcheck(original, encoded) local e = (mime.b64(original)) local d = (mime.unb64(encoded)) if e ~= encoded then fail("encoding failed") end if d ~= original then fail("decoding failed") end end local function chunkcheck(original, encoded) local len = string.len(original) for i = 0, len do local a = string.sub(original, 1, i) local b = string.sub(original, i+1) local e, r = mime.b64(a, b) local f = (mime.b64(r)) if (e .. (f or "") ~= encoded) then fail(e .. (f or "")) end end end local function padding_b64test() io.write("testing b64 padding: ") padcheck("a", "YQ==") padcheck("ab", "YWI=") padcheck("abc", "YWJj") padcheck("abcd", "YWJjZA==") padcheck("abcde", "YWJjZGU=") padcheck("abcdef", "YWJjZGVm") padcheck("abcdefg", "YWJjZGVmZw==") padcheck("abcdefgh", "YWJjZGVmZ2g=") padcheck("abcdefghi", "YWJjZGVmZ2hp") padcheck("abcdefghij", "YWJjZGVmZ2hpag==") chunkcheck("abcdefgh", "YWJjZGVmZ2g=") chunkcheck("abcdefghi", "YWJjZGVmZ2hp") chunkcheck("abcdefghij", "YWJjZGVmZ2hpag==") print("ok") end local function test_b64lowlevel() io.write("testing b64 low-level: ") local a, b a, b = mime.b64("", "") assert(a == "" and b == "") a, b = mime.b64(nil, "blablabla") assert(a == nil and b == nil) a, b = mime.b64("", nil) assert(a == nil and b == nil) a, b = mime.unb64("", "") assert(a == "" and b == "") a, b = mime.unb64(nil, "blablabla") assert(a == nil and b == nil) a, b = mime.unb64("", nil) assert(a == nil and b == nil) local binary=string.char(0x00,0x44,0x1D,0x14,0x0F,0xF4,0xDA,0x11,0xA9,0x78,0x00,0x14,0x38,0x50,0x60,0xCE) local encoded = mime.b64(binary) local decoded=mime.unb64(encoded) assert(binary == decoded) print("ok") end local t = socket.gettime() create_b64test() identity_test() encode_b64test() decode_b64test() compare_b64test() cleanup_b64test() padding_b64test() test_b64lowlevel() create_qptest() encode_qptest() decode_qptest() compare_qptest() encode_qptest("binary") decode_qptest() compare_qptest() cleanup_qptest() print(string.format("done in %.2fs", socket.gettime() - t))
mit
AdamGagorik/darkstar
scripts/zones/Windurst_Walls/npcs/Four_of_Diamonds.lua
13
1062
----------------------------------- -- Area: Windurst Walls -- NPC: Four of Diamonds -- Type: Standard NPC -- @zone: 239 -- @pos -187.184 -3.545 151.092 -- -- 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(0x010b); 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/Qufim_Island/npcs/Pitoire_RK.lua
13
3326
----------------------------------- -- Area: Qufim Island -- NPC: Pitoire, R.K. -- Type: Outpost Conquest Guards -- @pos -245.366 -20.344 299.502 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
D-m-L/evonara
modules/entities/miner.lua
1
3630
local ent = {} function ent:load( x, y, w, h, size ) self.chance = 0 self.x, self.y = x or 0, y or 0 self.active = true --math.randomseed(love.timer.getTime()) --self.dir = math.random(1,8) --self.dir = math.random(2946) % 4 self.size, self.tilesize = size or 1, size or 2 self.parent = nil end function ent:setParent( parent ) self.parent = parent end function ent:dig(parent) -- cave = self.parent local cave = parent if self.active == true then self.parent.chance = math.random(1000) self.parent.dir = math.random(1,4) self.x, self.y = maths.clamp(self.x, 2, cave.width - 1), maths.clamp(self.y, 2, cave.height - 1) -- delete square of size n local n = self.size if cave.data[self.y][self.x] == 1 then self.x = maths.clamp(self.x, 1 + n, cave.width - n) self.y = maths.clamp(self.y, 1 + n, cave.height - n) --cave.data[self.y][self.x] = 0 cave.nscoops = cave.nscoops + 1 for y = 1, n do for x = 1, n do cave.data[math.floor(self.y + y - n/2)][math.floor(self.x + x - n/2)] = 0 cave.nscoops = cave.nscoops + 1 end end end if self.parent.dir == 1 and cave.data[self.y-self.size][self.x] == 1 then self.y = self.y - self.size elseif self.parent.dir == 2 and cave.data[self.y][self.x+self.size] == 1 then self.x = self.x + self.size elseif self.parent.dir == 3 and cave.data[self.y+self.size][self.x] == 1 then self.y = self.y + self.size elseif self.parent.dir == 4 and cave.data[self.y][self.x-self.size] == 1 then self.x = self.x - self.size end self.x, self.y = maths.clamp(self.x, 2, cave.width - 1), maths.clamp(self.y, 2, cave.height - 1) -- If we have less than X many miners, there is a chance a new miner will be born if cave.activeminers < 1000 then if self.parent.chance <= 50 then local randx, randy = math.random(-self.size,self.size), math.random(-self.size,self.size) local newx, newy = maths.clamp(self.x + randx, 2, cave.width - 1), maths.clamp(self.y + randy, 2, cave.height - 1) -- cave.numminers = cave.numminers + 1 -- cave.miners[cave.numminers]:init(newx, newy, 0, 0, 1) cave:createMiner(newx, newy) end end if cave.data[self.y+1][self.x] == 0 and cave.data[self.y-1][self.x] == 0 and cave.data[self.y][self.x+1] == 0 and cave.data[self.y][self.x-1] == 0 then -- IF THERE'S NOTHING NEARBY if cave.activeminers == 1 then -- IF WE'RE THE LAST MINER local n = 1 local randx, randy = love.math.random(-self.size,self.size), love.math.random(-n,n) self.x, self.y = maths.clamp(self.x + randx, 1+n, cave.width - n), maths.clamp(self.y + randy, 1 + n, cave.height - n) else self:deactivate() end end if cave.activeminers > 1 then if self.y == 2 then self:deactivate() elseif self.y == cave.height - 1 then self:deactivate() elseif self.x == 2 then self:deactivate() elseif self.x == cave.width - 1 then self:deactivate() end end end end function ent:deactivate() self.active = false self.parent.activeminers = self.parent.activeminers - 1 end function ent:setPos( x, y ) self.x = x self.y = y end function ent:setSize( size ) self.size = size end function ent:draw() if self.active == true then lg.setColor(255,0,0,255) lg.setLineWidth(1) love.graphics.rectangle("line", self.x * self.parent.tilesize, self.y * self.parent.tilesize, self.size * self.parent.tilesize, self.size * self.parent.tilesize) end end return ent
mit
sjznxd/lc-20130204
applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
apache-2.0
AdamGagorik/darkstar
scripts/zones/Bastok_Mines/npcs/Rashid.lua
13
3699
----------------------------------- -- Area: Bastok Mines -- NPC: Rashid -- Type: Mission Giver -- @pos -8.444 -2 -123.575 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local CurrentMission = player:getCurrentMission(BASTOK); local Count = trade:getItemCount(); if (CurrentMission ~= 255) then if (CurrentMission == FETICHISM and player:hasCompletedMission(BASTOK,FETICHISM) == false and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then player:startEvent(0x03F0); -- Finish Mission "Fetichism" (First Time) elseif (CurrentMission == FETICHISM and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then player:startEvent(0x03ED); -- Finish Mission "Fetichism" (Repeat) elseif (CurrentMission == TO_THE_FORSAKEN_MINES and player:hasCompletedMission(BASTOK,TO_THE_FORSAKEN_MINES) == false and trade:hasItemQty(563,1) and Count == 1) then player:startEvent(0x03F2); -- Finish Mission "To the forsaken mines" (First Time) elseif (CurrentMission == TO_THE_FORSAKEN_MINES and trade:hasItemQty(563,1) and Count == 1) then player:startEvent(0x03EE); -- Finish Mission "To the forsaken mines" (Repeat) end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() ~= BASTOK) then player:startEvent(0x03eb); -- For non-Bastokian else local CurrentMission = player:getCurrentMission(BASTOK); local cs, p, offset = getMissionOffset(player,1,CurrentMission,player:getVar("MissionStatus")); if (cs ~= 0 or offset ~= 0 or ((CurrentMission == 0 or CurrentMission == 16) and offset == 0)) then if (CurrentMission <= 15 and cs == 0) then player:showText(npc,ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 1~5) elseif (CurrentMission > 15 and cs == 0) then player:showText(npc,EXTENDED_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 6~10) else player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]); end elseif (player:getRank() == 1 and player:hasCompletedMission(BASTOK,THE_ZERUHN_REPORT) == false) then player:startEvent(0x03E8); -- Start First Mission "The Zeruhn Report" elseif (CurrentMission ~= 255) then player:startEvent(0x03EA); -- Have mission already activated else local flagMission, repeatMission = getMissionMask(player); player:startEvent(0x03E9,flagMission,0,0,0,0,repeatMission); -- Mission List 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); finishMissionTimeline(player,1,csid,option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Upper_Jeuno/npcs/Laila.lua
6
10576
----------------------------------- -- Area: Upper Jeuno -- NPC: Laila -- Type: Job Quest Giver -- @zone: 244 -- @pos -54.045 -1 100.996 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) --TODO-- -- make sure the surrounding npcs react to the player accordingly after each quest. There are a few event IDs that I don't recall using -- make global variables for all these event hexvalues and put them in textids --TODO-- ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local lakesideMin = player:getQuestStatus(JEUNO,LAKESIDE_MINUET); local lakeProg = player:getVar("Lakeside_Minuet_Progress"); if (lakesideMin == QUEST_AVAILABLE and player:getMainLvl() >= ADVANCED_JOB_LEVEL and ENABLE_WOTG == 1) then player:startEvent(0x277f); -- Start quest csid, asks for Key Item Stardust Pebble elseif (lakesideMin == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x2787); elseif (player:hasKeyItem(STARDUST_PEBBLE)) then player:startEvent(0x2786); -- Ends Quest elseif (lakeProg == 3) then player:startEvent(0x2781); elseif (lakesideMin == QUEST_ACCEPTED) then player:startEvent(0x2780) -- After accepting, reminder elseif ((player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_AVAILABLE or (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED and player:hasItem(19203)==false)) and player:getMainJob()==JOB_DNC and player:getMainLvl()>=40) then player:startEvent(0x2791); elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED and player:getVar("QuestStatus_DNC_AF1")==5 and player:seenKeyItem(THE_ESSENCE_OF_DANCE) and player:getMainJob()==JOB_DNC) then player:startEvent(0x2795); elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED) then player:startEvent(0x2796); --Dancer AF: The Road to Divadom-- elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_ROAD_TO_DIVADOM) == QUEST_AVAILABLE and player:getMainJob()==JOB_DNC) then player:startEvent(0x2798); -- CSID 10136 elseif (player:getVar("roadToDivadomCS") == 1) then player:startEvent(0x2799); -- quest chat line after the quest has been accepted elseif (player:getVar("roadToDivadomCS") == 4) then player:startEvent(0x279B); --CSID 10139 elseif (player:getVar("roadToDivadomCS") == 5) then player:startEvent(0x27BA); --CSID 10170. This should only occur if the player's inventory was full during the chain of events that start in the elseif above. --Dancer AF: Comeback Queen-- elseif (player:getQuestStatus(JEUNO,THE_ROAD_TO_DIVADOM) == QUEST_COMPLETED and player:getQuestStatus(JEUNO, COMEBACK_QUEEN) == QUEST_AVAILABLE and player:getMainJob()==JOB_DNC) then player:startEvent(0x279F); elseif (player:getVar("comebackQueenCS") == 1) then player:startEvent(0x27A0); -- quest chat line after quest accepted; Rhea and Olgald have a line as well. elseif (player:getVar("comebackQueenCS") == 2) then player:startEvent(0x27A3); elseif (player:getVar("comebackQueenCS") == 3 or player:getVar("comebackQueenCS") == 6) then local currentVanaDay = VanadielDayOfTheYear(); if (player:getVar("comebackQueenDanceOffTimer") < currentVanaDay) then player:startEvent(0x27A7); -- play laila cs 10152->10154 olgald: 1053 if they lose the minigame else player:startEvent(0x279C); end; elseif (player:getVar("comebackQueenCS") == 4 or player:getVar("comebackQueenCS") == 5) then player:startEvent(0x27AA); --This occurs if the player's inventory was full during the final chain of events or if the player speaks with laila afterwards. else player:startEvent(0x2788); -- Default 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 == 0x277f and option == 1) then player:addQuest(JEUNO,LAKESIDE_MINUET); elseif (csid == 0x2786) then player:setVar("Lakeside_Minuet_Progress",0); player:completeQuest(JEUNO,LAKESIDE_MINUET); player:addTitle(TROUPE_BRILIOTH_DANCER); player:unlockJob(19); player:messageSpecial(UNLOCK_DANCER); player:addFame(JEUNO, 30); player:delKeyItem(STARDUST_PEBBLE); player:needToZone(true); elseif (csid==0x2791) then if (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED) then player:delQuest(JEUNO,THE_UNFINISHED_WALTZ); player:delKeyItem(THE_ESSENCE_OF_DANCE); end player:addQuest(JEUNO,THE_UNFINISHED_WALTZ); player:setVar("QuestStatus_DNC_AF1", 1); elseif (csid==0x2795) then player:setVar("QuestStatus_DNC_AF1", 0); player:addItem(19203); -- war hoop player:messageSpecial(ITEM_OBTAINED,19203); player:completeQuest(JEUNO,THE_UNFINISHED_WALTZ); --Dancer AF: The Road to Divadom-- elseif (csid == 0x2798) then -- Road To Divadom pt 1 player:setVar("roadToDivadomCS", 1); player:addQuest(JEUNO, THE_ROAD_TO_DIVADOM); elseif (csid == 0x279B) then -- string of events player:startEvent(0x27E6); elseif (csid == 0x27E6) then player:startEvent(0x27E7); elseif (csid == 0x27E7) then player:setVar("roadToDivadomCS", 5); player:startEvent(0x27BA); elseif (csid == 0x27BA) then if (player:getFreeSlotsCount() == 0) then --do nothing. player doesn't have room to receive the reward item. player:messageSpecial( ITEM_CANNOT_BE_OBTAINED, 15660); -- the names of the gender specific items are the same else player:completeQuest(JEUNO, THE_ROAD_TO_DIVADOM); player:setVar("roadToDivadomCS", 0); player:setVar("dancerTailorCS", 1); -- allows player to start dancer version of Coffer AF. check Olgald and Matthias(@Bastok Markets) for the rest of the quest line --determine what gender the player is so we can give the correct item local playerGender = player:getGender(); local dancersTights = 15660 - playerGender; player:addItem(dancersTights); player:messageSpecial(ITEM_OBTAINED, dancersTights); player:completeQuest(JEUNO, THE_ROAD_TO_DIVADOM); end; --Dancer AF: Comeback Queen -- elseif (csid == 0x279F) then player:setVar("comebackQueenCS", 1); player:addQuest(JEUNO, COMEBACK_QUEEN); player:addKeyItem(WYATTS_PROPOSAL); player:messageSpecial( KEYITEM_OBTAINED, WYATTS_PROPOSAL); elseif (csid == 0x27A3) then player:setVar("comebackQueenCS", 3); local danceOffTimer = VanadielDayOfTheYear(); player:setVar("comebackQueenDanceOffTimer", danceOffTimer); elseif (csid == 0x27A7) then --the dance off minigame if (option > 0) then -- player won the minigame player:startEvent(0x27E0); -- starts exhausting string of events else player:setVar("comebackQueenCS", 6); -- have surrounding npcs use losing state CS local danceOffTimer = VanadielDayOfTheYear(); player:setVar("comebackQueenDanceOffTimer", danceOffTimer); end; elseif (csid == 0x27E0) then player:startEvent(0x27E1); elseif (csid == 0x27E1) then player:startEvent(0x27E2); elseif (csid == 0x27E2) then player:setVar("comebackQueenCS", 4); player:startEvent(0x27E3); elseif (csid == 0x27E3) then --finally reward the player if (player:getFreeSlotsCount() == 0) then --do nothing. player doesn't have room to receive the reward item. player:messageSpecial( ITEM_CANNOT_BE_OBTAINED, 14578); -- the names of the gender specific items are the same else player:completeQuest(JEUNO, COMEBACK_QUEEN); player:setVar("comebackQueenCS", 5); -- final state for all of the surrounding NPCs --determine what gender the player is so we can give the correct item local playerGender = player:getGender(); local dancersCasaque = 14579 - playerGender; player:addItem(dancersCasaque); player:messageSpecial(ITEM_OBTAINED, dancersCasaque); player:completeQuest(JEUNO, COMEBACK_QUEEN); end; elseif (csid == 0x27AA) then if (player:getVar("comebackQueenCS") == 4) then -- player's inventory was full at the end of the final cutscene if (player:getFreeSlotsCount() == 0) then --do nothing. player doesn't have room to receive the reward item. player:messageSpecial( ITEM_CANNOT_BE_OBTAINED, 14578); -- the names of the gender specific items are the same else player:completeQuest(JEUNO, COMEBACK_QUEEN); player:setVar("comebackQueenCS", 5); -- final state for all of the surrounding NPCs --determine what gender the player is so we can give the correct item local playerGender = player:getGender(); local dancersCasaque = 14579 - playerGender; player:addItem(dancersCasaque); player:messageSpecial(ITEM_OBTAINED, dancersCasaque); player:completeQuest(JEUNO, COMEBACK_QUEEN); end; --the surrounding NPCs should have their dialogue check comebackqueenCS as well. end; end; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Al_Zahbi/npcs/Taten-Bilten.lua
13
1179
----------------------------------- -- Area: Al Zahbi -- NPC: Taten-Bilten -- Guild Merchant NPC: Clothcraft Guild -- @pos 71.598 -6.000 -56.930 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(60430,6,21,0)) then player:showText(npc,TATEN_BILTEN_SHOP_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); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Ranguemont_Pass/npcs/Perchond.lua
13
1699
----------------------------------- -- Area: Ranguemont Pass -- NPC: Perchond -- @pos -182.844 4 -164.948 166 ----------------------------------- package.loaded["scripts/zones/Ranguemont_Pass/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1107,1) and trade:getItemCount() == 1) then -- glitter sand local SinHunting = player:getVar("sinHunting"); -- RNG AF1 if (SinHunting == 2) then player:startEvent(0x0005); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SinHunting = player:getVar("sinHunting"); -- RNG AF1 if (SinHunting == 1) then player:startEvent(0x0003, 0, 1107); else player:startEvent(0x0002); 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 == 3) then player:setVar("sinHunting",2); elseif (csid == 5) then player:tradeComplete(); player:addKeyItem(PERCHONDS_ENVELOPE); player:messageSpecial(KEYITEM_OBTAINED,PERCHONDS_ENVELOPE); player:setVar("sinHunting",3); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Pashhow_Marshlands/npcs/Tahmasp.lua
13
1904
----------------------------------- -- Area: Pashhow Marshlands -- NPC: Tahmasp -- Type: Outpost Vendor -- @pos 464 24 416 109 ----------------------------------- package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Pashhow_Marshlands/TextIDs"); local region = DERFLAND; local csid = 0x7ff4; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
ObsidianGuardian/xenia
tools/build/scripts/test_suite.lua
10
2547
include("build_paths.lua") include("util.lua") newoption({ trigger = "test-suite-mode", description = "Whether to merge all tests in a test_suite into a single project", value = "MODE", allowed = { { "individual", "One binary per test." }, { "combined", "One binary per test suite (default)." }, }, }) local function combined_test_suite(test_suite_name, project_root, base_path, config) group("tests") project(test_suite_name) kind("ConsoleApp") language("C++") includedirs(merge_arrays(config["includedirs"], { project_root.."/"..build_tools, project_root.."/"..build_tools_src, project_root.."/"..build_tools.."/third_party/catch/include", })) libdirs(merge_arrays(config["libdirs"], { project_root.."/"..build_bin, })) links(merge_arrays(config["links"], { "gflags", })) files({ project_root.."/"..build_tools_src.."/test_suite_main.cc", base_path.."/**_test.cc", }) end local function split_test_suite(test_suite_name, project_root, base_path, config) local test_paths = os.matchfiles(base_path.."/**_test.cc") for _, file_path in pairs(test_paths) do local test_name = file_path:match("(.*).cc") group("tests/"..test_suite_name) project(test_suite_name.."-"..test_name) kind("ConsoleApp") language("C++") includedirs(merge_arrays(config["includedirs"], { project_root.."/"..build_tools, project_root.."/"..build_tools_src, project_root.."/"..build_tools.."/third_party/catch/include", })) libdirs(merge_arrays(config["libdirs"], { project_root.."/"..build_bin, })) links(merge_arrays(config["links"], { "gflags", })) files({ project_root.."/"..build_tools_src.."/test_suite_main.cc", file_path, }) end end -- Defines a test suite binary. -- Can either be a single binary with all tests or one binary per test based on -- the --test-suite-mode= option. function test_suite( test_suite_name, -- Project or group name for the entire suite. project_root, -- Project root path (with build_tools/ under it). base_path, -- Base source path to search for _test.cc files. config) -- Include/lib directories and links for binaries. if _OPTIONS["test-suite-mode"] == "individual" then split_test_suite(test_suite_name, project_root, base_path, config) else combined_test_suite(test_suite_name, project_root, base_path, config) end end
bsd-3-clause
FH3095/RollBot
RollTimerWindow.lua
1
1940
local RB = RollBot local log = FH3095Debug.log local DEFAULT_POS = { LEFT = { relativePoint = "TOP", xOfs = 0, yOfs = -100, }, WndHeight = 100, WndWidth = 150, } local function cancelTimer() local vars = RB.vars.rollTimeWindowVars if vars.timerId ~= nil then log("RollTimeWindow: Cancel Timer") RB.timers:CancelTimer(vars.timerId) vars.timerId = nil vars.rollTimeText = nil vars.rollTimeWindow:ReleaseChildren() vars.rollTimeWindow:Hide() vars.rollTimeWindow = nil end end local function timerFunc() local vars = RB.vars.rollTimeWindowVars vars.timerCounter = vars.timerCounter - 1 vars.timerLabel:SetText(tostring(vars.timerCounter)) if vars.timerCounter <= 0 then if RB:isMyselfMasterLooter() then RB:sendChatMessage(RB.db.profile.rollFinishChatMsg) end cancelTimer() end end local function createCounterText(frame) local vars = RB.vars.rollTimeWindowVars local text = RB.gui:Create("Label") text:SetText(RB.vars.lastRoll.rollTime) text:SetFontObject(GameFontNormalLarge) frame:AddChild(text) vars.timerCounter = RB.vars.lastRoll.rollTime vars.timerLabel = text vars.rollTimeWindow = frame vars.timerId = RB.timers:ScheduleRepeatingTimer(timerFunc, 1) end function RB:openRollTimerWindowAndStart() if self.vars.lastRoll.rollTime <= 0 then return end log("StartRollTimer") cancelTimer() -- Create a container frame local f = self.vars.rollTimeWindowVars.guiFrame if f ~= nil then f:Show() else f = self.gui:Create("Window") f:SetCallback("OnClose",function(widget) RB.db.char.windowPositions.rollTimeWindow = RB:getWindowPos(widget, true) cancelTimer() widget:ReleaseChildren() widget:Hide() end) f:SetTitle(self.l["ROLL_TIME_WINDOW_NAME"]) f:SetLayout("Fill") f:EnableResize(false) self:restoreWindowPos(f, self.db.char.windowPositions.rollTimeWindow, DEFAULT_POS) self.vars.rollTimeWindowVars.guiFrame = f end createCounterText(f) end
gpl-3.0
chfg007/skynet
test/testmongodb.lua
62
2661
local skynet = require "skynet" local mongo = require "mongo" local bson = require "bson" local host, db_name = ... function test_insert_without_index() local db = mongo.client({host = host}) db[db_name].testdb:dropIndex("*") db[db_name].testdb:drop() local ret = db[db_name].testdb:safe_insert({test_key = 1}); assert(ret and ret.n == 1) local ret = db[db_name].testdb:safe_insert({test_key = 1}); assert(ret and ret.n == 1) end function test_insert_with_index() local db = mongo.client({host = host}) db[db_name].testdb:dropIndex("*") db[db_name].testdb:drop() db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"}) local ret = db[db_name].testdb:safe_insert({test_key = 1}) assert(ret and ret.n == 1) local ret = db[db_name].testdb:safe_insert({test_key = 1}) assert(ret and ret.n == 0) end function test_find_and_remove() local db = mongo.client({host = host}) db[db_name].testdb:dropIndex("*") db[db_name].testdb:drop() db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"}) local ret = db[db_name].testdb:safe_insert({test_key = 1}) assert(ret and ret.n == 1) local ret = db[db_name].testdb:safe_insert({test_key = 2}) assert(ret and ret.n == 1) local ret = db[db_name].testdb:findOne({test_key = 1}) assert(ret and ret.test_key == 1) local ret = db[db_name].testdb:find({test_key = {['$gt'] = 0}}):sort({test_key = -1}):skip(1):limit(1) assert(ret:count() == 2) assert(ret:count(true) == 1) if ret:hasNext() then ret = ret:next() end assert(ret and ret.test_key == 1) db[db_name].testdb:delete({test_key = 1}) db[db_name].testdb:delete({test_key = 2}) local ret = db[db_name].testdb:findOne({test_key = 1}) assert(ret == nil) end function test_expire_index() local db = mongo.client({host = host}) db[db_name].testdb:dropIndex("*") db[db_name].testdb:drop() db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index", expireAfterSeconds = 1, }) db[db_name].testdb:ensureIndex({test_date = 1}, {expireAfterSeconds = 1, }) local ret = db[db_name].testdb:safe_insert({test_key = 1, test_date = bson.date(os.time())}) assert(ret and ret.n == 1) local ret = db[db_name].testdb:findOne({test_key = 1}) assert(ret and ret.test_key == 1) for i = 1, 1000 do skynet.sleep(11); local ret = db[db_name].testdb:findOne({test_key = 1}) if ret == nil then return end end assert(false, "test expire index failed"); end skynet.start(function() test_insert_without_index() test_insert_with_index() test_find_and_remove() test_expire_index() print("mongodb test finish."); end)
mit
nerdclub-tfg/telegram-bot
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
r1k/vlc
share/lua/modules/dkjson.lua
95
25741
--[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.1* This module writes no global values, not even the module table. Import it using json = require ("dkjson") Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This is mainly useful for tables that can be empty. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.1"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the functions `quotestring` and `decode`. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable this option: --]==] local always_try_using_lpeg = true --[==[ In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. You can contact the author by sending an e-mail to 'kolf' at the e-mail provider 'gmx.de'. --------------------------------------------------------------------- *Copyright (C) 2010, 2011 David Heiko Kolf* 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. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall = error, require, pcall local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local concat = table.concat local common = require ("common") local us_tostring = common.us_tostring if _VERSION == 'Lua 5.1' then local function noglobals (s,k,v) error ("global access: " .. k, 2) end setfenv (1, setmetatable ({}, { __index = noglobals, __newindex = noglobals })) end local _ENV = nil -- blocking globals in Lua 5.2 local json = { version = "dkjson 2.1" } pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = us_tostring (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local metatype = valmeta and valmeta.__jsontype local isa, n if metatype == 'array' then isa = true n = value.n or #value elseif metatype == 'object' then isa = false else isa, n = isarray (value) end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 1 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = tonumber (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end function json.decode (str, pos, nullval, objectmeta, arraymeta) objectmeta = objectmeta or {__jsontype = 'object'} arraymeta = arraymeta or {__jsontype = 'array'} return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") local pegmatch = g.match local P, S, R, V = g.P, g.S, g.R, g.V local SpecialChars = (R"\0\31" + S"\"\\\127" + P"\194" * (R"\128\159" + P"\173") + P"\216" * R"\128\132" + P"\220\132" + P"\225\158" * S"\180\181" + P"\226\128" * (R"\140\143" + S"\168\175") + P"\226\129" * R"\160\175" + P"\239\187\191" + P"\229\191" + R"\176\191") / escapeutf8 local QuoteStr = g.Cs (g.Cc "\"" * (SpecialChars + 1)^0 * g.Cc "\"") quotestring = function (str) return pegmatch (QuoteStr, str) end json.quotestring = quotestring local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/tonumber local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, objectmeta, arraymeta) local state = { objectmeta = objectmeta or {__jsontype = 'object'}, arraymeta = arraymeta or {__jsontype = 'array'} } local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0